Q: Looking for testing matrices/systems for iterative linear solver I am currently working on a C++-based library for large, sparse linear algebra problems (yes, I know many such libraries exist, but I'm rolling my own mostly to learn about iterative solvers, sparse storage containers, etc..).
I am to the point where I am using my solvers within other programming projects of mine, and would like to test the solvers against problems that are not my own.  Primarily, I am looking to test against symmetric sparse systems that are positive definite.  I have found several sources for such system matrices such as:
Matrix Market
UF Sparse Matrix Collection
That being said, I have not yet found any sources of good test matrices that include the entire system- system matrix and RHS.  This would be great to have in order to check results.  Any tips on where I can find such full systems, or alternatively, what I might do to generate a "good" RHS for the system matrices I can get online?  I am currently just filling a matrix with random values, or all ones, but suspect that this is not necessarily the best way.

A: I would suggest using a right-hand-side vector obtained from a predefined 'goal' solution x:
b = A*x

Then you have a goal solution, x, and a resulting solution, x, from the solver.
This means you can compare the error (difference of the goal and resulting solutions) as well as the residuals (A*x - b).
Note that for careful evaluation of an iterative solver you'll also need to consider what to use for the initial x.
The online collections of matrices primarily contain the left-hand-side matrix, but some do include right-hand-sides and also some have solution vectors too.:
http://www.cise.ufl.edu/research/sparse/matrices/rhs.txt
By the way, for the UF sparse matrix collection I'd suggest this link instead:
http://www.cise.ufl.edu/research/sparse/matrices/

A: I haven't used it yet, I'm about to, but GiNAC seems like the best thing I've found for C++. It is the library used behind Maple for CAS, I don't know the performance it has for .
http://www.ginac.de/

A: it would do well to specify which kind of problems are you solving...
different problems will require different RHS to be of any use to check validity..... what i'll suggest is get some example code from some projects like DUNE Numerics (i'm working on this right now), FENICS, deal.ii which are already using the solvers to solve matrices... generally they'll have some functionality to output your matrix in some kind of file (DUNE Numerics has functionality to output matrices and RHS in a matlab-compliant files).
This you can then feed to your solvers..
and then again use their the libraries functionality to create output data
(like DUNE Numerics uses a VTK format)... That was, you'll get to analyse data using powerful tools.....
you may have to learn a little bit about compiling and using those libraries...
but it is not much... and i believe the functionality you'll get would be worth the time invested......
i guess even a single well-defined and reasonably complex problem should be good enough for testing your libraries.... well actually two
one for Ax=B problems and another for Ax=cBx (eigenvalue problems) ....


Q: How to jump a commit in the same branch at git Suppose I'm in the branch develop.
I'm in commit (A) and I do some bad things and make another commit (B).
Supposing that undoing the bad things I did is a very painful job, how can I manage to put another commit ahead of (B) in the same branch develop?
CURRENT STATE:
 _______________________________________
|develop|   (A) ----> (B)
 ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾

WHAT I IMAGINE:
 _______________________________________
|develop|   (A) ----> (B)       (D)
 ‾‾‾‾‾‾‾‾‾‾‾‾|‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
             |                   |
 _______________________________|______
|bugfix |   (C) -----------------'
 ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾

I have no intention of merging, since I don't want to utilize (B). I also cannot erase (B), so doing  force push isn't an option.
What should I do in this situation?
If there is a way to put a new commit (ahead of (B)) whose state is equal to (A), this would be also an acceptable solution.

A: You can 'revert' B.  This effectively creates a new commit which 'undoes' the changes made by B.  This works with one bad commit or a whole series of bad commits.


Q: Chrome mobile browser cross domain request Issue I am using pure JavaScript to make cross domain post request. Its working for all the desktop browser including Chrome. However request is getting failed with statusCode: 0 in the chrome mobile browser.
function MakeAJAXRequest(jsonData){
   var ajaxRequest = new window.XMLHttpRequest();
   ajaxRequest.onload = function () { . . . };
   ajaxRequest.onreadystatechange = function () { . . . };
   ajaxRequest.onerror = function () {. . . };
   ajaxRequest.ontimeout = function () { . . .};
   ajaxRequest.open("POST", 'https://someotherdomain.com/myservice/postSomeData', true);
   ajaxRequest.send(jsonData);
}

Any help would be much appreciated.
PS: I am getting the correct response in default android browser.
Thanks.


Q: Primeng12 Table with virtual scroll + lazyload + checkbox selection I have an old v12 angular/primeng based app that I am trying to retro fit checkbox selections on a table with virtual scrolling and lazy loading. I can initially toggle to select all the visible rows, but when performing a scroll to lazy load more items, the main checkbox header control doesnt stay selected, and the new rows that appear dont get marked as checked either.
https://stackblitz.com/edit/angular-zavyn1?file=src/app/app.module.ts
I know I am on an older primeng version, just wondering if there are any workarounds to get this functionality behaving, I did consider implementing my own checkbox selection behaviour, but that seems overkill.
I see this was tracked in an issue here which has since been fixed from v13 onwards in this commit I believe. Wondering if there is a way to override the methods on the table\checkbox header instance for the table in my stackblitz example above and bring in the patch fixes?

A: I'm sorry for making a wrong assumption before. The behavior you described is how it should work.
The current version is not working as they implemented it wrong, so ver 12 won't work. Detail: https://github.com/primefaces/primeng/issues/10697
But the new version is working as expected. I just forked the link from the homepage and make some changes. You can see the forked link here:
https://stackblitz.com/edit/primeng-tablevirtualscroll-demo-p2j757?file=src/app/app.component.ts
Your original code also missed the part where you need to listen for the select/click event on the header.
If you wanted to "fix" the issue in the old version, you can just copy the patch from the new version. The code is under updateCheckedState


Q: nginx refuses connections after some time I have a problem with my nginx configuration, my server works fine but after 1 or 2 days it just hangs and stop responding. It's not possible to connect to the server anymore.
(7) Failed to connect to XX.XX.XX.XX port 80: Connection refused

The main job of this server is running heavy PHP tasks, I run cron jobs every 5 seconds for many tasks. Restart helps and again nginx works correctly for the next 1-2 days. I don't have any error logs, nginx dosn't report anything in /var/log/nginx/error.log. It simply fails all connections. Any ideas where to start looking for a problem?
I run nginx on Ubuntu 16.04, 2 CPUs, 4 GB ram with PHP 7.0.
nginx version: nginx/1.10.0 (Ubuntu)
here is config file:
 user www-data;
 worker_processes 2;
 pid /run/nginx.pid;

 events {
  worker_connections 4096;
  #multi_accept on;
 }

http {

##
# Basic Settings
##

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 300;
types_hash_max_size 2048;
server_tokens off;

# server_names_hash_bucket_size 64;
# server_name_in_redirect off;

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

##
# SSL Settings
##

ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;

##
# Logging Settings
##

access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;

##
# Gzip Settings
##

gzip on;
gzip_disable "msie6";

# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

##
# Virtual Host Configs
##

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}

here is default file:
server {
 large_client_header_buffers 4 128k;
 listen XX:XX:XX:XX:80;

 set $root_path '/var/www/web/public/';

 root $root_path;
 index index.php;

 server_name XX:XX:XX:XX;

 location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ /index.php?$query_string;
 }

 location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    fastcgi_read_timeout 14400;

    proxy_set_header   Connection "";
    proxy_http_version 1.1;
 }

 location /status {
        stub_status on;
        access_log  off;
        allow XX:XX:XX:XX;
        deny all;
 }

 location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
    root $root_path;
 }

 # deny access to .htaccess files, if Apache's document root
 # concurs with nginx's one
 location ~ /\.ht {
    deny all;
 }
}

And the main thing, my cron jobs I run, for example:
* * * * * sleep 5; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 10; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 15; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 20; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 25; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 30; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 35; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 40; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 45; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 50; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1

etc.
UPDATE:
PHP FPM Status
 * php7.0-fpm.service - The PHP 7.0 FastCGI Process Manager
   Loaded: loaded (/lib/systemd/system/php7.0-fpm.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2017-01-13 10:46:41 CET; 3 days ago
  Process: 1439 ExecStartPre=/usr/lib/php/php7.0-fpm-checkconf (code=exited, status=0/SUCCESS)
 Main PID: 1662 (php-fpm7.0)
   Status: "Processes active: 0, idle: 25, Requests: 164215, slow: 0, Traffic: 0req/sec"
    Tasks: 26
   Memory: 377.3M
      CPU: 5h 57min 32.279s
   CGroup: /system.slice/php7.0-fpm.service
           |- 1662 php-fpm: master process (/etc/php/7.0/fpm/php-fpm.conf)
           |- 1752 php-fpm: pool www
           |- 8751 php-fpm: pool www
           |-12078 php-fpm: pool www
           |-14053 php-fpm: pool www
           |-14338 php-fpm: pool www
           |-14639 php-fpm: pool www
           |-14763 php-fpm: pool www
           |-16188 php-fpm: pool www
           |-16212 php-fpm: pool www
           |-16900 php-fpm: pool www
           |-17620 php-fpm: pool www
           |-17621 php-fpm: pool www
           |-17766 php-fpm: pool www
           |-18802 php-fpm: pool www
           |-19084 php-fpm: pool www
           |-22064 php-fpm: pool www
           |-24245 php-fpm: pool www
           |-24690 php-fpm: pool www
           |-25120 php-fpm: pool www
           |-27714 php-fpm: pool www
           |-29415 php-fpm: pool www
           |-30182 php-fpm: pool www
           |-30391 php-fpm: pool www
           |-32053 php-fpm: pool www
           `-32358 php-fpm: pool www

Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.

A: I would check php fpm logs. Maybe running out of php fpm processes.


Q: Screen layout doesn't look good on bigger screens I have 3 horizontal LinearLayouts, I've been making xml on 4.7 screen and it looked good, then i switched to bigger screen and it doesnt look good. So my xml looks good on screen size of 4.7 but on 10.01 and 7 it screws up
on 4.7 screen:

on 10,01 :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/backgroun"
    android:orientation="vertical"
  >

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="horizontal" >

     <Button
         android:id="@+id/button1"
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:layout_weight="1"
         android:text="Load" />

     <Button
         android:id="@+id/button2"
         android:layout_width="wrap_content"
        android:layout_height="match_parent"
         android:text="Play"
         android:layout_weight="1" />

     <Button
         android:id="@+id/button3"
         android:layout_width="wrap_content"
        android:layout_height="match_parent"
         android:text="Mute"
         android:layout_weight="1"/>

     <Button
         android:id="@+id/button4"
         android:layout_width="wrap_content"
        android:layout_height="match_parent"
         android:text="Volume up"
         android:layout_weight="1" />

     <Button
         android:id="@+id/button5"
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:text="Volume up"
         android:layout_weight="1" />

     <Button
         android:id="@+id/button6"
         android:layout_width="wrap_content"
        android:layout_height="match_parent"
         android:text="Mute"
         android:layout_weight="1"/>

     <Button
         android:id="@+id/button7"
         android:layout_width="wrap_content"
        android:layout_height="match_parent"
         android:text="Play"
         android:layout_weight="1"/>

     <Button
         android:id="@+id/button8"
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:text="Load"
         android:layout_weight="1" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:orientation="horizontal" >

        <SeekBar
            android:id="@+id/seekBar1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="7"/>

        <Button
            android:id="@+id/button9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button" />

        <Button
            android:id="@+id/button10"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button" />

        <SeekBar
            android:id="@+id/seekBar2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
             android:layout_weight="7"/>

    </LinearLayout>
     <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal" >

         <SeekBar
             android:id="@+id/seekBar3"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:layout_weight="1" />

         <SeekBar
             android:id="@+id/seekBar4"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:layout_weight="1" />

    </LinearLayout>

    </LinearLayout>

A: First of all when you use android:layout_weight you should set the android:layout_width="0dp"
Besides that now, I would suggest having a separate layout for xlarge screens. The way to do that is to create a separate folder that will contain a layout with the same name as your original layout (eg. main.xml). The folder name for 10" screens should be something like layout-xlarge. For more details you should check here.

A: For different size screens. you can also make another layout for bigger screen.
res/layout-small
res/layout-large
res/layout-xlarge
create a new folder as named "layout-xlarge" and copy your xml layout in there and you can adjust the sizes.
Android will automatically select the appropriate layout for the current device. Remember that, layout name should be the same in each folder.


Q: How to post php variables in swf? I have in test.php this:
$domain = $_GET['domain'];
$user = $_GET['user'];

and in my Action Script i have:
getURL("http://test.com/file.php?domain=?&user=?", "_blank");

How do get variables from php and put in my swf?
I'm beginner in flash!!!

A: To send variables from flash to PHP:
//Actionscript:
loadVariables ("test.php?myVariable=" + myFlashVar , _root);

//PHP can retrieve it using
$myVar = $_GET['myVariable'];

To send from PHP to flash, use exactly the same:
//Actionscript:
loadVariables ("test.php?" , _root);

//PHP:
echo "&myVariable=hello";

//Now in your flash movie, _root.myVariable will be equal to 'hello'

I hope this is enough to get you started :)


Q: Connect android to database I am doing a school project where we need to create an android application which needs to connect to a database. the application needs to gain and store information for people's profiles on the database. But unfortunatly we are a little bit stuck at this point because there are numerous ways to link the application such as http request through apache or through the SOAP/REST protocol.
But it's really hard to find good instructions or tutorials on the problem since I can't really find them. Maybe that's cause i'm probably using the wrong words on google. Unfortunately I have little relevant information. So if anyone can help me with finding relevant links to good online tutorials or howto's than those are very welcome.

A: I'd recommend using REST and JSON to communicate to a PHP script running on Apache.  Don't worry about the database on the Android side of things, just focus on what kinds of queries you might need to make and what data you need returned.  Then put together a PHP script to take those queries and generate the necessary SQL to query the database on the server.  For example, You need look look up a person by name and show their address in your Android app.  A REST Query is just a simple HTTP GET to request data.  For example, to look up John Smith, you might request: http://www.example.org/lookup.php?name=John+Smith which will return a short JSON snippet generated by PHP:
{
    name: "John Smith",
    address: "1234 N Elm St.",
    city: "New York",
    state: "New York"
}

You can instruct PHP to use the content type text/plain by putting this at the top of your PHP script:

Then you can just navigate to the above URL in your browser and see your JSON response printed out nicely as a page.  There should be a good JSON parser written in Java out there you can use with Android.  Hopefully, this will get you started.

A: This tutorial really helped me: http://www.screaming-penguin.com/node/7742


Q: Reload page with anchor after submit I have a big form in PHP with several tables, each of one calculates a sum (of price and quantity) and then there's one at the end that calculates the total.
The structure is, more or less, this:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="purchase_form">

            <input id="price_1">
            <input id="quantity_1">

            <input type="submit" name="calculate" value="Click here to calculate the partial">

            <input id="price_2">
            <input id="quantity_2">

            <input type="submit" name="calculate" value="Click here to calculate the partial">

        <?php *script* ?>
        <?php *script* ?>

</form>

Now, when I click on submit to calculate the "partial", it gives me the total, at the same time. I know it's not a state-of-the-art form, but anyway, just try to turn a blind eye on that.
What I want is, when I click on submit button, to have the page reloaded showing the form I have clicked on. Like, if I click on submit of the #purchase_1 table, I want the page to reload on #purchase_1 table, and so on.
Is it possible to do that with javascript?


Q: Swift NSPredicate filtering using set operations I'm trying to filter such that criteria is met for each AND every item in a set vice each OR every item.
If I use groceryItem IN %@, desiredGroceries, it acts like an OR statement.
Example:  I'm trying to return all grocery lists of groceryItems that included milk AND eggs (desiredGroceries=Set("Milk", "Eggs")).
If I use the above code, it returns all lists that included milk as well as lists that included eggs.
But I only want the lists that include BOTH milk and eggs.
What's the correct Predicate for this?
UPDATE:
From the Willeke's comments, I tried using .@count==%lu
This works if each groceryList only has one item.  However, if it has multiple items, I see inconsistent results when showing groceryLists.  Sometimes the filter works, other times it reports nothing.


Q: Python: Files assigned variable path not printing or editing I have most of the program done. The last part of this program needs to open the file in append mode> Add 2 names > close file. Then, it has to open file in read mode> print contents> close file.
The file path has been assigned to a variable.
I keep getting the below error. (code is below that)
I don't know what to do to fix this
Traceback (most recent call last):
File "C:\Users\gorri\Desktop\College Work\CPT180_ShellScripting\Assignments\Programs\workWithFiles2.py", line 34, in
cat_files = open(cat_files, 'a')
TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper
from pathlib import Path
import os
import os.path

path_E = Path('E:/CPT180Stuff')
os.chdir(path_E)

cat_files = (path_E / 'pets' / 'cats' / 'catnames.txt')

    #opens catnames file to append end and add names.
    cat_files = open(cat_files, 'a')
    cat_files.write('Princess\nFreya\n')
    cat_files.close()
    cat_files = open(cat_files, 'r')
    cat_files = cat_files.read()
    print(cat_files)
    cat_files.close()

A: In your current code, you are first assigning cat_files to the file name, but then in this line:
cat_files = open(cat_files, 'r')

You are now assigning cat_files to a file handle, which is not a string. This is why the next statement fails: it is expecting the filename string,  not the file handle. You should use a different variable name for the handle, e.g.:
#opens catnames file to append end and add names.
f = open(cat_files, 'a')
f.write('Princess\nFreya\n')
f.close()
f = open(cat_files, 'r')
f = f.read()
print(f)
f.close()


Q: Change colorpicker for nicedit.js to photoshop like I want to change the default color picker for nicedit.js
While going through the js file, I can see that the below code is generating the color-picker. Data is set up using colorList variable. Can anyone please help me to get a color-picker like photoshop or more relavant.
var nicEditorColorButton = nicEditorAdvancedButton.extend({
  addPane : function() {
      var colorList = {0 : '00',1 : '33',2 : '66',3 :'99',4 : 'CC',5 : 'FF'};
      var colorItems = new bkElement('DIV').setStyle({width: '270px'});

      for(var r in colorList) {
        for(var b in colorList) {
          for(var g in colorList) {
            var colorCode = '#'+colorList[r]+colorList[g]+colorList[b];

            var colorSquare = new bkElement('DIV').setStyle({'cursor' : 'pointer', 'height' : '15px', 'float' : 'left'}).appendTo(colorItems);
            var colorBorder = new bkElement('DIV').setStyle({border: '2px solid '+colorCode}).appendTo(colorSquare);
            var colorInner = new bkElement('DIV').setStyle({backgroundColor : colorCode, overflow : 'hidden', width : '11px', height : '11px'}).addEvent('click',this.colorSelect.closure(this,colorCode)).addEvent('mouseover',this.on.closure(this,colorBorder)).addEvent('mouseout',this.off.closure(this,colorBorder,colorCode)).appendTo(colorBorder);

            if(!window.opera) {
              colorSquare.onmousedown = colorInner.onmousedown = bkLib.cancelEvent;
            }

          }
        }
      }
      this.pane.append(colorItems.noSelect());
  }
});

A: I would change the colorList to array containing photoshop hex values and then use it like this:
var nicEditorColorButton = nicEditorAdvancedButton.extend({
  addPane : function() {
  var colorList = {0 : '000000',1 : 'FFFFFF'};  /* here goes color list */
  var colorItems = new bkElement('DIV').setStyle({width: '270px'});

  for(var g in colorList) {
    var colorCode = '#'+colorList[g];
    var colorSquare = new bkElement('DIV').setStyle({'cursor' : 'pointer', 'height' : '15px', 'float' : 'left'}).appendTo(colorItems);
    var colorBorder = new bkElement('DIV').setStyle({border: '2px solid '+colorCode}).appendTo(colorSquare);
    var colorInner = new bkElement('DIV').setStyle({backgroundColor : colorCode, overflow : 'hidden', width : '11px', height : '11px'}).addEvent('click',this.colorSelect.closure(this,colorCode)).addEvent('mouseover',this.on.closure(this,colorBorder)).addEvent('mouseout',this.off.closure(this,colorBorder,colorCode)).appendTo(colorBorder);

    if(!window.opera) {
      colorSquare.onmousedown = colorInner.onmousedown = bkLib.cancelEvent;
    }

  }
  this.pane.append(colorItems.noSelect());
}});

Not sure if my code is edited correctly but you get the basic idea. Remove 2 for loops and loop within the colorList directly


Q: Setting Apollo client header dynamically is not working I am trying to set the header of Apollo client dynamically according to official doc, but I am getting an error:
    TypeError: (0 , _apollo.default) is not a function

This is my apollo.js
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { AsyncStorage } from 'react-native';

const httpLink = createHttpLink({
    uri: 'http://192.168.2.4:8000/api/',
});

const authLink = setContext((_, { headers }) => {
    const token = AsyncStorage.getItem('token');

    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : "",
        }
    }
});

const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
});

export default client;

UPDATE
I am adding App.js:
import { ApolloProvider } from 'react-apollo';
import Routes from './app/config/routes';
import makeApolloClient from './app/config/apollo';

export default function App() {
  const client = makeApolloClient();

  return (
    <ApolloProvider client={client}>
      <Routes />
    </ApolloProvider>);
}

How can I solve this issue?

A: makeApolloClient isnt a function, the file just exports an instance of the apollo client. Just import it as if it's a variable.
import client from './app/config/apollo'

export default function App() {
    return (
        <ApolloProvider client={client}>
          <Routes />
        </ApolloProvider>
    );
}

A:
Storing JWT in local storage and session storage is not secure!
Use cookie with http-only enabled!

This code automatically reads and sets Authorization header after localStorage.setItem('jwt_token', jwt_token) in SignIn mutation.
import {ApolloClient, createHttpLink} from "@apollo/client";
import {setContext} from "@apollo/client/link/context";
import {InMemoryCache} from "@apollo/client";

const apolloHttpLink = createHttpLink({
    uri: process.env.REACT_APP_APOLLO_SERVER_URI || 'http://localhost/graphql',
})

const apolloAuthContext = setContext(async (_, {headers}) => {
    const jwt_token = localStorage.getItem('jwt_token')
    return {
        headers: {
            ...headers,
            Authorization: jwt_token ? `Bearer ${jwt_token}` : ''
        },
    }
})

export const apolloClient = new ApolloClient({
    link: apolloAuthContext.concat(apolloHttpLink),
    cache: new InMemoryCache(),
})

A: Apollo usequery has a context option that allows you to dynamically change or update the values of the header object.
import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
  cache: new InMemoryCache(),
  uri: "/graphql"
});

client.query({
  query: MY_QUERY,
  context: {
    // example of setting the headers with context per operation
    headers: {
      special: "Special header value"
    }
  }
});

The code above was copied from the Apollo docs.
To find out more check out  https://www.apollographql.com/docs/react/networking/advanced-http-networking/#overriding-options

A: Try this
const authLink = setContext(async (_, { headers }) => {
    const token = await AsyncStorage.getItem('token');

    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : "",
        }
    }
});

A: In React Native, AsyncStorage methods are async not like localStorage in Web. And the other methods doesn't work, except this.
https://github.com/apollographql/apollo-client/issues/2441#issuecomment-718502308


Q: how to load data fast from webservice in android? Am access data from web service,but when moving from one activity to other its showing black screen till that get loaded then its displaying my activity.
how to avoid black screen and access data fast?
code:
JSONObject json = getJSONfromURL(url);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();is =entity.getContent();

A: Here is a AsyncTask example - http://www.vogella.com/articles/AndroidPerformance/article.html
Here is a Progress dialogue example - http://www.vogella.com/articles/AndroidDialogs/article.html
should get you started in the right direction.

A: Use Asynchronous Task to display progress dialog when it is performing parsing. do in background method write all code that you perform and the on post method show result.


Q: Navigate user to particular message in channel upon clicking a button in Personal Chat adaptive card I am sending a message to the user using an Adaptive card. With the click of a button, I would like to redirect the user to a particular message in the channel. Is there any way we can achieve this?

A: On click of button you can add a deeplink of message in channel
Use below deep link format to navigate to a particular conversation within channel thread:
https://teams.microsoft.com/l/message//?tenantId=&groupId=&parentMessageId=&teamName=&channelName=&createdTime=
Example: https://teams.microsoft.com/l/message//1648741500652?tenantId=&groupId=&parentMessageId=1648741500652&teamName=&channelName=&createdTime=1648741500652
Ref Doc: https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/deep-links?tabs=teamsjs-v2#generate-deep-links-to-channel-conversation


Q: Project compiles on Ubuntu but not on Debian I have a strange problem where one of my projects is compiling just fine on Ubuntu 22.04 and Windows but gives a strange linker error on Debian bullseye even with the same gcc and cmake versions.
On Debian I get this linker error here:
#16 953.5 `_ZN5boost4asio12async_resultINS0_15use_awaitable_tINS0_15any_io_executorEEEJFvNS_6system10error_codeEmEEE8initiateEPZNS8_8initiateINS0_6detail36initiate_async_write_buffer_sequenceINS0_19basic_stream_socketINS0_2ip3tcpES3_EEEEJSt5arrayINS0_12const_bufferELm4EENSA_14transfer_all_tEEEENS0_9awaitableImS3_EET_S4_DpT0_E305_ZN5boost4asio12async_resultINS0_15use_awaitable_tINS0_15any_io_executorEEEJFvNS_6system10error_codeEmEEE8initiateINS0_6detail36initiate_async_write_buffer_sequenceINS0_19basic_stream_socketINS0_2ip3tcpES3_EEEEJSt5arrayINS0_12const_bufferELm4EENSA_14transfer_all_tEEEENS0_9awaitableImS3_EET_S4_DpT0_.Frame.destroy' referenced in section `.rodata.cst8' of src/gw2cc/Release/libgw2cc_lib.a(SecureTokenServerClient.cpp.o): defined in discarded section `.text._ZN5boost4asio12async_resultINS0_15use_awaitable_tINS0_15any_io_executorEEEJFvNS_6system10error_codeEmEEE8initiateEPZNS8_8initiateINS0_6detail36initiate_async_write_buffer_sequenceINS0_19basic_stream_socketINS0_2ip3tcpES3_EEEEJSt5arrayINS0_12const_bufferELm4EENSA_14transfer_all_tEEEENS0_9awaitableImS3_EET_S4_DpT0_E305_ZN5boost4asio12async_resultINS0_15use_awaitable_tINS0_15any_io_executorEEEJFvNS_6system10error_codeEmEEE8initiateINS0_6detail36initiate_async_write_buffer_sequenceINS0_19basic_stream_socketINS0_2ip3tcpES3_EEEEJSt5arrayINS0_12const_bufferELm4EENSA_14transfer_all_tEEEENS0_9awaitableImS3_EET_S4_DpT0_.Frame.destroy[_ZN7network6socks56socketIN5boost4asio19basic_stream_socketINS3_2ip3tcpENS3_15any_io_executorEEEE10do_connectERKNS5_14basic_endpointIS6_EERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESL_]' of src/gw2cc/Release/libgw2cc_lib.a(SecureTokenServerClient.cpp.o)

The project is using vcpkg to download and build all dependencies. Would be great if somebody could tell me what is causing this. All Linux compilations were done in a clean docker image with just the necessary dependencies installed. I even tried different gcc versions on Debian without any success.


Q: In which scenario I should use IS(Information Service) Parameters or SS(Solution Sets) Parameters in 3gpp notifications I am reading through the 3gpp ts for notifications like notifyNewAlarm, where I see IS Parameters and SS Parameters, unsure which one to use and the sample data for the fields, Please help me with some starting point.
Difference is
IS Parameters is with "objectClass" and "objectInstance" fields
SS Parameters is with "href".
I have figured out the sample data for IS Parameters. If you have any for IS parameter, please comment.


Q: What is the difference between ForAll and Select in PLINQ In the intro to PLINQ, the docs seem to show two different ways of getting data back from a process unordered.  In one case, AsParallel can be used with Unsorted and the Select or SelectMany method.  SelectMany says it

Projects in parallel each element of a sequence to an IEnumerable
  and flattens the resulting sequences into one sequence.

So to get a return list from a function, I call it like this:
def genGraph(node,constData):
    #do something
    return (constData+1,constData+2,constData+3)

newGraph = Graph.AsParallel().SelectMany(lambda node: genGraph(node,constData) ).ToList()

The other way would be using ForAll and a ConcurrentBag that is added to, and nothing returned.

For faster query execution when order preservation is not required and
  when the processing of the results can itself be parallelized, use the
  ForAll method to execute a PLINQ query.

def genGraph(node,constData,newGraph):
    #do something
    newGraph.Add(constData+1,constData+2,constData+3)

newGraph = Concurrent.ConcurrentBag[type((0,0,0))]()
Graph.AsParallel().ForAll(lambda node: genGraph(node,constData,newGraph) )

So the first one says it projects in parallel to an IEnumerable, and the second one says it is faster when processing can be parallelized.  It sounds to me the same thing. In my code, it currently runs the same amount of time as well, but I am wondering if there is some other case I am not understanding.


Q: How to append objects on a file in Java? I'm trying to make a small program inJava in which I need to save An array of objects on a file. I was looking for how to do this and I found the next code:
    //this is the array that will be stored
    private Atributtes list[]=new Atributtes [100];

    /*
    this is the way i save the data in the array,i always save them in
    index 0,and i made a for to put away the previous data because always
    there will have data in index 0
    */

    for (int i = totalElments; i>0; i--){
    list[i] = list[i-1];
    }

    list[0]=new Atributtes ("Atributtes data");
    save.storeInfile(list);
    totalElments++;

private static final String filename="file.obj";

public void storeInfile(Object array[]){
    try{
        FileOutputStream file= new FileOutputStream(filename,true);
        ObjectOutputStream object= new ObjectOutputStream(file);
        object.writeObject(array);
        object.close();
        file.close();
        System.out.println("recording successfully");
        System.out.println("-----------------------------------");
    }catch(Exception exceccao){
        System.out.println("recording wasn't successfull");
    }
}

My problem now is that when I want to save the same Array of objects but with another data,or when I reopen the file, the first data that was in the file is overwritten.
Note1:i was said to put the true boolean on FileoutPutSTream,but when i put it the recording doesn't happen anymore,but when i remove the true boolean the recording happens but with overwritten data always.
Note2: I've read about FileWriter and the PrintWriter, but I need to write only Objects, not Strings.thanks!!!!
Could someone tell how to append this new data on the file?
Thank you.

A: Change this line
FileOutputStream file= new FileOutputStream(filename);

to this
FileOutputStream file= new FileOutputStream(filename, true)

The true stands for append enable or disable. In default it is disabled.


Q: How can I efficiently concatenate multiple Arduino Strings? I was looking for an Arduino way of efficiently concatenating strings. I was looking for something like std::format(" {} blah blah {}", str1, str2);
I don't want to do something that will be slow such as
" " + str1 + " blah blah " + str2.

A: There is already a concat function.
myString.concat(parameter);

You can use it as that. Reference: Arduino Official Link


Q: Test a Spring multipart/form-data controller with uploading of some files I am trying to test this controller:
@RequestMapping(value="/u",consumes="multipart/form-data", method = RequestMethod.POST)
public @ResponseBody String register(
    @RequestParam String u,
    @RequestParam CommonsMultipartFile filea,
    @RequestParam CommonsMultipartFile fileb,
    @RequestParam CommonsMultipartFile filec,
    @RequestParam CommonsMultipartFile filed) {

    return "hi";
}

Whit this mock of a request:
mockMvc.perform(
    MockMvcRequestBuilders.fileUpload("/u")
        .file("filea","id.jpg".getBytes())
        .file("fileb","pc.jpg".getBytes())
        .file("filec","cl.jpg".getBytes())
        .file("filed","fo.jpg".getBytes())
        .param("u", u))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andDo(MockMvcResultHandlers.print());

Although, I guess I am writing the MockMvcRequest wrongly because the test fails (the status returned is 500).
Thanks in advance.

A: The issue is a very small one - just change your CommonsMultipartFile to MultipartFile and your test should run through cleanly.
The reason for this issue is the mock file upload parameter that is created is a MockMultipartFile which cannot be cast to the more specific CommonsMultipartFile type.

A: The simple way how to test multipart upload is use StandardServletMultipartResolver.
and for test use this code:
    final MockPart profilePicture = new MockPart("profilePicture", "stview.jpg", "image/gif", "dsdsdsd".getBytes());
    final MockPart userData = new MockPart("userData", "userData", "application/json", "{\"name\":\"test aida\"}".getBytes());

    this.mockMvc.perform(
            fileUpload("/endUsers/" + usr.getId().toString()).with(new RequestPostProcessor() {

                @Override
                public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
                    request.addPart(profilePicture);
                    request.addPart(userData);
                    return request;
                }
            })

MockPart class
public class MockPart extends MockMultipartFile implements Part {

private Map<String, String> headers;

public MockPart(String name, byte[] content) {
    super(name, content);
    init();
}

public MockPart(String name, InputStream contentStream) throws IOException {
    super(name, contentStream);
    init();
}

public MockPart(String name, String originalFilename, String contentType, byte[] content) {
    super(name, originalFilename, contentType, content);
    init();
}

public MockPart(String name, String originalFilename, String contentType, InputStream contentStream) throws IOException {
    super(name, originalFilename, contentType, contentStream);
    init();
}

public void init() {
    this.headers = new HashMap<String, String>();
    if (getOriginalFilename() != null) {
        this.headers.put("Content-Disposition".toLowerCase(), "form-data; name=\"" + getName() + "\"; filename=\"" + getOriginalFilename() + "\"");
    } else {
        this.headers.put("Content-Disposition".toLowerCase(), "form-data; name=\"" + getName() + "\"");
    }
    if (getContentType() != null) {
        this.headers.put("Content-Type".toLowerCase(), getContentType());
    }
}

@Override
public void write(String fileName) throws IOException {
}

@Override
public void delete() throws IOException {
}

@Override
public String getHeader(String name) {
    return this.headers.get(name.toLowerCase());
}

@Override
public Collection<String> getHeaders(String name) {
    List<String> res = new ArrayList<String>();
    if (getHeader(name) != null) {
        res.add(getHeader(name));
    }
    return res;
}

@Override
public Collection<String> getHeaderNames() {
    return this.headers.keySet();
}

}


Q: How to use Clutter.ShaderEffect.set_uniform_value() properly? I am trying set a uniform float of a Clutter.ShaderEffect. This works well if floating point Numbers are passed to set_uniform_value(). However, when you pass an integer Number, an OpenGL  error (1282, Invalid operation) is thrown. It seems that the implementation assumes in this case that the uniform is actually of type int. Here is a minimal example:
const {Clutter, GObject} = imports.gi;

Clutter.init(null);

let stage  = new Clutter.Stage({width: 200, height: 200});
let shader = new Clutter.ShaderEffect({shader_type: Clutter.ShaderType.FRAGMENT_SHADER});

shader.set_shader_source(`
  uniform float value;

  void main(void) {
    cogl_color_out = vec4(value, 0, 0, 1);
  }
`);

// This creates the OpenGL Error.
// shader.set_uniform_value('value', 1);

// This works however:
shader.set_uniform_value('value', 0.999);

stage.add_effect(shader);

stage.connect('destroy', () => Clutter.main_quit());
stage.show();

Clutter.main();

So how do I force set_uniform_value() to interpret the value as floating point number? Reading the documentation (https://gjs-docs.gnome.org/clutter6~6_api/clutter.shadereffect#method-set_uniform_value), I would assume that I could pass a GObject.Value - maybe like this:
let value = new GObject.Value();
value.init(GObject.TYPE_FLOAT);
value.set_float(1.0);
shader.set_uniform_value('value', value);

But this yields the error Invalid uniform of type 'GValue' for name 'value'. Maybe I now have a GObject.Value containing a GObject.Value containing a GObject.TYPE_FLOAT?

A: if someone looks for this question, I have the answer:
https://gjs-docs.gnome.org/clutter7~7_api/clutter.shadereffect#method-set_uniform_value value - a GObject.Value GObject.TYPE_FLOAT for float
and in gjs GTK Javascript they have https://gjs-docs.gnome.org/clutter7~7_api/clutter.value_set_shader_float
value_set_shader_float(value,[float]) method - Value must have been initialized using %CLUTTER_TYPE_SHADER_FLOAT.
and in Javascript version of GTK they dont have any way to initialize that CLUTTER_TYPE_SHADER_FLOAT or GObject.TYPE_FLOAT
The solution is:
function make_float(val) {
    return Math.floor(val)==val?val+0.000001:val;
}

A: As of GJS 1.68.0 (GNOME 40), passing a GObject.Value works:
let value = new GObject.Value();
value.init(GObject.TYPE_FLOAT);
value.set_float(1);
shader.set_uniform_value('value', value);


Q: How to register trigger in PostgreSQL? I have trigger and procedure. I want to be sure that string saved to database will have no '-' characters.
After executing
UPDATE interesant SET interesant_nip = '555-555-5555'

I get error

value is too long for varchar(10).

This suggests that '-' characters were not removed before insert-update.
Why is my trigger not being executed?
CREATE FUNCTION normalize_nip() RETURNS TRIGGER AS $$
BEGIN
    -- replace '' to NULL
    IF (NEW.interesant_nip LIKE '') THEN
        NEW.interesant_nip := NULL;
        RETURN NEW;
    END IF;

    -- remove '-' from string
    NEW.interesant_nip := REPLACE(NEW.interesant_nip, '-', '');

    RETURN NEW;
END; $$ LANGUAGE plpgsql;"

CREATE TRIGGER interesant_nip_normalize BEFORE INSERT OR UPDATE ON public.interesant FOR EACH ROW EXECUTE PROCEDURE normalize_nip()

A: The updated or inserted value is always treated as type varchar(10) - before and after the trigger function. So, you cannot handle the value because the input type does not fit the value even if the trigger function converts it into a valid one.
It works if you have an unbounded text type. There you can see that the trigger is executed:
demo:db<>fiddle

So, the only chance to handle this, is, to normalize it before inserting or updating:
demo:db<>fiddle
INSERT INTO interesant VALUES (normalize_nip('555-555-5555'));

UPDATE interesant SET interesant_nip = normalize_nip('555-555-5555')


Q: Two list element wise comparison using filter I have two lists of numbers:
l1 = [12, 3, 4, 5, 7]
l2 = [ 6, 8, 4, 2, 4]

I want to retrieve all the elements from l1 that are bigger than the elements from l2 (element-wise comparison)
So far I only achieved
results = list(map(operator.gt,l1,l2)

Which returns me a [True,False,...] list. But I want the values itself.
I would like to do it without any for loop thanks. I was thinking about filter() or itertools()
Thanks

A: you can use a list comprehension:
[a for a, b in zip(l1, l2) if a > b]

or you can use:
from operator import gt, itemgetter

list(map(itemgetter(1), filter(itemgetter(0), zip(map(gt, l1, l2), l1))))


Q: UI Multitouch Architecture? I am developing a game with multitouch controllers. But I have problems with UI Image multi touching
I want to create this architecture.

*

*Green Cycles will work as button. (Touch End)

*Red Cycle will work as a button.I need touch move or touch stay events for serial shoting. (Touch Move | Touch Stay)

*Yellow Box will work as a touchpad(UI Image Element). When finger moves over the box, It will trigger to Rotate method.
I tried some methods but all is failed.
I created a class named MultiTouchElement.
var touches = Input.touches;
for (int i = 0; i < touches.Count; i++)
{
    Touch touch = Input.GetTouch(i);
    TouchPhase phase = touch.phase;

    PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
    eventDataCurrentPosition.position = touch.position;

    List<RaycastResult> results = new List<RaycastResult>();
    EventSystem.current.RaycastAll(eventDataCurrentPosition, results);

    var touchOnThisObject = results.Any(x => x.gameObject.name.ToLower() == this.gameObject.name.ToLower());
    if (!touchOnThisObject)
        return;

    if (phase == TouchPhase.Began)
    {
        this.GetComponent<Image>().color = Color.red;
    }
    if (phase == TouchPhase.Ended)
    {
        this.GetComponent<Image>().color = Color.blue;
    }
}

Are there any tutorial for my architecture?

A: I found solution :)
Thank you Bro @IsGreen
Source : http://forum.unity3d.com/threads/solved-raycast-multitouch-input-convert-local-recttransform-rect-to-screen-position.318115/
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;

public class UImageRayCast : MonoBehaviour
{
Image image;
Color colorOn, colorOff;

void Start()
{
    this.image = this.GetComponent<Image>();
    this.colorOff = this.image.color;
    this.colorOn = new Color(this.colorOff.r, this.colorOff.g, this.colorOff.b, this.colorOff.a * 0.5f);
}

void Update()
{

    this.image.color = this.colorOff;

    PointerEventData pointer = new PointerEventData(EventSystem.current);
    List<RaycastResult> raycastResult = new List<RaycastResult>();

    foreach (Touch touch in Input.touches)
    {
        pointer.position = touch.position;
        EventSystem.current.RaycastAll(pointer, raycastResult);
        foreach (RaycastResult result in raycastResult)
        {
            if (result.gameObject == this.gameObject)
            {
                if(touch.phase == TouchPhase.Began)
                {
                    Debug.Log("Began " + result.gameObject.name );
                }
                else if(touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
                {
                    this.image.color = this.colorOn;
                }
                else if (touch.phase == TouchPhase.Ended)
                {
                    Debug.Log("End  " + result.gameObject.name);
                }
                //this.gameObject.transform.position = touch.position;

                //Do Stuff

            }

        }

        raycastResult.Clear();

    }

}


Q: Box shadow effect I'm trying to apply a shadow to a div, however I have been unable to achieve the desired effect. Effect to be 'below' the element.
Example: http://www.paulund.co.uk/creating-different-css3-box-shadows-effects
JSFiddle: http://jsfiddle.net/Ck7pG/
CSS
ul#nav li {
    display: inline;
    line-height: 40px;
}

 /* Shadow effect */
.shadow-effect {
    position: relative;
    -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
    -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}

.shadow-effect:before, .shadow-effect:after {
    content: "";
    position: absolute;
    z-index: -1;
    -webkit-box-shadow: 0 0 10px rgba(0,0,0,0.8);
    -moz-box-shadow: 0 0 10px rgba(0,0,0,0.8);
    box-shadow: 0 0 10px rgba(0,0,0,0.8);
    top: 20%;
    bottom: 0;
    left: 50px;
    right: 50px;
    -moz-border-radius: 100px / 10px;
    border-radius: 100px / 10px;
}

A: I just assumed your requirement from the website you provided,i think this is what you need
DEMO
.shadow-effect {
    position:relative;
    -webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px                 rgba(0, 0, 0, 0.1) inset;
       -moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
            box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.shadow-effect:before, .shadow-effect:after {
    content:"";
    position:absolute;
    z-index:-1;
    -webkit-box-shadow:0 0 10px rgba(0,0,0,0.8);
    -moz-box-shadow:0 0 10px rgba(0,0,0,0.8);
    box-shadow:0 0 10px rgba(0,0,0,0.8);
    top:20%;
    bottom:0;
    left:50px;
    right:50px;
    -moz-border-radius:100px / 10px;
    border-radius:100px / 10px;
}

.box h3{
    text-align:center;
    position:relative;
    top:80px;
}
.box {
    width:70%;
    height:100px;
    background:#FFF;
    margin:40px auto;
}

.effect6
{
    position:relative;
    -webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
       -moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
            box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.effect6:before, .effect6:after
{
    content:"";
    position:absolute;
    z-index:-1;
    -webkit-box-shadow:0 0 20px rgba(0,0,0,0.8);
    -moz-box-shadow:0 0 20px rgba(0,0,0,0.8);
    box-shadow:0 0 20px rgba(0,0,0,0.8);
    top:50%;
    bottom:0;
    left:10px;
    right:10px;
    -moz-border-radius:100px / 10px;
    border-radius:100px / 10px;
}


Q: issue with empty slide in JSSOR Slider and goto currentIndex property not working in javascript Hi I am working on JSSOR SLider and am trying to load a set of images on to it from database.
I am able to load therse images onto slider but i am getting first slide as an empty slide and rest are working fine.
In my index.html

in my js file
$('#galleryItem').on('pageshow', function () {
    var verticaltext = "";

    if ($('#galleryItem').has('#HomeImgSliders').length) {

        $("#HomeImgSliders").append("");

    }

    var allItems = Tables.images.all().order("capturedYear", false).order("capturedMonth", false).order("capturedDate", false);

    allItems.list(null, function (results) {
        var verticaltext = "";
        results.forEach(function (r) {

            // alert(JSON.stringify(r));
            imageDetailsarr.push([r.capturedDate, r.name, r.ratingTreatment, r.ratingSkinCleansing, r.ratingPlucking, r.ratingView, r.ratingLastVal, r.capturedDate, r.capturedMonth, r.capturedYear]);

            //  console.log("record is " + r.name);
            verticaltext = verticaltext + "

"

            //

        });

        $("#HomeImgSliders").append(verticaltext);
        // $("#HomeSlides").append(verticaltext);
        sliderDataReady(verticaltext);
 });

});

How can i get rid of this empty image that is appearing as the first slide
2) Also how can i set the slider set to a particular slide image based on some integer value that changes every time. I tried GoTO/slideIndex /currentIndex properties but could not get it ?
Any help would be appreciated ?Thanks

A: Re 1: Please dump value of 'verticaltext', with it you can create a static slider to see why there is an empty slide.
Re 2: Please use $StartIndex option
var options = {
    ...,
    $StartIndex: 0,    //specify slide index to display at the beginning.
    ...
};


Q: Char movement, getting x/y speeds from 2 points So i'm trying to make a program in java and i need to figure out how much I should add to x and y to make the player movement a constant speed at any angle. The information i have is 2 points, a starting point and an and and I need the char to move from a to b at a constant speed. I'm currently trying to figure out a bunch of different Math methods but I just cant get it right. Thanks in advance.

A: It's actually quite simple. You have points A (A.x, A.y) and B (B.x, B.y) and need the update for your character position.
Start by calculating the direction vector dir = B - A (subtract component-wise, such that dir.x = B.x - A.x; dir.y = B.y - A.y).
If you add this entire vector to your character's position, you will move it by sqrt(dir.x^2 + dir.y^2) (Pythagorean theorem). Hence, the speed will be: speed = sqrt(dir.x^2 + dir.y^2) / frameTime.
So if you want a constant speed, you have to find a multiple of the direction vector. This will be:
update = dir * speed / sqrt(dir.x^2 + dir.y^2) * frameTime
characterPosition = characterPosition + update

Don't bother with angle calculations. Vector arithmetic is usually way more robust and expressive.

A: Since u didn't provide us code I can just guess what exactly you are trying.
So I'll start with some basics.
I guess you are not just trying to make a program
but the basic movement of an 2d based game engine.
However a constant moving is based of an update method
that reads the player input about 30 times while rendering.
Example from my Projects:
public void run() {
    boolean isRunning = true;
    long lastNanoTime = System.nanoTime(),nowNanoTime = System.nanoTime();
    final double secondAsNano = 1000000000.0;
    final double sixtiethOfSecondAsNano = secondAsNano / 30.0;
    int delta = 1;
    while(isRunning){
        nowNanoTime = System.nanoTime();
        if(delta * sixtiethOfSecondAsNano + lastNanoTime < nowNanoTime){
            update();
            delta++;
            if(delta == 30){
                delta = 1;
                lastNanoTime = nowNanoTime;
            }
        }
        render();
    }
}

public update(){
    if(Input.moveUP) setPlayerY(getPlayerY() - 0.2);
    if(Input.moveDOWN) setPlayerY(getPlayerY() + 0.2);
    if(Input.moveRIGHT) setPlayerX(getPlayerX() + 0.2);
    if(Input.moveLEFT) setPlayerX(getPlayerX() - 0.2);
}

I just cut it down to be easy readable so it might not work correct but it should explain you how its basically done.

A: Mathematically (I won't provide code, sorry), assuming you can move in any direction on a two dimensional plane, from the top of my head it could be something like this (taken from old school geometry):

*

*Having a speed, let's say 20 pixels per second (it could also be any other unit you chose, including in-game distance)

*Having a polling system, where you have 2 main variables: the last known coords for the char (point A: Ax, Ay), the time of the last known update.

*Having the time of the current update.

*Having the coords for the destination (point B: Bx, By).

*Figure out the current position of your character, which could be done like this (without converting from cartesian to polar coord system):

*Figure out angle of movement: find the deltas for X and Y (Dx=Bx-Ax and Dy=By-Ay respectively), and use tangent to find the angle where Angle = tan-1(Dy/Dx).

*Figure out the travelled distance (TD) from last poll to current poll where TD = speed * elapsed time

*Figure out the coords for the new position (Cx and Cy) using sine and cosine, where travelled X is Tx=TD*sin(Angle) and travelled Y is Ty=TD*cos(Angle).

*Now add the travelled distances to your original coords, and you get the current position. Where Cx=Ax+Tx and Cy=Ay+Ty.

How "smooth" movement is depends highly on the quality of your polling and somehow also on rounding for small distances.

A: I ended up figuring this out almost an hour after posting this. Sorry that my question was so vague, what I was looking for was the math behind what i was trying to do not the code itself but thanks to people who answered. Here is the solution I came up with in code :
            if (q.get(0)[0][0] > q.get(0)[1][0]) {
                if(q.get(0)[0][0] == q.get(0)[1][0]) {
                    currentLocation[0] -= 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                    currentLocation[1] += 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                }
                else{
                    currentLocation[0] -= 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                    currentLocation[1] -= 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                }
            } else {
                if(q.get(0)[0][0] == q.get(0)[1][0]) {
                    currentLocation[0] += 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                    currentLocation[1] -= 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                }
                else{
                    currentLocation[0] += 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                    currentLocation[1] += 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
                }
            }

I figured out a way to get the result I wanted though I probably over complicated it. q is an ArrayList that holds 2d arrays that are 2x2 [a/b][x/y]. and currentLocation a 2 index array that's just [x/y]. The result is the affect I wanted where it draws a line in (X units) a pass from point a to b in any direction at the same speed. This question was poorly worded and i'm sorry for wasting peoples time.


Q: Trigger doesn't work (if statement) I have a problem. I want to create a trigger.
    DELIMITER $
    Create trigger xyz
    before delete on worker
    FOR EACH ROW
    Begin
    IF salary>2000
    then
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Zakaz usuwania';
    end if;
    End$
    DELIMITER ;

delete from pracownik where id=5

I get an error:

Error Code: 1054. Unknown column 'salary' in 'where clause'


Q: Sass styles are not applying I wanted to know why my styles of class="project-borders" and class="project-overlay" are not applying to div elements of data-modal="modal3" and data-modal="modal6". These styles are applying to every div element where used, except these two. I don't understand what's the problem even though the classes are the same across every div element. You can see the styles by removing class="project-borders" from div elements of data-modal="modal3" and data-modal="modal6".
Here is the visual representation:- Codepen
Please any help would be appreciated.
My HTML:

Coffee Grounds

Startup Employee Directory

Words Guessing Game

Motorcycle Parallax

Picture Portfolio

Video Creator Portfolio

My SASS:
.projects{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    width: 80%;
    margin: 0 auto;
    column-gap: 50px;
    row-gap: 50px;
    // margin-top: 60px;
    padding-top: 6%;

    img{
        width: 100%;
        height: 100%;
        cursor: pointer;
    }
}

.project-borders{
    position: relative;
    border: 2px solid #000;

    img{
        width: 100%;
        height: 100%;
        cursor: pointer;
        position: absolute;
        left: 10px;
        top: 10px;
    }

    &::before{
        position: absolute;
        border: 2px solid #ffde59;
        content: "";
        display: block;
        position: absolute;
        top: 25px;
        left: 25px;
        right: -20px;
        bottom: -20px;
    }

    .project-overlay{
        position: absolute;
        left: 10px;
        top: 10px;
        bottom: 0;
        transition: .5s;
        background-color: rgb(76, 72, 68);
        transition: .5s ease;
        width: 100%;
        height: 100%;
        opacity: 0;

        & p{
            position: absolute;
            font-size: 20px;
            top: 45%;
            width: 100%;
            text-align: center;
            color: #fff;
            transition: .5s;
            opacity: 0;
        }
    }
    &:hover .project-overlay{
            cursor: pointer;
             opacity: 1;
             z-index: 1;

    }
    &:hover .project-overlay p{
        cursor: pointer;
        display: block;
        opacity: 1;
        z-index: 1;
    }
}

A: Based on your codepen, it doesn't seem like the 3rd and 6th modals are the problem with the styles displaying. The real problem is that all the content in your modals are absolutely positioned which takes them out of the ordinary context of the document, which causes the project-borders containers to have a height that only consists of the borders. You'll need to define a fixed height for that container for things to display correctly like so...
.project-borders {
    position: relative;
    border: 2px solid #000;
    height: 209px;
}


Q: Parsing dl tag using Jsoup I am trying to parse a
 tag using Jsoup. The
 tag contains
 tags and
 tags. I have a HashMap (HashMap<String, List<String>) in which I want to put the
s as keys and
s as values (there are multiple
 tags per
 tag.
The HTML looks like this:

    Parameters:

    y - the ordinate coordinate

    x - the abscissa coordinate

    Returns:

    the theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.

I've tried the following:
String title = "";
List<String> descriptions = new ArrayList<>();
for (int i = 0; i < children.size(); i++) {
    Element child = children.get(i);

    if(child.tagName().equalsIgnoreCase("dt")) {
        if(descriptions.size() != 0) {
            block.fields.put(title, descriptions);
            descriptions.clear();

        }

        title = child.text();
    }
    else if(child.tagName().equalsIgnoreCase("dd")) {
        descriptions.add(child.text());

        if(i == children.size() - 1) {
            block.fields.put(title, descriptions);
        }
    }
}

I expected to get this:
 * Parameters -> y - the ordinate coordinate
 *               x - the abscissa coordinate
 * Returns    -> the theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.

But I got this:
 * Parameters -> the theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.

 * Returns    -> the theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.

A: You need to insert a copy of your descriptions list into the map, currently you manipulate 1 instance of the list. So instead of:
block.fields.put(title, descriptions);

create a new list, e.g.:
block.fields.put(title, new ArrayList<>(descriptions));


Q: Make links have the same distance I am trying to make a simple website and I need some help.
I have this div

<?php require "./Pages/header.html"; ?>

And the header html:
Home
Shop Information
Products
Cart
Login
Contact

I want something like this:
Home       Shop Information             Products             Cart               Login                    Contact
where Home will be at the beggining of the div and Contact will be at the end of the div and all these links will have the same distance, but I dont want to use   spaces.

A: Make use of ul

Home

Shop Information

Products

Cart

Contact

CSS
 ul li
 {
     display:inline;
     padding:5px;
 }

Here is the Demo

A: There are a lot of options. You can use margin-right or padding.
JS-fiddle:
http://jsfiddle.net/7Uq9y/
Home
Shop Information
Products
Cart
Login
Contact

css:
a{
    margin-right: 50px;
}

A: Can you try using  tag

Home
Shop Information
Products
Cart
Login
Contact

CSS:
nav {
      display:block;
      margin-left:auto;
      margin-right:auto;
  }

A: CSS Using your existing html/php code :
div#header a {
    margin-right: 10px;
    width: 150px;
    display: inline-block;
}

A: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>Test Website</title>

Home

Shop Information

Products

Cart

Login

Contact


Q: Unknown column 'Username' in 'where clause' mysql_select_db($database_binary, $binary);
$query_account = sprintf("SELECT * FROM users WHERE Username = %s", GetSQLValueString($colname_account, "text"));
$account = mysql_query($query_account, $binary) or die(mysql_error());
$row_account = mysql_fetch_assoc($account);
$totalRows_account = mysql_num_rows($account);

$maxRows_trade = 20;
$pageNum_trade = 0;
if (isset($_GET['pageNum_trade'])) {
  $pageNum_trade = $_GET['pageNum_trade'];
}
$startRow_trade = $pageNum_trade * $maxRows_trade;

$colname_trade = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_trade = $_SESSION['MM_Username'];
}
mysql_select_db($database_binary, $binary);
$query_trade = sprintf("SELECT * FROM asset WHERE Username = %s", GetSQLValueString($colname_trade, "text"));
$query_limit_trade = sprintf("%s LIMIT %d, %d", $query_trade, $startRow_trade, $maxRows_trade);
$trade = mysql_query($query_limit_trade, $binary) or die(mysql_error());
$row_trade = mysql_fetch_assoc($trade);

if (isset($_GET['totalRows_trade'])) {
  $totalRows_trade = $_GET['totalRows_trade'];
} else {
  $all_trade = mysql_query($query_trade);
  $totalRows_trade = mysql_num_rows($all_trade);
}
$totalPages_trade = ceil($totalRows_trade/$maxRows_trade)-1;

$maxRows_withdrawreq = 10;
$pageNum_withdrawreq = 0;
if (isset($_GET['pageNum_withdrawreq'])) {
  $pageNum_withdrawreq = $_GET['pageNum_withdrawreq'];
}
$startRow_withdrawreq = $pageNum_withdrawreq * $maxRows_withdrawreq;

$colname_withdrawreq = "-1";
if (isset($_SESSION['Username'])) {
  $colname_withdrawreq = $_SESSION['Username'];
}
mysql_select_db($database_binary, $binary);
$query_withdrawreq = sprintf("SELECT * FROM withdrawal WHERE Username = %s", GetSQLValueString($colname_withdrawreq, "text"));
$query_limit_withdrawreq = sprintf("%s LIMIT %d, %d", $query_withdrawreq, $startRow_withdrawreq, $maxRows_withdrawreq);
$withdrawreq = mysql_query($query_limit_withdrawreq, $binary) or die(mysql_error());
$row_withdrawreq = mysql_fetch_assoc($withdrawreq);

I am getting an error:

Unknown column 'Username' in 'where clause'

How can I solve it?

A: The asset and withdrawal tables do not have a column called Username. So add that column to these tables or change WHERE condition in the sql statement related to these tables.These sql statements refer to the Username column in the WHERE clause that does not exist:
SELECT * FROM **asset** WHERE **Username**

SELECT * FROM **withdrawal** WHERE **Username**

New CREATE statements including Username column:
    CREATE TABLE asset ( Asset varchar(100) NOT NULL, optiontype varchar(200)
NOT NULL,
    Invested varchar(200) NOT NULL, Username varchar(100) NOT NULL,
    Entry Rate varchar(200) NOT NULL, Rate varchar(200) NOT NULL, Entry Time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, Expiration Time varchar(200) NOT NULL, Status varchar(200) NOT NULL, Returns varchar(200) NOT NULL, Customer varchar(200) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=armscii8;

CREATE TABLE withdrawal ( id varchar(100) NOT NULL, Username varchar(100) NOT NULL,
Date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, Customer varchar(200) NOT NULL, Amount varchar(100) NOT NULL, currency varchar(100) NOT NULL, email varchar(100) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=armscii8;


Q: Firebase storage upload stopped working on react-native I am using
"firebase": "^3.6.0",
"react": "15.3.2",
"react-native": "0.37.0",
"react-native-camera": "git+https://github.com/lwansbrough/react-native-camera.git",
"react-native-fetch-blob": "^0.10.0",
"react-native-vector-icons": "^3.0.0",
"react-native-video": "^0.9.0"

And i'm trying to upload a video recorded with react-native-video to firebase - this worked but suddenly it stopped working and now it doesn't succeed.
I'm using the following code where this.props.file.path looks something like this:
file:///storage/emulated/0/Pictures/vidid.mp4
  accept = () => {
    let rnfbURI = RNFetchBlob.wrap(this.props.file.path)
    Blob
    .build(rnfbURI, { type : 'video/mp4;'})
    .then((blob) => {
      // upload image using Firebase SDK
      firebase.storage()
        .ref()
        .child('testImageName')
        .put(blob, { contentType : 'video/mp4' })
        .then((snapshot) => {
          console.log(snapshot)
          blob.close()
          done()
        })
    })
}

I tried writing Firebase support, but then won't help me since this is a workaround.
My blob object looks like this:
 { listeners: {},
   isRNFetchBlobPolyfill: true,
   multipartBoundary: null,
   _ref: 'file:///storage/emulated/0/Pictures/VID_20161113_142100.mp4',
   _blobCreated: true,
   _closed: false,
   cacheName: 'blob-559cd5c4-e880-4742-a3fe-dfae7e1a0df0',
   type: 'video/mp4;',
   size: '3665375' }


Q: How to reuse objects between Automake program and tests targets? I have a non-recursive Makefile.am with something like the following:
SHARED_SRCS = src/bar.cpp src/baz.cpp

bin_PROGRAMS = foo

foo_SOURCES = src/main.cpp $(SHARED_SRCS)
foo_CXXFLAGS = -I$(srcdir)/src $(SOME_CFLAGS)
foo_LDADD = $(SOME_LIBS)

check_PROGRAMS = test1 test2 test3
TESTS = test1 test2 test3

test1_SOURCES = tests/test1.cpp $(SHARED_SRCS)
test2_SOURCES = tests/test2.cpp $(SHARED_SRCS)
test3_SOURCES = tests/test3.cpp $(SHARED_SRCS)
test1_CXXFLAGS = $(foo_CXXFLAGS)
test2_CXXFLAGS = $(foo_CXXFLAGS)
test3_CXXFLAGS = $(foo_CXXFLAGS)
test1_LDADD = $(foo_LDADD)
test2_LDADD = $(foo_LDADD)
test3_LDADD = $(foo_LDADD)

However, every target builds its own SHARED_SRCS, getting them built 4 times, even when sharing the same flags.
Is there a way to get them built without creating a convenience library, e.g. libbar.a or libtool's libbar.la?

A: No, there's not. The point is that you're not rebuilding the sources, you're rebuilding binaries.
What you can do is build an intermediate .o consisting only of the shared sources, and then use that in your tests, and binaries.


Q: How to move changes as uncommitted from one branch to another on Git I want to move all changes that are in a branch relative to master to another branch.
I don't want them as commits just as changes so that i can modify them and remove some of the changes and commit as one. I don't want to retain the old committed history.
I tried git format-patch master --stdout > mypatch.path
and git apply
but that applies as commits which i can't modify after that.

A: I would do this to move the changes from branch1 to branch2:
git checkout branch2

git merge --squash branch1

No commit has been created or "copied" between the branches. The changes can be modified before committing if need be.

A: If I understand what you want to do correctly, one way would be to start with your first branch:
git checkout branch1

Create a new branch from there:
git checkout -b branch2

Reset back to master, which will remove any commits that were made on branch1, but leave the changes as unstaged:
git reset master

You can then modify the files further and commit them as one commit.


Q: Popup not working and no errors Popup.alert is not working using "ionic-framework: 2.0.0-alpha.42".
I am using "ionic-framework: 2.0.0-alpha.42" locally and "ionic@2.0.0-beta.15" globally in NPM.
Using this document as an example.
this.popup.alert({
    title: "New Friend!",
    template: "Your friend, Obi wan Kenobi, just accepted your friend request!",
    cssClass: 'my-alert'
}).then(() => {
    console.log('Alert closed');
});

That code is not working. I do not see a popup and i do not see "Alert closed" ever shown in the console. I pull in "popup" through the constructor.
private popup: Popup;
constructor(popup: Popup) {
    this.popup = popup;
}

A: I figured out the issue. You need to add
<ion-overlay></ion-overlay>
to your app.html. I saw that no where in the documentation.


Q: Is there any way to run a python script using the google API / Oauth function without needing to authenticate the account every time the script runs? Here is a quickpython  script that I wrote to upload a file to Google Drive:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
drive = GoogleDrive(gauth)

upload_file_list = [#placeholderfilename]
for upload_file in upload_file_list:
    gfile = drive.CreateFile({'parents': [{'id': '#placeholderdriveID'}]})
    # Read file and set it as the content of this instance.
    gfile.SetContentFile(upload_file)
    gfile.Upload() # Upload the file.

This script works, but every time it runs it also opens a window to authenticate the account accessing the drive. My goal for this script is to run it every morning with no input. Is there a way to set up the API so I don't need to manually authenticate the account every time I access google drive? Or does Google not allow that?


Q: is register_next_step_handler exist in aiogram? we have something like:
bot = telebot.TeleBot(TOKEN)

@bot.message_handler(commands=['start'])
def process_start(message):
    text = 'start'
    bot.send_message(message.chat.id, text)
    bot.register_next_step_handler(message, process_mid)

def process_mid(message):
    text = 'mid'
    bot.send_message(message.chat.id, text)
    bot.register_next_step_handler(message, process_end)

def process_end(message):
    text = 'end'
    bot.send_message(message.chat.id, text)

bot.polling(none_stop=True)

in pyTelegramBotAPI
this function is for when you ask user for like a number and after he/she sends num you process it in that special func that you mentioned

A: evgfilim1:
Hello. You need to use FSM, it's more flexible than register_next_step_handler.
Check the example: https://github.com/aiogram/aiogram/blob/dev-2.x/examples/finite_state_machine_example.py
The linked page won't break as the implementation is not going to change in aiogram 2.x.


Q: Spring MVC Test with Hamcrest: How compare a XML's node directly against a Java object I am working with:

*

*Spring MVC Test

*Hamcrest

For an item from a collection such as:
<collection>
    <item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="persona">
        <id>087</id>
        <nombre>Leonardo</nombre>
        <apellido>Jordan</apellido>
        <fecha>1981-07-05</fecha>
    </item>
    ....

The following works:
.andExpect(xpath("collection/item[1]").exists())
.andExpect(xpath("collection/item[1]/*").nodeCount(is(4)))
.andExpect(xpath("collection/item[1]/id").exists())
.andExpect(xpath("collection/item[1]/id").string(is("087")))
.andExpect(xpath("collection/item[1]/id").string(is(personasArray[0].getId())))
.andExpect(xpath("collection/item[1]/nombre").exists())
.andExpect(xpath("collection/item[1]/nombre").string(is("Leonardo")))
.andExpect(xpath("collection/item[1]/nombre").string(is(personasArray[0].getNombre())))
.andExpect(xpath("collection/item[1]/apellido").exists())
.andExpect(xpath("collection/item[1]/apellido").string(is("Jordan")))
.andExpect(xpath("collection/item[1]/apellido").string(is(personasArray[0].getApellido())))

I want to know if is possible do a direct comparison against an object and not for each field, consider an entity with 15 to 45 fields.
I need something like this:
.andExpect(xpath("collection/item[1]/*").how(is(personasArray[0])))

See the how part, it represents what is the correct method to use.
Same consideration for the path's String content.

A: It is possible to do such an assertion. But you'll need to write your custom ResultMatcher for that. I don't think it is a good idea to convert XML (nodes) to Java objects just to do a simple comparison in a unit test.
You may run into problems with XML namespace resolution or the Java hashCode equals contract if not implemented right.
Instead, you should use libraries that lets you focus on your unit tests and not on the details of a technology or a programming language.
I recommend you to use XMLUnit in your test. XMLUnit is a Java library for XML comparison.
The example below depicts how easy it is to compare a XML document with XMLUnit and a custom ResultMatcher.
import org.hamcrest.Matcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xmlunit.builder.Input;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;

@RunWith(SpringRunner.class)
@WebMvcTest(XmlUnitDemoTests.XmlUnitDemo.class)
public class XmlUnitDemoTests {

    static final String XML_CONTENT = "<node1><node2 id=\"1\">text</node2></node1>";

    @Autowired
    MockMvc mockMvc;

    @Test
    public void xmlUnit() throws Exception {
        mockMvc.perform(get("/xml"))
            .andExpect(xml(XML_CONTENT));
    }

    static ResultMatcher xml(String bodyValue) {
        return MockMvcResultMatchers.content().source(equalXml(bodyValue));
    }

    static Matcher equalXml(String value) {
        return isSimilarTo(Input.fromString(value).build());
    }

    @SpringBootApplication
    @RestController
    static class XmlUnitDemo {

        @RequestMapping(value = "xml", produces = "text/xml")
        String xml() {
            return XML_CONTENT;
        }
    }

}

Of course, you may load big XML files from classpath or select a node with XPatch before doing a comparison. Take a look at the XMLUnit documentation for more information on that.


Q: How do I pass a subdirectory path to the GunDB S3 storage driver so the same S3 bucket can be shared with non-Gun data? I see examples referencing a few parameters for the S3 storage driver for GunDB that look like this:
var Gun = require('gun');
var gun = Gun({
    file: 'data.json',
    s3: {
            key: '', // AWS Access Key
            secret: '', // AWS Secret Token
            bucket: '' // The bucket you want to save into
    }
});

I don't see a parameter to define a subdirectory/path within the S3 bucket, to facilitate sharing the bucket with non-GunDB data. Is there such an option/parameter?

A: @hillct there is an option called prefix, thank you for pointing out that the options aren't documented. Here is how to use it:
var Gun = require('gun');
var gun = Gun({
    file: 'data.json',
    s3: {
            key: '', // AWS Access Key
            secret: '', // AWS Secret Token
            bucket: '', // The bucket you want to save into
            prefix: 'gun/'
    }
});

And just in case, here are some of the other options:
{
  throttle: 15 // Throttle writes to S3 in 15 second intervals, keeps S3 API costs down.
  batch: 10 // Or if there are more than 10 things in queue, don't wait.
}


Q: How to set values in a 2d numpy array given 1D indices for each row? In numpy you can set the indices of a 1d array to a value
import numpy as np

b = np.array([0, 0, 0, 0, 0])

indices = [1, 3]

b[indices] = 1
b

array([0, 1, 0, 1, 0])

I'm trying to do this with multi-rows and an index for each row in the most programmatically elegant and computationally efficient way possible. For example
b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])

indices = [[1, 3], [0, 1], [0, 3]]

The desired result is
array([[0, 1, 0, 1, 0],
       [1, 1, 0, 0, 0],
       [1, 0, 0, 1, 0]])

I tried b[indices] and b[:,indices] but they resulted in an error or undesired result.
From searching, there are a few work arounds, but each tends to need at least 1 loop in python.
Solution 1: Run a loop through each row of the 2d array. The draw back for this is that the loop runs in python, and this part won't take advantage of numpy's c processing.
Solution 2: Use numpy put. The draw back is put works on a flattened version of the input array, so the indices need to be flattened too, and altered by the row size and number of rows, which would use a double for loop in python.
Solution 3: put_along_axis seems to only be able to set 1 value per row, so I would need to repeat this function for the number of values per row.
What would be the most computationally and programatically elegant solution? Anything where numpy would handle all the operations?

A: In [330]: b = np.zeros((3,5),int)
To set the (3,2) columns, the row indices need to be (3,1) shape (matching by broadcasting):
In [331]: indices = np.array([[1,3],[0,1],[0,3]])

In [332]: b[np.arange(3)[:,None], indices] = 1

In [333]: b
Out[333]:
array([[0, 1, 0, 1, 0],
       [1, 1, 0, 0, 0],
       [1, 0, 0, 1, 0]])

put along does the same thing:
In [335]: b = np.zeros((3,5),int)
In [337]: np.put_along_axis(b, indices,1,axis=1)

In [338]: b
Out[338]:
array([[0, 1, 0, 1, 0],
       [1, 1, 0, 0, 0],
       [1, 0, 0, 1, 0]])

A: On solution to build the indices in each dimension and then use a basic indexing:
from itertools import chain

b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])

# Find the indices along the axis 0
y = np.arange(len(indices)).repeat(np.fromiter(map(len, indices), dtype=np.int_))

# Flatten the list and convert it to an array
x = np.fromiter(chain.from_iterable(indices), dtype=np.int_)

# Finaly set the items
b[y, x] = 1

It works even for indices lists with variable-sized sub-lists like indices = [[1, 3], [0, 1], [0, 2, 3]]. If your indices list always contains the same number of items in each sub-list then you can use the (more efficient) following code:
b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
indices = np.array(indices)
n, m = indices.shape
y = np.arange(n).repeat(m)
x = indices.ravel()
b[y, x] = 1

A: Simple one-liner based on Jérôme's answer (requires all items of indices to be equal-length):
>>> b[np.arange(np.size(indices)) // len(indices[0]), np.ravel(indices)] = 1
>>> b
array([[0, 1, 0, 1, 0],
       [1, 1, 0, 0, 0],
       [1, 0, 0, 1, 0]])


Q: How to set the active profile when creating Spring context programmatically? tl;dr: how to create a Spring context based on an annotation-based configuration class, while supplying active profiles?
I am trying to create a Spring context using a class with the configuration specified using annotations.
org.springframework.context.ApplicationContext context =
    new org.springframework.context.annotation.AnnotationConfigApplicationContext( com.initech.ReleaserConfig.class );

However when it starts up it crashes because it cannot find a required bean, but that bean does exist : albeit only under a certain profile "myProfile".
How do I specify the active profile? I have a feeling I need to use one the org.springframework.context.annotation.AnnotationConfigApplicationContext(org.springframework.beans.factory.support.DefaultListableBeanFactory) constructor but I'm not sure which ones is appropriate.

PS- I am not using Spring Boot, but am on Spring 4.2.4.RELEASE.

A: If you want classpath:resources/application-${spring.profiles.active}.yml to be working, setting system properties before refreshing is the way to go.
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().getSystemProperties().put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
applicationContext.scan("com.sample");
applicationContext.refresh();

A: This should do the trick...
final AnnotationConfigApplicationContext appContext =  new AnnotationConfigApplicationContext();
appContext.getEnvironment().setActiveProfiles( "myProfile" );
appContext.register( com.initech.ReleaserConfig.class );
appContext.refresh();


Q: Javascript variable & ajax ; with JsonForm. Using .jsonForm() with a variable I'm using JsonForm: https://github.com/joshfire/jsonform/wiki#wiki-getting-started
I'm trying to load a form schema into $('form').Jsonfrom(), from an external .txt file,
attempting this by loading it into my .html file with ajax, putting it in a javascript variable , then calling $('form').Jsonfrom() with a click event .
Here is my code:
<script>
#Load in .txt to javascript variable using ajax
var stringData = $.ajax({
                    url: "schema.txt",
                    async: false
                 }).responseText;

#check that file is loaded correctly .- have check this works.
#alert(stringData);

#on clicking of a piece of text in a <p> wrapper call jsonForm function.
$(document).ready(function(){
  $("p").click(function(){
       $('form').jsonForm(stringData   )
  });
});

</script>

the error I'm getting in firebug is:

"TypeError: this.formDesc.schema is undefined"

& my stack trace is this:
http://tinypic.com/r/2uiybo4/5
Think my problem may be in the way in loading in the .txt file with ajax.
however if I comment in: alert(stringData);  . . . the scheme for the for is displayed perfectly.
Like so: http://tinypic.com/r/2ynl9qh/5
Also there is no problem with the scheme, as i have tried putting it directly into in $('form').Jsonfrom("here") & it works fine.

A: Managed to solve this .
had to use a templating language (jinja2) instead of ajax, to get my form schema into my html document.. so that json form ( a jquery form builder) couple execute on a full html doc on the page loading .
Silly !
Hope this helps .


Q: Checking DB health in github actions Im running a container with mssql, and want to know if the DB is healthy after a set of second, cant figure out how to return the value of this step that has the docker inspect command in it

docker inspect --format={{.State.Health.Status}} test-db

so I can tell it in a next step, ex. the output == 'healthy' and if this is true then go forward with the steps onto build down the line..
I dont know the format and my head is starting to explode.
If anyone could help me understand how to do this?
EDIT:
I know im close:

EDIT:
solution was to use those damned single quotes or the $() docker inspect --format={{.State.Health.Status}} test-db

A: try surrounding the {{ with single quote like
docker inspect --format='{{.State.Health.Status}}' test-db

and executing in the if condition like:
if [[ $(docker inspect --format='{{.State.Health.Status}}' test-db) == "healthy"  ]]


Q: Get functions called with GDB I am using GDB to understand a C++ program. I put a break in the middle of the running which turns to be something like:
break main.cpp:500
and I would like to see which functions have been called before. I tried "backtrace" but it shows only info about main, as previous calls to previous functions have already finished.
My question is how can I get (with GDB or another method) the info about which functions have been called before this point, even if the call has been returned.
Thanks

A: A gdb script might be a solution for your problem.
Create a script that puts break point to each possibly called function.
At break prints the stack with 'bt' and continue the execution.
You should put an other break point to main.cpp:500 to quit from debugging.

b 'main.cpp::500'
commands 1
    detach
    quit
end

break 'A::f1()'
break 'A::f2()'
while true
continue
bt
end

You can start the script like this:

gdb --command ./gdbscript.gdb fpmanager

If you have too much possibly called function you can grep the code to find all.


Q: Label the midpoint of a segment in ggplot In the plot below I'd like to label the arrows with the text in bar$lbl. I'd like to do so in a way that would keep any labels from overlapping (they wouldn't in the simple example below). I'd prefer not to calculate the label position by hand.
I'm familiar with getting pretty, non-overlapping labels on points with ggrepel and curious if there is a similar way to label the midpoints of segments?
Any advice appreciated.
library(ggplot2)
foo <- data.frame(x=runif(50),y=runif(50))
bar <- data.frame(x1=c(0.2,0),x2=c(0.7,0.2),
                  y1=c(0.1,0.9),y2=c(0.6,0.5),
                  lbl=c("Arrow 1", "Arrow 2"))
p1 <- ggplot(data=foo,aes(x=x,y=y))
p1 <- p1 + geom_point(color="grey")
p1 <- p1 + geom_segment(data=bar,aes(x=x1, xend=x2, y=y1, yend=y2),
                        size = 0.75,arrow = arrow(length = unit(0.5, "cm")))
p1

A: I know you would prefer not to calculate the mid points by hand, however, it is often easier to work with variables inside the aesthetics then with statistics, so I did it calculating the midpoints before hand and mapping to the axis
library(ggplot2)
library(directlabels) # provides a geom_dl that works easier with labels

foo <- data.frame(x=runif(50),y=runif(50))
bar <- data.frame(x1=c(0.2,0),x2=c(0.7,0.2),
                  y1=c(0.1,0.9),y2=c(0.6,0.5),
                  midx = c(0.45, 0.1), # x mid points
                  midy = c(0.35, 0.7), # y midpoints
                  lbl=c("Arrow 1", "Arrow 2"))

p1 <- ggplot(data=foo,aes(x=x,y=y))
p1 <- p1 + geom_point(color="grey")
p1 <- p1 + geom_segment(data=bar,aes(x=x1, xend=x2, y=y1, yend=y2),
                        size = 0.75,arrow = arrow(length = unit(0.5, "cm")))
p1 + geom_dl(data = bar, aes(x = midx, y = midy, label = lbl),
             method = list(dl.trans(x = unit(x, 'cm'), y = unit(y, 'cm'))))

A: Here are two ways to do it with a lot of tidying. You don't need to do anything by hand if you think about the fact that the midpoint has coordinates that are just the means of x values and the means of y values of the 2 endpoints. First way is to tidy your data frame, calculate the midpoints, then make it wide again to have x and y columns. That data frame goes into ggplot, so it's passed through all the geoms, but we override with data arguments to geom_point and geom_segment. geom_segment gets just the original copy of the bar data frame.
library(tidyverse)
foo <- data.frame(x=runif(50),y=runif(50))
bar <- data.frame(x1=c(0.2,0),x2=c(0.7,0.2),
                                    y1=c(0.1,0.9),y2=c(0.6,0.5),
                                    lbl=c("Arrow 1", "Arrow 2"))

bar %>%
    gather(key = coord, value = value, -lbl) %>%
    mutate(coord = str_sub(coord, 1, 1)) %>%
    group_by(lbl, coord) %>%
    summarise(value = mean(value)) %>%
    ungroup() %>%
    spread(key = coord, value = value) %>%
    ggplot() +
        geom_point(aes(x = x, y = y), data = foo, color = "grey") +
        geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), data = bar, size = 0.75, arrow = arrow(length = unit(0.5, "cm"))) +
        geom_text(aes(x = x, y = y, label = lbl))

But maybe you don't want to do all that piping at the beginning, or you have to do this several times, so you want a function to calculate the midpoints. For the second version, I wrote a function that does basically what was piped into ggplot in the first version. You supply it with the bare column name where your labels are kept, which is the column it will be grouped on. Then you can just use that in your geom_text.
## cool function!
tidy_midpt <- function(df, lbl_col) {
    lbl_quo <- enquo(lbl_col)

    df %>%
        gather(key = coord, value = value, -!!lbl_quo) %>%
        mutate(coord = str_sub(coord, 1, 1)) %>%
        group_by(lbl, coord) %>%
        summarise(value = mean(value)) %>%
        ungroup() %>%
        spread(key = coord, value = value)
}

ggplot(data = bar) +
    geom_point(aes(x = x, y = y), data = foo, color = "grey") +
    geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), size = 0.75, arrow = arrow(length = unit(0.5, "cm"))) +
    geom_text(aes(x = x, y = y, label = lbl), data = . %>% tidy_midpt(lbl))

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


Q: MongoDB findOneAndUpdate not updating So, I've been working with MongoDB for a couple days, I have been doing a per-server mute role command but when I was doing the set muterole command, when using findOneAndUpdate function, it doesn't seem to update the values, I've been searching for other answers and I've tried multiple of them, yet it doesn't seem to work, this is my code:
muteSchema.findOne(
                {
                    guildId: message.guild.id
                }, async (err, data) => {
                    if(err) console.log(err)
                    if(data)
                    {
                        muteSchema.findOneAndUpdate(
                            {
                                guildId: data.guildId
                            },
                            {
                                guildId: message.guild.id,
                                roleId: role.id
                            }
                        )
                    }
                    else
                    {
                        data = new muteSchema(
                            {
                                guildId: message.guild.id,
                                roleId: role.id
                            }
                        )

                        data.save().catch((err) => console.log(err) )
                    }
                }
            )

I do have the muteSchema import on top and this is my muteSchema file:
const mongoose = require("mongoose")

let MuteroleSchema = mongoose.Schema(
    {
        guildId: String,
        roleId: String
    },
    {
        strict: false
    }
)

module.exports = mongoose.model("muterole", MuteroleSchema)

The values are registered the first time it is used, but they don't update once they are there.

A: You are making things too complex for yourself. Why do you first find then again find and then update?
Simply go with the following flow
Update using filter

Code Sample:
exports.updateToken = async (id, forgotToken) => {//function
return User.updateOne({ _id: id }, { resetPasswordToken: forgotToken });//_id:id is a filter while the reset is code to update
}


Q: sound sequence on iphone - best practice? I'd like to make a sound sequencer on iPhone, almost like "dropphone" LINK
So I would need to

*

*play multiple samples (1~6seconds) at the same time

*keeping them synchronized with an NSTimer.

*being able to stop them / change the global volume

I've tried 2 approaches but I'm not that convinced :

*

*AVAudioPlayer
Downside: I get half a second lag when I want to play a sound

*AudioServices
Downside: I can't control/stop the sounds once they're launched
Is there another method to handle sounds that would be optimized to play overlapping sounds?


Q: Uncaught TypeError: Cannot read property 'tcp' of undefined in chrome extension I am trying to develop an extension in chrome which can snoop browser history and send it to a remote machine. I need to establish socket connection for transporting data.
But I am getting the above error. Read a lot of posts online which say there must be errors in the manifest file in context with socket permissions. Can anyone find out the error? Please check the code beneath.
Manifest File:
{
    "manifest_version": 2,
    "name": "Browser History Snooping",
    "description": "This extension snoops browser history and sends it to a remote machine",
    "version": "1.0",
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },
    "permissions": [
        "history"
    ],
    "sockets": {
        "tcp": {
            "connect": ""
        }
    }
}

JavaScript
var histories = [];
var visits = [];

chrome.history.search({
    text: '',
    maxResults: 0
}, function (historyItems) {
    var historiesProcessed = 0;
    for (var i = 0; i < historyItems.length; i++) {
        //histories.push(historyItems[i]);
        console.log(historyItems[i]);

        chrome.history.getVisits({
            url: historyItems[i].url
        }, function (visitItems) {
            for (var i = 0; i < visitItems.length; i++) {
                visits.push(visitItems[i]);
            }
            historiesProcessed++;
            if (historiesProcessed === historyItems.length) {
                console.log(visits.length + ' visits');
            }
        });
    }

    console.log(histories);
});

chrome.sockets.tcp.create({}, function (createInfo) {
    chrome.sockets.tcp.connect(createInfo.socketId, '127.0.0.1', 8888,
        function (result) {
            if (result >= 0) {
                console.log('Successfully connected');
            }
        });
});

A: The error is self-explanatory: chrome.sockets is undefined.
There's no sockets API in the extension documentation, but it is defined for the chrome apps.