text:
Q: Improve fetch request load speed I have a web scraper that that basically fetches the html page and scrapes text data using cheerio.js
It takes about ~2sec to retrieve the data but I'm looking for way to improve this. The biggest bottleneck is fetching the html  which takes about 1.0-1.7sec to load on average. Are they any techniques that I could use to improve this? For instance there are auto-play videos and images that I don't need is there a way to block those elements?
Things I've tried:
I have changed the user-agent to a mobile device so I can retrieve the mobile version of the website but it hasn't much of a difference.
P.S the scraper is hosted on Heroku free tier.
The code I'm trying to improve
const USER_AGENT = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1'

function getHTML(url) {
    return axios.get(url,
        {
            timeout: 5000,
            headers: {
                'Content-Type': 'text/html',
                'user-agent': `${USER_AGENT}`
            }
        })
        .then(response => {
            return response.data
        })
        .catch(error => { console.log(error); return null })
 }

The above code return the html which than I scrape with cheerio in the functions below.
 async function getData(url)  {
        ...

        await getHTML(url).then((html) => {
                const $ = cheerio.load(html)
                if ($(html).find('#quote-header-info')) {
                    const info = $('info-box').text()
                }

                //More scraping
        }
    }


text:
Q: Displaying MS Access records as lines in ArcMap? I'm trying to add an MS Access table as a layer in ArcMap 10.6. There are four columns with coordinates - from_x, from_y, to_x and to_y. I want to represent the records as lines on the map.
I can add the table, but when I choose "Display XY Data..." I get no option to display data as anything but points:

Is there a way to display lines? For compatibility with other software, I need to keep the data in an Access database, so keeping everything in a geodatabase is not an option.
In the ideal scenario, data should automatically be up to date as in the Access table every time I open my workspace. If that is not possible, some kind of import step where you by simple user action reimport the data could also work.

A: You are using the wrong tool, what you are showing is converting XY to points. You need to be using the XY to Line tool. This will create straight lines between your pair of coordinates.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I link a user input argument with a string? So, I'm rather new to Java and I just starting a project, but I ran into some issues.
My question is... How do I link a user input (argument) with a String?
I have already defined a few Strings earlier on in my code, but in this line I want it to match up and check from the String which matches the argument and check if it contains something:
if (!cs.hasPermission("foo." + args[0]) &&   [CODE HERE]   ){

I want [CODE HERE] to check If args[0] (user input) matches a String, if it does then check if it matches some text.

A: This is String equals api, so it should look something like:
if (!cs.hasPermission("foo." + args[0]) && args[0].equals(string){
  //code
}

A: Java has a .equals() method which can be used to compare two Strings. It can used to compare two variables which hold references to String objects or to compare String literals
if( args[0].equals(someString) ) { // compare args[0] to another String variable
}

if( "someText".equals(args[0]) ) { // compare args[0] to a String literal
}

Reading through the String documentation will also be very useful to you starting out.

A: You can easily do it with the equals() method. But you should also check that args[0] is set.
if (args.length > 0) {
    if (!cs.hasPermission("foo." + args[0]) && "StringToCompare".equals(args[0])) {
        // do something
    }
} else {
    // handle error
}


text:
Q: Amazon Feed API - The file's header row is missing or invalid I am trying to submit a flat file (tab delimited) full of products. If I upload this file via the Upload Products & Inventory page is uploads correctly. However, if I try to use the API I get an error:
The file's header row is missing or invalid. The header row is for Amazon use only and must not be modified or deleted. To correct this error, download the template again from seller Help and use that new copy, or insert the correct header row directly above the column headings in your existing file.
The code I am using it the sample code, Feeds API Section Client Library - C#.
SubmitFeedRequest request = new SubmitFeedRequest();
request.Merchant = merchantId;
request.MarketplaceIdList = new IdList();
request.MarketplaceIdList.Id = new List<string>(new string[] { marketplaceId });

request.FeedContent = File.Open(@"C:\Amazon_Upload_20141104_10.txt", FileMode.Open, FileAccess.Read);

request.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent);
request.FeedContent.Position = 0;

request.FeedType = "_POST_FLAT_FILE_LISTINGS_DATA_";

SubmitFeedSample.InvokeSubmitFeed(service, request);

Why would this file work through the web interface but not through the API?

A: In case anyone else finds this by Google my problem was the incorrect feed type.
I had _POST_FLAT_FILE_LISTINGS_DATA_
When is should have been _POST_FLAT_FILE_INVLOADER_DATA_
For a list of feedTypes: Click Here


text:
Q: Faster way to update dataframe rows after group by Sample Input:

    GAME_ID     TIME    PER EVENT
0   0022000394  12:00   1   12
1   0022000394  12:00   1   10
2   0022000394  11:36   1   1
3   0022000394  11:24   1   1
4   0022000394  11:04   1   1
5   0022000394  10:41   1   1
6   0022000394  10:30   1   2
7   0022000394  10:29   1   4
8   0022000394  10:17   1   1
9   0022000394  10:01   1   1
10  0022000394  9:48    1   2
11  0022000394  9:46    1   4
12  0022000394  9:42    1   6
13  0022000394  9:42    1   3
14  0022000394  9:42    1   3
15  0022000394  9:25    1   1
16  0022000394  9:15    1   1
17  0022000394  9:15    1   6
18  0022000394  9:15    1   3
19  0022000394  8:53    1   1
20  0022000394  8:33    1   1
21  0022000394  8:22    1   1
22  0022000394  8:16    1   2
23  0022000394  8:16    1   4
24  0022000394  8:12    1   2

I have a dataframe where I get a group of rows using groupby.
If that group contains 3 rows where the column EVENTMSGTYPE contains all of [1, 6, & 3] I want to update the row in the original dataframe where EVENTMSGTYPE == 1
Current Working Solution (Slow)
# Group by
for _, data in df.groupby(['GAME_ID', 'TIME', 'PER']):

    # If EVENT in group contains 1, 6, and 3 then update original df
    if all(x in list(data.EVENT) for x in [1, 6, 3]):

        # Update original df row where EVENT equals 1, should only have one value
        index = data[data.EVENT == 1].index.values[0]

        # Set UPDATED to True
        df.at[index, 'UPDATED'] = True

Expected Output:
    GAME_ID     TIME    PER EVENT UPDATED
...
16  0022000394  9:15    1   1     True
...

My dataframe has 1,694,389 rows and this takes ~53 seconds to run on my machine, can the performance of this be improved?

A: df['UPDATED'] = df.groupby(['GAME_ID', 'TIME', 'PER'])['EVENT'].filter(lambda x: set(x) >= {1,3,6}, dropna=False).eq(1)

Output:
     GAME_ID   TIME  PER  EVENT  UPDATED
0   22000394  12:00    1     12    False
1   22000394  12:00    1     10    False
2   22000394  11:36    1      1    False
3   22000394  11:24    1      1    False
4   22000394  11:04    1      1    False
5   22000394  10:41    1      1    False
6   22000394  10:30    1      2    False
7   22000394  10:29    1      4    False
8   22000394  10:17    1      1    False
9   22000394  10:01    1      1    False
10  22000394   9:48    1      2    False
11  22000394   9:46    1      4    False
12  22000394   9:42    1      6    False
13  22000394   9:42    1      3    False
14  22000394   9:42    1      3    False
15  22000394   9:25    1      1    False
16  22000394   9:15    1      1     True
17  22000394   9:15    1      6    False
18  22000394   9:15    1      3    False
19  22000394   8:53    1      1    False
20  22000394   8:33    1      1    False
21  22000394   8:22    1      1    False
22  22000394   8:16    1      2    False
23  22000394   8:16    1      4    False
24  22000394   8:12    1      2    False

Stole the set logic from sammywemmy~

A: One option is using set with transform; speed wise I expect Bert2ME's solution to be faster:
df.assign(UPDATED = df.groupby(grouper)
                      .EVENT
                      .transform(lambda x: set(x) >= {1,3,6})
                                           & df.EVENT.eq(1))

     GAME_ID   TIME  PER  EVENT  UPDATED
0   22000394  12:00    1     12    False
1   22000394  12:00    1     10    False
2   22000394  11:36    1      1    False
3   22000394  11:24    1      1    False
4   22000394  11:04    1      1    False
5   22000394  10:41    1      1    False
6   22000394  10:30    1      2    False
7   22000394  10:29    1      4    False
8   22000394  10:17    1      1    False
9   22000394  10:01    1      1    False
10  22000394   9:48    1      2    False
11  22000394   9:46    1      4    False
12  22000394   9:42    1      6    False
13  22000394   9:42    1      3    False
14  22000394   9:42    1      3    False
15  22000394   9:25    1      1    False
16  22000394   9:15    1      1     True
17  22000394   9:15    1      6    False
18  22000394   9:15    1      3    False
19  22000394   8:53    1      1    False
20  22000394   8:33    1      1    False
21  22000394   8:22    1      1    False
22  22000394   8:16    1      2    False
23  22000394   8:16    1      4    False
24  22000394   8:12    1      2    False

A: idx_cols = ['GAME_ID', 'TIME', 'PER']

df = df.set_index(idx_cols)

cond1 = (
    df.groupby(level=idx_cols)['EVENT']
      .agg(lambda event_group: all(x in event_group for x in [1, 6, 3]))
      .reindex_like(df)
)

cond2 = df['EVENT'].eq(1)

df['UPDATED'] = cond1 & cond2

df = df.reset_index()
print(df)

Output:
     GAME_ID   TIME  PER  EVENT  UPDATED
0   22000394  12:00    1     12    False
1   22000394  12:00    1     10    False
2   22000394  11:36    1      1    False
3   22000394  11:24    1      1    False
4   22000394  11:04    1      1    False
5   22000394  10:41    1      1    False
6   22000394  10:30    1      2    False
7   22000394  10:29    1      4    False
8   22000394  10:17    1      1    False
9   22000394  10:01    1      1    False
10  22000394   9:48    1      2    False
11  22000394   9:46    1      4    False
12  22000394   9:42    1      6    False
13  22000394   9:42    1      3    False
14  22000394   9:42    1      3    False
15  22000394   9:25    1      1    False
16  22000394   9:15    1      1     True
17  22000394   9:15    1      6    False
18  22000394   9:15    1      3    False
19  22000394   8:53    1      1    False
20  22000394   8:33    1      1    False
21  22000394   8:22    1      1    False
22  22000394   8:16    1      2    False
23  22000394   8:16    1      4    False
24  22000394   8:12    1      2    False


text:
Q: Javascript: document.execCommand cross-browser? I just stumble on a piece of code which I never saw before:
document.execCommand('Copy');
which seems to copy the clipboard contents to the element in focus.
Is this functionality available cross-browser?

I found a page that shows a compatibility matrix for document.execCommand.

A: Yes, I have used it in IE, Chrome, Safari.  If it works for these browser then it should work for the rest. Anyway, the execCommand method of the document object is used to execute commands relating to the built in Rich Text Editing features in the browser. The syntax of the execCommand is as follow: document.execCommand(command, uiBool, argument)
The command parameter is the command to execute - bold, underline, font, etc.
Then you have the uiBool which is the boolean value that specifies whether or not the default user interface should be shown.
And the last parameter is the argument use for some commands that requires that we pass an argument. If no argument is required by the command we pass a value of null as the third parameter.
Example:
document.getElementById("whateverID").document.execCommand('bold', false, null);

or:
document.getElementById("whateverID").document.execCommand('bold', false, <a variable nae>);

A: Update:  Well, document.execCommand is documented in the Mozilla DOM documentation, but its description there looks slightly different from the MSDN documentation.
I'm still pretty sure it's not in the ECMA-262 standard.

A: This is for 'design mode' where the browser effectively turns the document into an editor.  The execCommand API originated with IE and was later added to HTML5. Exactly which commands are supported, as well as their behavior varies across browsers. Clipboard access is considered a security risk.


text:
Q: mysql insert can't with select into outfile? mysql> insert into helpme set user=(select 0x616361 into outfile 'c://windows//temp//test.ini');
Database changed

mysql> select * from helpme;
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| user                                                                                | id    |
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| a                                                                                |     1 |                                                                                | 37833 |
| aca                                                                                | 37834 |
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
2 rows in set

why user is aca?and can't find the file (c://windows//temp//test.ini)?

A: SELECT … INTO … can't be used in a sub-query:

An INTO clause should not be used in a nested SELECT because such a SELECT must return its result to the outer context.

That's why MySQL chose to return the value instead of writing it into file.


text:
Q: Java -version will not update after SDK installation I am having an issue launching Eclipse saying incorrect JVM version(1.5, needs 1.7+), I installed both Java 7 and 8 from the website but when checking the version in cmd, i am still seeing 1.5
java version "1.5.0_30"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_30-b03)
Java HotSpot(TM) Client VM (build 1.5.0_30-b03, mixed mode)

It was my understanding that when I install a newer jdk, this version would update.  How can I manually update this?
My Java_Home variable is pointing to the newer jdk.
C:\Program Files (x86)\java\jdk1.7.0_79

A: check your PATH environment variable

A: Start eclipse with the -vm argument, followed by the address of the jvm you want to use.
This way, you'll be sure of the version you're using.
Example:
eclipse.exe -vm C:\_jde\Java\jdk1.8.0_45\bin\javaw.exe

A: I think you need to add your JAVA_HOME variable to path as well.
appending the JAVA_HOME like this should set java 7 to default in your system .
%JAVA_HOME%\bin;

or you can check this link to see how to set java.

A: It's most likely that your system variable is still having this. Please recheck your system variable.
Also, you have an option of setting your default JRE:
Open Eclipse.
Navigate to Window > Preferences > Java > Installed JREs
Set your default JRE

A: I face this issue whenever i switch between various Java versions. The solution is below:
Go to c:\Windows\system32
Delete java.exe, javaw.exe, javaws.exe files
Open the command prompt and check the java -version.
Hope this is helpful!


text:
Q: Getting Sprite to fade back in after fade out? Entitiy Modifier Hi im trying to get a sprite to fade in and scale up after fading out and scaling down. For this i used an Entitiy modifier listener but its not working? Heres my code:
public class GameScene {

Scene gameScene;
Engine engine;
Activity activity;

BitmapTextureAtlas mTextureAtlas;
ITextureRegion X;
ITextureRegion O;
ITextureRegion XO;

FadeInModifier fadeIn = new FadeInModifier(2);
FadeOutModifier fadeOut = new FadeOutModifier(2);
ScaleModifier scaleDown = new ScaleModifier(3, 1, 0);
ScaleModifier scaleUp = new ScaleModifier(2, 0, 1);

Sprite XOsprite;
Random rand = new Random();
boolean XYset = false;

public GameScene(Engine eng, Activity act) {
    engine = eng;
    activity = act;
}

public Scene getScene() {

    gameScene = new Scene();
    gameScene.setBackground(new Background(0, 256, 59));
    int x = 0, y = 0;

    if (rand.nextInt(2) == 0) {
        XO = X;
    } else {
        XO = O;
    }

    if (!XYset) {
        x = rand.nextInt(MainActivity.CAM_WIDTH);
        y = rand.nextInt(MainActivity.CAM_HEIGHT);
        XYset = true;
    }

    XOsprite = new Sprite(x, y, XO, engine.getVertexBufferObjectManager()) {
        @Override
        public boolean onAreaTouched(final TouchEvent te, final float xVal,
                final float yVal) {
            XOsprite.registerEntityModifier(fadeOut);
            XOsprite.registerEntityModifier(scaleDown);
            return true;

        }
    };
    IEntityModifierListener fadeOutListener = new IEntityModifierListener() {

        @Override
        public void onModifierStarted(IModifier<IEntity> pModifier,
                IEntity pItem) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onModifierFinished(IModifier<IEntity> pModifier,
                IEntity pItem) {
            // TODO Auto-generated method stub
            XOsprite.clearEntityModifiers();
            XOsprite.setPosition(rand.nextInt(MainActivity.CAM_WIDTH), rand.nextInt(MainActivity.CAM_HEIGHT));
            XOsprite.registerEntityModifier(fadeIn);
            XOsprite.registerEntityModifier(scaleUp);
        }
    };
    fadeOut.addModifierListener(fadeOutListener);
    XOsprite.registerEntityModifier(scaleUp);
    XOsprite.registerEntityModifier(fadeIn);

    gameScene.attachChild(XOsprite);
    gameScene.registerTouchArea(XOsprite);

    return gameScene;
}

The sprite just fades out and nothing happens. I also want the sprite to change to a random position on the screen when it fades back in. Help?

A: If you want to do  fade in and  scale in  parallel then you can use use parallelEntityModifier.
Similarly for  fade out and  scale out  parallel then you can use use parallelEntityModifier.
To run these two in sequence use  SequenceEntityModifier.
Try this it will work.


text:
Q: How i can convert the following SQL Query to Doctrine How can I convert the following SQL Query to Doctrine?
select * from `Leave_types`
where (leave_name = in_leave_name or leave_code=in_leave_code)
and academic_year_id =in_academic_year_id

I trying the follow code:
    $em = $this->doctrine->em;
    $qb = $em->createQueryBuilder();
    $qb->select('lt');
    $qb->from('Entity\LeaveTypes', 'lt');
    $qb->innerjoin('lt.academicYear', 'ay');
    $qb->where('ay.academicId = :academicId');
    $qb->andwhere(
        $qb->orWhere('leaveName', '?1'),
        $qb->orWhere('leaveCode', '?2')
    );
    $qb->setParameter('academicId', $add_data['academic_year_id']);
    $qb->setParameter(1, $add_data['leave_name']);
    $qb->setParameter(2, $add_data['leave_code']);
    $result = $qb->getQuery()->getResult();

A: Thank everyone,
I solve the issue using
 $qb->where('ay.academicId = :academicId');
 $qb->andWhere('lt.leaveName = :leaveName OR lt.leaveCode = :leaveCode');


text:
Q: —- " added in HTML when converting MarkDown file to HTML using Jekyll tool I have used Jekyll tool to convert MarkDown file To HTML. It has been successfully converted to HTML. but the below  following encoded punctuation characters has been added at the top of the HTML, due to the file encoded format is Encode in UTF-8.
  "—-"

After changed the same markdown file to Encode in ANSI format in NotePad++[encoding option in menu bar]. The punctuation character not included in generated HTML.
In this we need to manually change the markdown file to ANSI for HTML generation 'Jekyll'.
Any solution for this?

A:  is the UTF-8 BOM so that's probably what you are seeing, assuming you are looking at it using CP1252; and — is something out of the General Punctuation block.
Proper diagnostics are not possible without an indication of which character encoding you are using instead of UTF-8 to view the file, and/or what exact bytes you have in the file, probably as a hex dump.  The first few bytes (the BOM) would be EF BB BF.  See also the character-encoding tag wiki for troubleshooting tips.
Quick googling indicates that Jekyll is highly allergic to UTF-8 BOM in its input, so it seems unlikely that it generates spurious BOM characters on output.  I could speculate that the template file you are using has a BOM and that it is being faithfully included in the output, but I'm not really familiar enough with Jekyll to actually help troubleshoot any further.
Of course, as per the big ugly warnings all over the Jekyll site, I assume you have already made sure that your Markdown input doesn't have a BOM character.  Many Windows editors are notorious for putting one in when you save as UTF-8; make sure you use "UTF-8 without a BOM" as the "Save As..." format -- and switch to an editor which offers this option if yours doesn't have it.

A: try using charset=utf-8
or
Check your content has any straight double quote (" ") or straight single quote (' ') and remove those
http://practicaltypography.com/straight-and-curly-quotes.html

A: This encoding format issue. make the markdown file in UTF-8 without BOM format.
This will remove the punctuation character in 'html' .


text:
Q: understanding synchronized in java Why usually threading samples put so many code in synchronized block. According to my understanding in following case synchronized is used just for locking b for wait and notify:
Main class ThreadA :
class ThreadA {
      public static void main(String [] args) {
         ThreadB b = new ThreadB();
         b.start();

         synchronized(b) {
            try {
               System.out.println("Waiting for b to complete...");

              b.wait();
           } catch (InterruptedException e) {}
           System.out.println("Total is: " + b.total);
           System.out.println(Thread.currentThread().getName());

        }
     }
  }

and class ThreadB:
class ThreadB extends Thread {
     int total;
     public void run() {
        synchronized(this)
        {
           System.out.println();
           for(int i=0;i<100;i++)
           {
               System.out.println(Thread.currentThread().getName());
              total += i;
           }
           notify();
        }
     }
  }

What will change if I put just wait and notify in synchronized block:
class ThreadA {
      public static void main(String [] args) {
         ThreadB b = new ThreadB();
         b.start();
            try {
               System.out.println("Waiting for b to complete...");

                synchronized(b) {   b.wait();}
           } catch (InterruptedException e) {}
           System.out.println("Total is: " + b.total);
           System.out.println(Thread.currentThread().getName());

     }
  }

A:
According to my understanding in following case synchronized is used just for locking b for wait and notify

Your understanding is wrong.
synchronized is also used for:

*

*Mutual exclusion, to ensure that only one thread executes code "guarded" by a particular monitor at a time

*Ensuring memory access across threads is correct (that one thread sees changes made by another thread)

What will change if I put just wait and notify in synchronized block:

In this particular case, it will make a difference based on a race condition - in the original code, if the new thread starts executing before the synchronized block is reached in the original thread, it won't get as far as "Waiting for b to complete" until the second thread has finished... at which point it will block forever in wait.
Note that it's a really bad idea to wait on Thread monitors, as wait/notify is used internally by Thread.
In short, the example you've used is a bad one to start with in various ways - but synchronization is used for more than just wait/notify.

A: Please note that total += i is not an atomic operation in Java. So you have to sync also this construct.
You also have not to sync notify() and wait() because their locks are handled internally.

A: Expanding on the answer by @sk2212, the increment operation is not atomic, but there is an equivalent atomic operation provided in high-level concurrency primitives.


text:
Q: Calculate area rectangle from latitude and longitude using python I would like to create a polygon assuming it is drawn in a geographic environment using latitude, longitude, bearing, length and width. The code is below:
def get_rotated_points(coordinates, bearing, width, length):
    start = geopy.Point(coordinates)
    width = width / 1000
    length = length / 1000
    rectlength = geopy.distance.distance(kilometers=length)
    rectwidth = geopy.distance.distance(kilometers=width)
    halfwidth = geopy.distance.distance(kilometers=width / 2)
    halflength = geopy.distance.distance(kilometers=length / 2)

    pointAB = halflength.destination(point=start, bearing=bearing)
    pointA = halfwidth.destination(point=pointAB, bearing=0 - bearing)
    pointB = rectwidth.destination(point=pointA, bearing=180 - bearing)
    pointC = rectlength.destination(point=pointB, bearing=bearing - 180)
    pointD = rectwidth.destination(point=pointC, bearing=0 - bearing)

    points = []
    for point in [pointA, pointB, pointC, pointD]:
        coords = (point.latitude, point.longitude)
        points.append(coords)

    return points

The variables are:
v1_coord_5= [41.39129840757358, 2.1658667401858738]
v1_length = 5 #meters
v1_width = 1.8 #meters
v1_bearing=148.26196928529635

points = get_rotated_points(tuple(v1_coord_5), v1_bearing,
                               v1_width, v1_length)

The points results are the following:
POLYGON ((41.39127237180109 2.1658768035733806, 41.39128615544415 2.1658881248848436, 41.391324443338675 2.165856676778987, 41.39131065969457 2.1658453554632664, 41.39127237180109 2.1658768035733806))

So far, I've tried the following:
1)
!pip install area
from area import area
obj = {'type':'Polygon','coordinates':[[[41.39127237180109, 2.1658768035733806],[41.39128615544415, 2.1658881248848436],[41.391324443338675, 2.165856676778987],[41.39131065969457, 2.1658453554632664],[41.39127237180109, 2.1658768035733806]]]}
area(obj)

Result: 10.735455561073895
2)
!pip install pyproj

co = {"type": "Polygon", "coordinates": [
    [(41.39127237180109, 2.1658768035733806),
     (41.39128615544415, 2.1658881248848436),
     (41.391324443338675, 2.165856676778987),
     (41.39131065969457, 2.1658453554632664)]]}
lon, lat = zip(*co['coordinates'][0])
from pyproj import Proj
pa = Proj("+proj=aea +lat_1=37.0 +lat_2=41.0 +lat_0=39.0 +lon_0=-106.55")
x, y = pa(lon, lat)
cop = {"type": "Polygon", "coordinates": [zip(x, y)]}
from shapely.geometry import shape
shape(cop).area  # 268952044107.43506

Result: 10.663792266425144
3)
from shapely.geometry import Polygon

points = [(41.39127237180109, 2.1658768035733806), (41.39128615544415, 2.1658881248848436), (41.391324443338675, 2.165856676778987), (41.39131065969457, 2.1658453554632664), (41.39127237180109, 2.1658768035733806)]
polygon = Polygon(points)
area_sdeg = polygon.area

Result: 8.669387666688732e-10
If I use a regular formula, the result is 9 m2. Unfortunately, I couldn't get that result. Any clue what I'm missing? thanks


text:
Q: How to show in a ListView a Tree of Strings? I have a Map<String, dynamic>, where dynamic is a dynamic tree of Strings. I need to show in a ListView (or another Widget that allow to show a Tree structure) the Strings and their children. Each String is a collapsable item (if has children) of the ListView. For example:
Text
     text
           text
           text
     text
text
     text
text
text

this is the code of an example of the tree:
void main() {
  Map<String, dynamic> joinTrees(int level, int maxLevel,
      List<List<String>> trees, Map<String, dynamic> tmpMap) {
    if (maxLevel < 0) return {};
    List<String> nodes = trees.map((tree) => tree[level]).toSet().toList();
    print(nodes);

    for (String node in nodes) {
      List<List<String>> childrenBranchs =
          trees.where((tree) => tree[level] == node).toList();
      if (childrenBranchs.length == 1 &&
          childrenBranchs[0][childrenBranchs[0].length - 1] == node) {
        print("leaf: " + node);
        tmpMap[node] = null;
      } else {
        Map<String, dynamic> childrenTree = joinTrees(
            level + 1, maxLevel, childrenBranchs, new Map<String, dynamic>());
        print("node: " + node);
        tmpMap[node] = childrenTree;
      }
    }
    return tmpMap;
  }

  List<List<String>> trees = [
    ["A", "A11", "A21"],
    ["A", "A12"],
    ["A", "A11", "A22"],
    ["B", "B11", "B21"],
    ["C"]
  ];
  int maxLength = trees
      .map((tree) => tree.length)
      .toList()
      .reduce((curr, next) => curr > next ? curr : next);
  int maxLevel = maxLength - 1;

  print(trees);
  print(maxLength);
  Map<String, dynamic> joinedTree =
      joinTrees(0, maxLevel, trees, new Map<String, dynamic>());
  print(joinedTree);
}

this is de ouput of joinedTree:
{
 A:
    {
     A11:
          {
           A21: null,
           A22: null
          },
     A12: null
    },
 B:
    {
     B11:
         {
           B21: null
         }
    },
 C: null

}

A: if your tree look like this, detail Entry class please reference full code
final List<Entry> data = <Entry>[
  Entry(
    'A',
    <Entry>[
      Entry(
        'A11',
        <Entry>[
          Entry('A21'),
          Entry('A22'),
        ],
      ),
      Entry('A12'),
    ],
  ),
  Entry(
    'B',
    <Entry>[
      Entry(
        'B11',
        <Entry>[
          Entry('B21'),
        ],
      ),
    ],
  ),
  Entry(
    'C',
  ),
];

inside ListView.builder, build item with
Widget _buildTiles(Entry root) {
    if (root.children.isEmpty) {
      return Padding(
        padding: const EdgeInsets.only(left: 10.0),
        child: ListTile(title: Text(root.title)),
      );
    }
    return Padding(
      padding: const EdgeInsets.only(left: 10.0),
      child: ExpansionTile(
        key: PageStorageKey<Entry>(root),
        title: Text(root.title),
        children: root.children.map(_buildTiles).toList(),
      ),
    );
  }

full code
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: ExpansionTileSample(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class ExpansionTileSample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('ExpansionTile'),
        ),
        body: ListView.builder(
          itemBuilder: (BuildContext context, int index) =>
              EntryItem(data[index]),
          itemCount: data.length,
        ),
      ),
    );
  }
}

// One entry in the multilevel list displayed by this app.
class Entry {
  Entry(this.title, [this.children = const <Entry>[]]);

  final String title;
  final List<Entry> children;
}

// The entire multilevel list displayed by this app.
final List<Entry> data = <Entry>[
  Entry(
    'A',
    <Entry>[
      Entry(
        'A11',
        <Entry>[
          Entry('A21'),
          Entry('A22'),
        ],
      ),
      Entry('A12'),
    ],
  ),
  Entry(
    'B',
    <Entry>[
      Entry(
        'B11',
        <Entry>[
          Entry('B21'),
        ],
      ),
    ],
  ),
  Entry(
    'C',
  ),
];

// Displays one Entry. If the entry has children then it's displayed
// with an ExpansionTile.
class EntryItem extends StatelessWidget {
  const EntryItem(this.entry);

  final Entry entry;

  Widget _buildTiles(Entry root) {
    if (root.children.isEmpty) {
      return Padding(
        padding: const EdgeInsets.only(left: 10.0),
        child: ListTile(title: Text(root.title)),
      );
    }
    return Padding(
      padding: const EdgeInsets.only(left: 10.0),
      child: ExpansionTile(
        key: PageStorageKey<Entry>(root),
        title: Text(root.title),
        children: root.children.map(_buildTiles).toList(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildTiles(entry);
  }
}


text:
Q: Saving/retrieving file in ProgramData folder using OfficeJS I am new in "Apps for Office" development. I am using task pane in my add-in. From my add-in I am trying to save some file to "C:\ProgramData" folder. In VSTO I can easily access local folders using C# code and save file there:
SpecialFolder.CommonApplicationData

Is there any way to have the local file access using OfficeJS and save a file there? My point is that as OfficeJs using word context and word can save file anywhere my local pc, so there may be a way of saving file in local PC programmatically.
I have checked the OfficeJS document and also searched in stack overflow but do not find any way to do that. Is it possible to do? If possible what is the proper way to implement this ?
Again I am new in "Apps for Office" development. I may miss any initial knowledge regarding my question. Please refer me the proper way. Thanks in advance for any types of help.

A: Office.js Add-ins are web apps hosted within the context of an Office application. Generally speaking, anything you can do in a traditional browser can be done within an add-in. They are inherently cross-platform, designed to work across Windows, Mac, iOS, Android and Web.
This particular scenario doesn't work however. You could trigger the download of a .lnk file but you would have to instruct the user how and where to save it. More importantly, only Windows would understand what to do with this file type. Other platforms don't store web links in the same manor or in the same location.


text:
Q: Error 502 when attempting Gitlab Jenkins webhook I'm trying to set up a webhook between both my Gitlab server and Jenkins server, however when using the "test" dropdown box in Gitlab's webhook page, I receive the following error:
Hook executed successfully but returned HTTP 502  <title>502 Bad Gateway</title>
502 Bad Gateway

nginx/1.10.3

Is there an easy way to resolve this problem? Or at least some ways to troubleshoot the issue? I don't get any output when I set up a system logger on Jenkins for com.dabsquared.gitlabjenkins... Thanks in advance.


text:
Q: Recursively decompressing a string that was compressed using RLE I'm trying to write a method that decompresses a string that was compressed using the RLE format recursively. So, I want a method that converts "5a2*3h32" into "aaaaa**hhh222".
Input: 5a2*3h32
Output: aaaaa**hhh222 --> this is correct
Input: i24 (should be: i44)
Output: Exception in thread "main" java.lang.NumberFormatException: For input string: "i"
So basically it doesn't like when a character is not preceded by a digit. However, if the input had one lone character at the end of the string, the method works fine.
I can't seem to figure this out. Any input would be really helpful!
public static String decompress(String compressedText){
    char c = ' ';
    String temp;

    if(compressedText.length() != 1){
        c = compressedText.charAt(1);
    }if(compressedText.length() == 1){
        return compressedText;
    }else if(compressedText.charAt(0) == '0' && compressedText.length() != 2){
        return decompress(compressedText.substring(2));
    }else if(compressedText.charAt(0) == '0' && compressedText.length() == 2){
        compressedText = "\0";
        return compressedText;
    }else if(Character.isLetterOrDigit(c) == true || Character.isLetterOrDigit(c) == false){
        int i = Integer.parseInt(compressedText.substring(0,1));
        i = i-1;
        temp = Integer.toString(i);
        return c + decompress(temp.concat(compressedText.substring(1)));
    }if(Character.isLetter(c) == false){
        c = compressedText.charAt(2);
        int i = Integer.parseInt(compressedText.substring(0,2));
        i = i-1;
        temp = Integer.toString(i);
        return c + decompress(temp.concat(compressedText.substring(2)));
    }
    return compressedText;
}

A: As I commented the problem was with your condition, I change it a little bit and now it is working:
public static String decompress(String compressedText){
    char c = ' ';
    String temp;

    if(compressedText.length() != 1){
        c = compressedText.charAt(1);
    }if(compressedText.length() == 1){
        return compressedText;
    }else if(compressedText.charAt(0) == '0' && compressedText.length() != 2){
        return decompress(compressedText.substring(2));
    }else if(compressedText.charAt(0) == '0' && compressedText.length() == 2){
        compressedText = "\0";
        return compressedText;
    }else if(Character.isDigit(compressedText.charAt(0)) == true){
        int i = Integer.parseInt(compressedText.substring(0,1));
        i = i-1;
        temp = Integer.toString(i);
        return c + decompress(temp.concat(compressedText.substring(1)));
    }
    return compressedText.charAt(0)+decompress(compressedText.substring(1));
}

checkout the online version here.


text:
Q: TF object detection: return subset of inference payload Problem
I'm working on training and deploying an instance segmentation model using TF's object detection API. I'm able to successfully train the model, package it into a TF Serving Docker image (latest tag as of Oct 2020), and process inference requests via the REST interface. However, the amount of data returned from an inference request is very large (hundreds of Mb). This is a big problem when the inference request and processing don't happen on the same machine because all that returned data has to go over the network.
Is there a way to trim down the number of outputs (either during model export or within the TF Serving image) so allow faster round trip times during inference?
Details
I'm using TF OD API (with TF2) to train a Mask RCNN model, which is a modified version of this config. I believe the full list of outputs is described in code here. The list of items I get during inference is also pasted below. For a model with 100 object proposals, that information is ~270 Mb if I just write the returned inference as json to disk.
inference_payload['outputs'].keys()
dict_keys(['detection_masks', 'rpn_features_to_crop', 'detection_anchor_indices', 'refined_box_encodings', 'final_anchors', 'mask_predictions', 'detection_classes', 'num_detections', 'rpn_box_predictor_features', 'class_predictions_with_background', 'proposal_boxes', 'raw_detection_boxes', 'rpn_box_encodings', 'box_classifier_features', 'raw_detection_scores', 'proposal_boxes_normalized', 'detection_multiclass_scores', 'anchors', 'num_proposals', 'detection_boxes', 'image_shape', 'rpn_objectness_predictions_with_background', 'detection_scores'])

I already encode the images within my inference requests as base64, so the request payload is not too large when going over the network. It's just that the inference response is gigantic in comparison. I only need 4 or 5 of the items out of this response, so it'd be great to exclude the rest and avoid passing such a large package of bits over the network.
Things I've tried

*

*I've tried setting the score_threshold to a higher value during the export (code example here) to reduce the number of outputs. However, this seems to just threshold the detection_scores. All the extraneous inference information is still returned.

*I also tried just manually excluding some of these inference outputs by adding the names of keys to remove here. That also didn't seem to have any effect, and I'm worried this is a bad idea because some of those keys might be needed during scoring/evaluation.

*I also searched here and on tensorflow/models repo, but I wasn't able to find anything.

A: I was able to find a hacky workaround. In the export process (here), some of the components of the prediction dict are deleted. I added additional items to the non_tensor_predictions list, which contains all keys that will get removed during the postprocess step. Augmenting this list cut down my inference outputs from ~200MB to ~12MB.
Full code for the if self._number_of_stages == 3 block:
    if self._number_of_stages == 3:

      non_tensor_predictions = [
          k for k, v in prediction_dict.items() if not isinstance(v, tf.Tensor)]

      # Add additional keys to delete during postprocessing
      non_tensor_predictions = non_tensor_predictions + ['raw_detection_scores', 'detection_multiclass_scores', 'anchors', 'rpn_objectness_predictions_with_background', 'detection_anchor_indices', 'refined_box_encodings', 'class_predictions_with_background', 'raw_detection_boxes', 'final_anchors', 'rpn_box_encodings', 'box_classifier_features']

      for k in non_tensor_predictions:
        tf.logging.info('Removing {0} from prediction_dict'.format(k))
        prediction_dict.pop(k)

      return prediction_dict

I think there's a more "proper" way to deal with this using signature definitions during the creation of the TF Serving image, but this worked for a quick and dirty fix.

A: I've ran into the same problem. In the exporter_main_v2 code there is stated that the outputs should be:
and the following output nodes returned by the model.postprocess(..):
  * `num_detections`: Outputs float32 tensors of the form [batch]
      that specifies the number of valid boxes per image in the batch.
  * `detection_boxes`: Outputs float32 tensors of the form
      [batch, num_boxes, 4] containing detected boxes.
  * `detection_scores`: Outputs float32 tensors of the form
      [batch, num_boxes] containing class scores for the detections.
  * `detection_classes`: Outputs float32 tensors of the form
      [batch, num_boxes] containing classes for the detections.

I've submitted an issue on the tensorflow object detection github repo, I hope we will get feedback from the tensorflow dev team.
The github issue can be found here

A: If you are using exporter_main_v2.py file to export your model, you can try this hack way to solve this problem.
Just add following codes in the function _run_inference_on_images of exporter_lib_v2.py file:
    detections[classes_field] = (
        tf.cast(detections[classes_field], tf.float32) + label_id_offset)

############# START ##########
    ignored_model_output_names = ["raw_detection_boxes", "raw_detection_scores"]
    for key in ignored_model_output_names:
        if key in detections.keys(): del detections[key]
############# END ##########

    for key, val in detections.items():
      detections[key] = tf.cast(val, tf.float32)

Therefore, the generated model will not output the values of ignored_model_output_names.
Please let me know if this can solve your problem.

A: Another approach would be to alter the signatures of the saved model:
model = tf.saved_model.load(path.join("models", "efficientdet_d7_coco17_tpu-32", "saved_model"))

infer = model.signatures["serving_default"]
outputs = infer.structured_outputs
for o in ["raw_detection_boxes", "raw_detection_scores"]:
    outputs.pop(o)

tf.saved_model.save(
    model,
    export_dir="export",
    signatures={"serving_default" : infer},
    options=None
)


text:
Q: Kotlin HttpClient and HttpRequest unresolved reference errors on Intelij-idea I can't get references to HttpClient and HttpRequest to import/map properly in my Kotlin code. I'm new to Kotlin, so I might not being configuring the project correctly. I tried this both on Mac and Windows machines, and ran into the same issue.
My Import statements:
import io.jsonwebtoken.Header
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.io.Decoders
import io.jsonwebtoken.security.Keys
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.security.Key
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.util.*
import kotlin.collections.HashMap

Lines causing issues in inside the main fuction:
val client = HttpClient.newBuilder().build();
val request = HttpRequest.newBuilder()
    .uri(URI.create("https://openapi.example.com/example/"))
    .header("Authorization", "Bearer $jwt")
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .build();

I receive unresolved reference errors:

Configuration:

*

*Intelij-IDEA with Kotlin (latest)

*Amazon Corretto 17

*Gradle 8.0.1

A: The import java.net.http.HttpClient was added in JDK 11 but your Gradle configuration should still uses a lower language level.
Try to open your build.gradle/build.gradle.kts, and change your jvmToolchain to 17. Reload the Gradle in IDEA.


text:
Q: Inverse x axis in the hexbinplot Is it possible to reverse x-axis for the hexbinplot?
hexbinplot(y~x, xbins=30,xlim = rev(range(x)))

The option  xlim = rev(range(x)) did not work out.

A: I don't know how to do this with hexbin::hexbinplot, but it's pretty easy with ggplot2, using geom_hex and scale_x_reverse.
 dd <- data.frame(x=rnorm(1000),y=rnorm(1000))
 ggplot(dd,aes(x,y))+geom_hex()+scale_x_reverse()

A: You can mulitply the x by -1 to reverse the plot, and then use the scales argument to reverse the labels
set.seed(1)
dd <- data.frame(x=rnorm(1000),y=rnorm(1000))
y = dd$y ; xnew=-dd$x

library(hexbin)
hexbinplot(y ~ xnew, scales=list(x=list(at = pretty(xnew),
                                        labels = rev(pretty(xnew)))))


text:
Q: Fast way of generating non-repeating bytes in a random reproducible order I need a fast way to generate 256 rows, each with 256 random bytes and no duplicates.
The lookup tables are generated in such way the element in the first table points to the element from the 2nd table that points to the one in the 1st table, but that's not the point.
This is what I have so far (kinda slow, especially the while (random_int >= (int)unused.size()) part):
unsigned char lookup_table[256 * 256];
unsigned char lookup_table_inverted[256 * 256];

std::vector<unsigned char> unused;
std::mt19937_64 rng(seed);
std::uniform_int_distribution<int> dist(0, 255);
int random_int;

for (int i = 0; i < 256; ++i)
{
    for (int j = 0; j < 256; ++j)
    {
        unused.push_back((unsigned char)j);
    }

    for (int j = 0; j < 256; ++j)
    {
        random_int = dist(rng);
        while (random_int >= (int)unused.size())
        {
            random_int = dist(rng);
        }

        lookup_table[(i * 256) + j] = unused[random_int];
        lookup_table_inverted[(i * 256) + unused[random_int]] = (unsigned char)j;
        unused.erase(unused.begin() + random_int);
    }
}

SOLVED: Using std::shuffle() and std::iota().

A: Just use the standard algorithms, specifically std::shuffle() and std::iota.
Don't try to bake your own, it's error-prone and likely inefficient.
unsigned char lookup_table[256 * 256];
unsigned char lookup_table_inverted[256 * 256];
for (int i = 0; i < 256; ++i) {
     auto start = lookup_table + 256 * i;
     std::iota(start, start + 256, 0);
     std::shuffle(start, start + 256, rng);
     auto rev = lookup_table_inverted + 256 * i;
     for (int c = 0; c < 256; ++c)
         rev[start[c]] = c;
}

A: I would use std::shuffle maybe something like this:
std::array<unsigned char, 256> get_random_bytes(int seed = 0)
{
    thread_local static std::mt19937 mt{std::random_device{}()};

    if(seed)
        mt.seed(seed);

    std::array<unsigned char, 256> bytes;

    // fill with the full range of values
    std::iota(std::begin(bytes), std::end(bytes), 0);
    std::shuffle(std::begin(bytes), std::end(bytes), mt); // randomly shuffle them

    return bytes;
}

If you supply the function with a non-zero argument it is used to seed the PRNG making the results reproducable.


text:
Q: Why do you we say a is congruent to b mod n and not equal? When talking about modulos why is that we use congruency and not equality?
From the accepted answer in the post What is the difference between congruency and equality? It states that:

... two figures are equal if they have the same points.
Congruent figures have the same shape and size (informally) but
possibly different points.

Which confuses me since I think 7 mod 4 results in the same value or the same point as 3.

A: This is mostly a question of taste; but there's very, very good reason for that taste. Indeed, it's important to disambiguate things thoroughly to make sure we're correct when it concerns technical details.
Generally, the core factor where you can say "7 is equal to 3" without the fear mistaken is being in the right context, namely, being in the space $\mathbb{Z}/4\mathbb{Z}$. In this "four hour clock", $7$ and $3$ are indeed equal, but it's not the $7$ and $3$ that you know from $\mathbb{Z}$, it's one element, generally written with a hat, like so: $\hat{-1} = \hat3 = \hat 7$. The way we write this element refers to $\mathbb{Z}$, since we construct $\mathbb{Z}/4\mathbb{Z}$ from $\mathbb{Z}$; so it helps our intuition. But I could just as well forbid you from writing in a way that refers to $\mathbb{Z}$, and decide to write $\mathbb{Z}/4\mathbb{Z} = \{ 0, \alpha, \beta, \gamma \}$.
In the context of $\mathbb{Z}$ itself, $3$ and $7$ are NEVER equal. They are only EQUIVALENT, relative to the equivalence relation of congruence modulo 4. From any equivalence relation, you can make an algebraic quotient, and in the resulting space, the elements now become equal: $7$ and $3$ are both mapped to a single element $\gamma$, and their results are then equal. But you must never lose track of the space/context in which things are happening, since this is ripe for misuse and mistake.


text:
Q: How to update choropleth map in Dash I'm making a webapp using Python and Dash, this webapp includes a choropleth map of the world with data based on the selected year. I want to be able to change the year and with that also update the map to match that year. I prefer to do this with the Dash slider, although any other way I would appreciate as well.
I've tried updating other graphs such as line charts with the text input, and that worked, but when i changed it to a choropleth map it stopped updating. It now only creates the map but updates on it don't show up. I've put some print text in the update function and it confirmed that it is actually called when I change the input, but the graph just doesn't update.
The layout:with the dcc.input i want to update the html.Div 'my-div'
app.layout = html.Div( children=[
    html.H1(
        children='UN Sustainable Development goal: Poverty',
        style={
            'textAlign': 'center',
            'color': colors
        }
    ),
    dcc.Input(id='my-id',value='30', type='text'),
    html.Div(id='my-div')
    ,
    daq.Slider(
        id='my-daq-slider',
        min=1,
        max=sliderlength,
        step=1,
    ),
    html.Div(id='slider-output')

],        style={
        'textAlign': 'center'
    })

The update part
@app.callback(
    Output('my-div', 'children'),
    [Input('my-id', 'value')])

def update_output_div(input_value):
    return dcc.Graph(
        id='my-div',

        figure={'data': [go.Choropleth(
    locations = df_pov['Country Code'],
    z = df_pov.iloc[:,int(input_value)],
    text = df_pov['Country Name'],

    autocolorscale = True,
    reversescale = False,
    marker = go.choropleth.Marker(
        line = go.choropleth.marker.Line(
            color = 'rgb(180,180,180)',
            width = 0.5
        )),
    colorbar = go.choropleth.ColorBar(
        tickprefix = '%',
        title = '%  below 1.90$ '),
)],
                'layout': go.Layout(
    title = go.layout.Title(
        text = list(df_pov)[int(input_value)]
    ),
    geo = go.layout.Geo(
        showframe = False,
        showcoastlines = False,
        projection = go.layout.geo.Projection(
            type = 'equirectangular'
        )
    ),
    annotations = [go.layout.Annotation(
        x = 0.55,
        y = 0.1,
        xref = 'paper',
        yref = 'paper',
        text = 'Source: Kaggle',
        showarrow = False
    )]
)
        }
    )

What i expected: for the choropleth to update when changing the text input, or slider input.
Actual: the map gets created once ( with the same function that should update it), but doesn't update.

A: Dash doesn't like new components being loaded in like this. Try initializing your graph by adding an empty graph to the layout like this:
html.Div(id='my-div', children=[
        dcc.Graph(
            id='my-graph-id',
            figure=dict(
                data=[],
                layout={},
            ),
        )
    ])

With the graph already on the page, you would have to change the callback so that it updates the figure prop of the Graph instead of the children of the div.
Also, you have multiple IDs that are the same. Dash doesn't like that. Make sure every ID is unique. If all of this still does not work, I may need to ask you to post some more details so I can help further. Good luck!


text:
Q: How to redirect in React.js I would like to ask you about redirecting in React.js.
Below is modified thing of Home.js in https://github.com/supasate/connected-react-router/blob/master/examples/basic/src/components/Home.js
(It's NOT my private GitHub Repo! It's open source library)
import React, { useState } from 'react'
import { Redirect } from 'react-router-dom'

const Home = () => {
  console.log('Home');

  const renderRedirect = () => {
    return <Redirect to={{
      pathname: '/counter'
    }} />
  }

  const clicked = () => {
    console.log('clicked');
    return <Redirect to={{
      pathname: '/counter'
    }} />
  }

  return (

      Home
      {/* {renderRedirect()} */}
      <button onClick={() => clicked()}>counter</button>

  )
}

export default Home

The function renderRedirect() is commented in  tag now. And if I uncomment this function, this function and redirecting work well.
But when I clicked a button in  tag, redirecting won't work. Why does redirecting have no effect?
Thanks for reading.

A: try in this way :
import React, { useState } from 'react'
import { Redirect } from 'react-router-dom'

const Home = () => {
  console.log('Home');
  constructor(props){
   this.state={
    isRedirect : false;
 }
}
  const renderRedirect = () => {
  if (this.state.isRedirect) {
    return (
     <Redirect to={{
      pathname: '/counter'
     }}
    />
   );
 }
}

  const clicked = () => {
    console.log('clicked');
    this.setState({
     isRedirect :true
    })
  }

  return (

      Home
       {renderRedirect()}
      <button onClick={() => clicked()}>counter</button>

  )
}

export default Home;

A: There is no redirecting scenario in the react. Instead it just re render the particular component. That's why it is recognized as virtual DOM. In your scenario the component is not re rendering.

A: Clicked function is only returning Redirect component. But it is not getting appended in the JSX anywhere. Triggering it is one part and appending it is second. Commenting out renderRedirect means you are missing the second step.


text:
Q: Git not working on nfs share First, the setup. I'm running a haneWin nfs server on a Windows Server 2012, mounting it at startup in a ubuntu server with this fstab entry ~ip~:/sharenfs /srv/share nfs rw 0 0
The umask is set on the windows server to 000, which indeed results in every user on ubuntu having rw access to the entire share.
Now here's the problem: I want to use the nfs share to store all our git repos so that the windows server can back them up together with all its data. In an earlier setup the ubuntu host provided a nfs share which worked perfect, but for storage reasons the windows server should host the share.
The git repos are supposed to be created automatically by redmine, which worked fine prior to the nfs change, but now it just fails silently. The logs dont provide any useful information.
But here's something that does provide information, if I create a new directory on the nfs share, run git init, the following comes out:
error: could not lock config file /srv/share/git/metatest/test1/.git/config: File exists
... (this line shows a total of 6 times)
error: could not lock config file /srv/share/git/metatest/test1/.git/config: File exists
Reinitialized existing shared Git repository in /srv/share/git/metatest/test1/.git/

The dir was completely empty! In fact running rm -rf .git; git init has the same output.
A ls -lAhR shows this
./.git:
total 22K
drwxrwxrwx 2 git git 4.0K Jun  5 17:07 branches/
-rw-rw-rw- 1 git git   53 Jun  5 17:07 config
-rw-rw-rw- 1 git git   21 Jun  5 17:07 config.lock
-rw-rw-rw- 1 git git   73 Jun  5 17:07 description
-rw-rw-rw- 1 git git   23 Jun  5 17:07 HEAD
drwxrwxrwx 2 git git 4.0K Jun  5 17:07 hooks/
drwxrwxrwx 2 git git 4.0K Jun  5 17:07 info/
drwxrwxrwx 4 git git 4.0K Jun  5 17:07 objects/
drwxrwxrwx 4 git git 4.0K Jun  5 17:07 refs/

./.git/branches:
total 0

./.git/hooks:
total 17K
-rwxrwxrwx 1 git git  452 Jun  5 17:07 applypatch-msg.sample*
-rwxrwxrwx 1 git git  896 Jun  5 17:07 commit-msg.sample*
-rwxrwxrwx 1 git git  189 Jun  5 17:07 post-update.sample*
-rwxrwxrwx 1 git git  398 Jun  5 17:07 pre-applypatch.sample*
-rwxrwxrwx 1 git git 1.7K Jun  5 17:07 pre-commit.sample*
-rwxrwxrwx 1 git git 1.3K Jun  5 17:07 prepare-commit-msg.sample*
-rwxrwxrwx 1 git git 1.4K Jun  5 17:07 pre-push.sample*
-rwxrwxrwx 1 git git 4.8K Jun  5 17:07 pre-rebase.sample*
-rwxrwxrwx 1 git git 3.6K Jun  5 17:07 update.sample*

./.git/info:
total 512
-rw-rw-rw- 1 git git 240 Jun  5 17:07 exclude

./.git/objects:
total 8.0K
drwxrwxrwx 2 git git 4.0K Jun  5 17:07 info/
drwxrwxrwx 2 git git 4.0K Jun  5 17:07 pack/

./.git/objects/info:
total 0

./.git/objects/pack:
total 0

./.git/refs:
total 8.0K
drwxrwxrwx 2 git git 4.0K Jun  5 17:07 heads/
drwxrwxrwx 2 git git 4.0K Jun  5 17:07 tags/

./.git/refs/heads:
total 0

./.git/refs/tags:
total 0

Interestingly though when redmine tries to create a repository the directory isnt even created. Again, it fails silently, no useful output.
When I try to run git add or from a remote pc push any changes from existing repos that where created when redmine did work, I get
fatal: error when closing sha1 file: Permission denied

This all makes absolutely no sense to me. Any ideas?

A: The question might not be entirely right about the cause of the problem. It turned out, that the gitolite installation had been broken by porting it over to a SMB mount, and then after moving it to an NFS mount the problem persisted.
I can't tell for sure if that's what happened, but right now it's working on an NFS share and this is my most probable explanation.
Another explanation would be that hanewin nfs was the problem, since right now running the Windows Server 2012 NFS Server it's working.


text:
Q: about advance in STL the define of function advance() is :
template<class InIt, class Dist>
void advance(
        InIt& it,
        Dist n
);

when i use this function in my code:
string strArr[10];
strArr[0] = string("dd");
strArr[1] = string("gg");
strArr[2] = string("tt");
const vector<string> vecStr(strArr, strArr+6);
advance(vecStr.begin(), 2);
cout<<*(vecStr.begin())<<endl; // the output is dd

You know the first parameter in function advance() is reference, so after advance(vecStr.begin(), 2);, verStr.begin() should point to vecStr[2].
But from the output we find vecStr.begin() points to str[0].
I want to know wy?

A: advance(vecStr.begin(), 2);
cout<<*(vecStr.begin())<<endl; // the output is dd

You are using two different iterators, one of which you use advance on, and the other which you use in printing.
For your code to work, use advance and cout on the same iterator
auto iter = vecStr.begin();
advance(iter , 2);
cout << *iter << endl;

Just a comment in your original code, advance(vecStr.begin(), 2); won't actually compile, at least if you are using strict compiler settings. vecStr.begin() returns a temporary object, one which cannot be bound to the first parameter of std::advance which is an l-value reference.

Also, std::vector::begin() logically returns a copy of the actual begin iterator inside the vector, not a reference to it. This means that whatever you do to the returned iterator will not be reflected to the begin iterator inside the vector. I'm talking about the iterators here, not the elements they point to.

A: std::advance will not change iterator underneath std::vector, also your advance on a temporary iterator
// this will advance on a temporary iterator returned from vecStr.begin()
// it shouldn't compile as C++ doesn't allow bind reference to temporary object
advance(vecStr.begin(), 2);

The reason you could compile your code is that you are using Visual Sutdio extention C4239, sometimes known as evil extension.
You should do:
auto biter = vecStr.begin();    // biter points to begin of vecStr
std::advance(biter, 2);         // advance biter by 2 position
std::cout<< *biter << std::endl;

A: vector::begin() is a function returning an iterator. You can't change what begin() returns by modifying the iterator it returns - you can only change what it returns by modifying the vector contents.
Try this instead:
auto it = vecStr.begin();
advance(it, 2);
cout<<*(it)<<endl;

A: Your code does not compile under a standards conforming compiler. I'm guessing you're using Visual Studio and your warning level isn't high enough to tell you about taking references of temporaries.
vector::begin() does not return a reference to an iterator. It returns an iterator by value; it returns a temporary. std::advance's first parameter is a non-const reference. And those are, in standard C++, not allowed to bind to an argument that is a temporary. So your code fails to compile.
But on VS, where this is allowed, this doesn't do what you want because you're advancing a temporary object, not what's actually "stored" in the vector. After all, a vector may not actually store these things; they may be generated from arbitrary data. So you can't simply modify iterators in a vector, because a vector may not have iterators in it.


text:
Q: How can I sort multiple arrays in PHP with values being dependent on each other to be in the same position? I'm trying to create these array maps of values, but I need them to be sorted in a way were different values are dependent on each other being in the same position. You could view them as distribution maps but within each map they "belong" to other values in other arrays. There is a master array which holds the relations between values.
All arrays are 100% identical in length. It's almost like "a table" where each row is the individual array.
These are the arrays I have (pseudo):
$array1 = [1,2,3,4,5];
$array2 = [6,7,8,9,10];
$array3 = [11,12,13,14,15];

And this is my master list of dependencies (basically how they depend on each other):
$sort = [[1,7,13],[2,6,11],[1,8,15]];

As you can see not all values are present. It's only the values being dependent on each other that are present. How can I now achieve my outcome which is theory would be something like this:
$array1 = [1,2,3,4,5];
$array2 = [7,6,8,9,10];
$array3 = [13,11,15,12,14];

Notice how "8" and "15" doesn't really have anything more to map against so they are just left as combined at the end of their own array. This isn't super important, they could be randomized to just keep the first keys of the array intact for as long as it's possible to create the sorting as intended.


text:
Q: Is there a way to edit 'record' object in List view at the client side in Admin-on-rest? I'm using Admin-on-rest (1.3.2) and I'm trying to build a custom list view with input text fields and a 'Save' button.
By clicking 'Save' I want it to take all the values in the input fields for the current row and send it to the backend.
I'm struggling to share the fields state so that the 'Save' button will get those values and do it propose.
import React from 'react';
import {Datagrid, List} from 'admin-on-rest'
import TextField from 'material-ui/TextField/TextField.js';
import RaisedButton from 'material-ui/RaisedButton';

export const PostList = (props) => (
  <List title="IMDB Top Feature Films 2017" {...props}>
    <Datagrid>
      <InputTextField source="id"/>
      <InputTextField source="title"/>
      <InputTextField source="body"/>
      <SaveButton />
    </Datagrid>
  </List>
);

const InputTextField = ({source, record = {}}) => <TextField defaultValue={record[source]}/>;
const SaveButton = ({source, record = {}}) => <RaisedButton label="Save"/>;

List with input field example:

A: import React from 'react';
import {Datagrid, List} from 'admin-on-rest'
import TextField from 'material-ui/TextField/TextField.js';
import RaisedButton from 'material-ui/RaisedButton';

export class PostList extends React.Component {
  constructor() {
    this.state = {
     id: "",
     title: "",
     body: "",
    };
  }

  setValueInState = (field, value) => {
    this.setState({
      [field]: value
    });
  };

  save = () => {
    const {id, title, body} = this.state;
    // write your saving log here
  };

  render() {
    return (
      <List title="IMDB Top Feature Films 2017" {...props}>
        <Datagrid>
          <InputTextField setValueInState={setValueInState} source="id"/>
          <InputTextField setValueInState={setValueInState} source="title"/>
          <InputTextField setValueInState={setValueInState} source="body"/>
          <SaveButton save={save} />
        </Datagrid>
      </List>
    );
  }
}

const InputTextField = ({source.setValueInState, record = {}}) => <TextField defaultValue={record[source]} onChange={setValueInState}/>;

const SaveButton = ({source, record = {}}) => <RaisedButton label="Save"/>;

Please check for the brackets. Idea is on the similar lines that I showed in the code.


text:
Q: How to set filtered views from Button clicks in the same View in swiftui? I have more than three button which comes from Api with id and when I clicked the buttons then I want to set the new views according to id
this is my main View
struct CategoriesView: View {

  @StateObject var list =
    CategoriesViewModel(_httpUtility: HttpUtility())
  @State var pressed: Bool = true
  @State var id: Int = 1
  @State var subId: Int = 19
  private var columns = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]

  var body: some View {

    NavigationView {
      VStack {
        ScrollView(.horizontal, showsIndicators: false) {
          HStack {
            if list.bookName.capacity != 0 {
              Button(
                action: {
                  pressed = true
                },
                label: {
                  Text("All").foregroundColor(.white)
                    .font(.system(size: 15))
                    .foregroundColor(.white)
                    .padding().frame(height: 35)
                    .background(Color("default_"))
                    .cornerRadius(22)
                })
            }
            ForEach(list.bookName, id: \.id) { item in
              Button(
                action: {
                  self.subId = item.id
                  list.getData(id: self.id, subId: self.subId)
                  pressed = false
                },
                label: {
                  Text(item.category_name).font(.system(size: 15)).foregroundColor(.white).padding()
                    .frame(height: 35)
                    .background(Color("default_"))
                    .cornerRadius(22)
                })
            }
          }.frame(height: 65).background(Color.white)
        }
        if pressed {
          AllCategoriesView()
        } else {
          FilterCategoriesView()
        }
      }
    }.onAppear {
      list.getData(id: self.id)
    }
  }
}

I want to show the the view according to the clicked the Button in the images section.


text:
Q: The source attachment does not contain the source for the file В Eclipse в редакторе кода пытаюсь открыть из своего кода класс драйвера org.postgresql.Driver, но при этом получаю ошибку "The source attachment does not contain the source for the file".
Код рабочий, класс подключен. Project> Properties> Java Build Path> Libraries содержит jar-файл драйвера и указывает на source attachment, путь к которому совпадает с путем к файлу драйвера.
Пробовал распаковывать jar-файл драйвера. Он действительно содержит нужный мне класс. Пробовал при появлении указанного сообщения нажимать кнопку "Change attach source" и указывать путь к jar-файлу (хотя он и так указан в открывающемся диалоге). Ничего не получается. Как же его открыть?


text:
Q: How to check if a byte array is a valid image? I know there is no .Net function that exists for checking, but is there an algorithm or easy and effective way of checking if a byte is a valid image before I use the byte array. I need this because I'm sending different commands to a server who is constantly listening to the client and one of the commands is to get the screenshot of the server's computer.

A: You can try to generate an image from the byte array and check for the ArgumentException if its not.
public static bool IsValidImage(byte[] bytes)
{
    try {
        using(MemoryStream ms = new MemoryStream(bytes))
           Image.FromStream(ms);
    }
    catch (ArgumentException) {
       return false;
    }
    return true;
}

A: For a JPEG you can check that the first two bytes are 0xFF, 0xD8 and the last two are 0xFF, 0xD9. Of course its still possible that the image data will match the EOI tag, but this should be rare.

A: As noted, trying to load it into an image is the only fail-safe way. You can check the magick number aka file header based on the [expected] image type. For instance, the first 8 octets of a *.PNG file are, in hex:
0x89 0x50 0x4E 0x47 0x0D 0x0A 0x1A 0x0A

http://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
Most other types of image files have similar magick numbers.
But checking that won't actually tell you if the file is a valid image file. All you'll know after that is that the magick number seems to indicate that its a file of type X. It could still be truncated or otherwise corrupted, or even be something else entirely that just happens to have the right sequence of octets in the right place.

A: According to me, if you want only image input(Proper image), then you should go with accept attribute of input field like this:
input type="file" name="uploadedFile" id="imageContent" class="required" accept="image/*"/>
This will give you only images in input. So, you can freely code for backend. Without worrying about the image is valid or not.
And even you can specify specific image type if you want like:
input type="file" name="uploadedFile" id="imageContent" class="required" accept="image/jpeg, image/gif, image/png">


text:
Q: Deploying android apps for my business I would like to deploy android apps to my employees. We have roughly 900 employees.
I was looking here, and it indicates that I have to setup a private channel by enabling Google apps for my domain. I've also read that it costs $50/employees to have my entire company on google apps.
Are there any other ways to deploy android apps strictly to my employee base? Am I really going to have to pay $50 per head?
Any advice is welcome.

A: you can always just install the apk file.
but in that case all your users/employers would have to enable other sources in the settings and get the file on the device somehow and start it(which might require an extra app).
How about just making it a public app and restrict the access to the app somehow (e.g. with a company login)

A: No you don't need to pay that.

*

*Get a developer licenses from developer.android.com ($25)

*Then create a google group for your Employees and invite them all using their gmail (or other google, see screen shot below) accounts they have installed on their devices.

Step 1 complete, they are all inside the google group you have specified.
in the developer console:
Upload your apk as an alpha or beta apk (see screen shot below), set up the app as normal with all required fields, but when specifying the testing group you can reference this google group you have just created, which will give you a url that can only be accessed by those google accounts in the group.

Send this link out to all the employees that you previously invited to that google group and get them to accept the link for alpha/beta testing.
Once, accepted the employees will be able to download the apk from the Android device with that google account. (The app can then be found in the PlayStore app under Apps & Games -> My apps & Games - > All)
Now anytime you upload a new Alpha/beta apk all users of this group will see the app update or if auto update apps is enable for them, it will happen automatically.
for more details on beta setup: Alpha/beta help
Good Luck and happy coding!


text:
Q: HTML client receiving continous stream of server output data What would be best mechanism, for achieving ability, for users, that are logged in, receive messages, generated by server. As there is no way for a server, to send information to user, when it has new message to deliver, a user browser should poll with some specific interval, to receive in response new messages, additionally, there should be a way for server, to not send messages, that are already delivered to user. You could draw a connections with something like public chat mechanism, but the thing I need is message delay as close to realtime and ability to handle about 100 users simultaniously, making least traffic possible. Additional note: data is needed only when user is online, no need to store that data in server, for other users to read "history".
In my mind, there are one way of achieving this - global "message box" where server puts all messages, user browser is constantly polling the server, to check, if last received message ID is equal to last message ID in message box.
The question is, if this is right way to do that, or there are another ways for such tasks, as need for realtime data can be found everywhere: sensor data, multiplayer games, chat, stock market and more...

A: XEP-0124: Bidirectional-streams Over Synchronous HTTP (BOSH)
https://github.com/ssoper/jquery-bosh
Build a web-based notification tool with XMPP
Write real-time web applications with XMPP, PHP, and JavaScript
Hope this helps.

A: Isn't pushing a better strategy? Keep a tcp connection open between server and browser and stream changes to the browser when new information is available.
Take a look at html 5 websockets. (which does exactly this)
heres a demo

A: Have you looked at Comet?

Comet is a web application model in
  which a long-held HTTP request allows
  a web server to push data to a
  browser, without the browser
  explicitly requesting it.

If you search stackoverflow there is plenty of info about its use.


text:
Q: Changing onClick to be random I'm looking to make the handler OnClick to just be random instance instead of requiring user interaction.
// add the canvas in
  document.body.appendChild(mainCanvas);
  document.addEventListener('mouseup', createFirework, true);
  document.addEventListener('touchend', createFirework, true);

// and now we set off
    update();
  }

  /**
   * Pass through function to create a
   * new firework on touch / click
   */
  function createFirework() {
        createParticle();
  }

Thanks! :)

A: Having a function call itself isn't too difficult:
// This function executes itself the first time immediately
(function randFunc () {
    // We output some information to the console
    console.log("Called myself..." + new Date());
    // And then instruct this function to be called between 0 and 10 seconds
    setTimeout(randFunc, Math.random() * 10 * 1000);
}());

Demo: http://jsfiddle.net/8tZEu/2/

A: Just extend a good solution from Jonathan: you do not need to create eventListeners the recursive randFunc() is  invoked at random times until you quit the browser.
I Guess you need to implement a way to stop the function. Here is one solution:
     var stopFW = false;
        function randFunc () {
             // stop execution
            if (stopFW) return;
            console.log("Called myself..." + new Date());
            // And then instruct this function to be called between 0 and 10 seconds
            setTimeout(randFunc, Math.ceil(Math.random() * 10) * 1000);
        }

        function stopFireWork() {
            stopFW = !(stopFW);
            console.log(stopFW);
        }

<body onload="randFunc()">
    <button onclick="stopFireWork()">Stop Firework</button>
</body>


text:
Q: Do we need to determine the lesser of two numbers before subtracting? I'm writing a computer program which represents integers as linked lists because the integers may be very large such that they won't fit the usual int type.
In my linked list representation the list start with the least significant digit and ends with the most significant one. For example, $123$ is represented as 3->2->1 ($3$ is the first node in the list).
So I'm writing a subtract function which subtract digits one by one, like in elementary school. It looks like that in order to use the basic school subtraction arithmetic I need to first determine the bigger number because:

*

*When calculating $123-99$ the steps are: $13-9 = 4, 11-9=2$ so the result is $24$.

*But to calculate $23-99$ the logic is different and I can't do $13-9, 1-9$ which would be $-84$ but really is $76$.
So I'm wondering if I really have to know in advance which number is the bigger one. Of course this means that I'd have to add another pass over both linked lists which would decrease the efficiency of the algorithm.

A: Your $-84$ is really $(-8)(+4)$ in that the four in the ones place is positive.  When we write a number with a minus sign in front we mean that all the digits are negative.  Your $(-8)(+4)$ would normally be written $-76$, which is the correct answer.  You can just do your subtraction normally digit by digit with the digits representing positive quantities.  Then if the most significant digit is negative you need to turn everything negative by borrowing from the most significant digit.  If you subtract $13792-26317$ you get $(-2)(+7475)$ which becomes $-12525$

A: I have myself once implemented the $4$ operations for large reals represented as strings, I found it simpler to deal with signs separately.
Also for multiplication it is simpler to multiply by the lower number, so you will need the comparison function at some point.
Have a look for instance at the subtraction wrapper:
https://bpaste.net/show/12a67e8ec170
I first assign a number from $0$ to $7$ depending on the signs $++,+-,-+,--$ and whether $|x|<|y|$ or the opposite.
Then I call the basic function that deals with positive integers and $y\ge x$ for the operation $y-x$.
Of course it is not mandatory to proceed like this, but it will simplify the implementation of the basic function since it has not to deal with particular cases.

A: You don't have to but what you'd have to do instead would be more complicated.
$23 - 99$ who start with $13 -9 = 4$ and borrow.
$2-1 = 1$ and $1-9 = 2$ and borrow... but now there is nothing to left of $23$ to borrow from.
So you go into a negative number subroutine.  You answer of $[24]$ represents a number less than zero.  The $4$ must be increased by $6$ to get to zero.  $6+4 = 10$ and you carry to get $2+1 = 3$.  Then three must be increased by $7$ to get to $0$.  You have reached $0$ (so you "drop" what you were carrying) and $[24] = -76$.
Basically if $10^{k-1} \le xy < 10^k$ then $[xy] = 10^k - xy$.
....
I'd be easier just to program in a check the larger routine.
====
Or you can put off carrying to the end.
$123 - 99$ would be $3-9 = -6$
$2-9 = -7$
$1-0 = 1$ so you end up with $1(-7)(-6)$
To convert this to a "real" number you must determine if it is bigger or less than $0$.  That's simply a matter of seeing if the leftmost non-zero term is positive or negative.  It is $1$ postive.  This is a positive number.
to convert you borrow 10 from the left:  $1(-7)(-6)\mapsto 1(-8)(10-6)=1(-8)4\mapsto 0(10-8)4=024 = 24$
But $456 - 492$ would be $6-2 =4$
$5 - 9 = -4$
$4-4 = 0$
So we end up with $0(-4)4$
We check leftmost non-zero term.  It is $-4$ it is negative.  So this will be a negative number.  We switch the signs of every term $0(-4)(4) = -[04(-4)]$ and we cconvert by borrowing:
$-[04(-4)]\mapsto -[03(10-4)] = -[036] = -36$.
That actually might be the easiest.


text:
Q: Force getUserMedia re-prompt when using HTTPS on Firefox I am making a simple app with two webcams that needs to work only on latest Firefox. Locally it works fine:

*

*the user is prompted for the access to the camera

*the user selects one camera

*the user is prompted again

*the user selects the second camera

*both streams work fine

However, when I upload it to the server which serves the page through HTTPS, the access from the first camera is remembered and I just get two of the same streams.
Is there a way to force re-prompting on HTTPS so that the user can select the other camera, as well?
This is my code:
    function handleSuccess1(stream) {
      video1.srcObject = stream;

      navigator.mediaDevices.getUserMedia(constraints).
        then(handleSuccess2).catch(handleError);
    }

    function handleSuccess2(stream) {
      // this gets called automatically with the first stream
      // without re-prompting the user
      video2.srcObject = stream;
    }

    const constraints = {
      video: true
    };

    function handleError(error) {
      console.error(error);
    }

    navigator.mediaDevices.getUserMedia(constraints).
        then(handleSuccess1).catch(handleError);

A: Use navigator.mediaDevices.enumerateDevices() to list the available cameras and/or microphones.
You can read about it in more detail here: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices


text:
Q: Does subprocess inherit python's linux capabilities? I'm using a program to issue a tc command via the subprocess module, but tc is outputting RTNETLINK answers: Operation not permitted
To solve this, I have given python the CAP_NET_ADMIN capability with the epi flags, but I still am not able to issue the tc command.
$ getcap /usr/bin/python3.5
$ /usr/bin/python3.5 test-capabilities.py
CompletedProcess(args=['tc', 'qdisc', 'add', 'dev', 'eth0', 'root', 'pfifo'], returncode=2, stdout=b'', stderr=b'RTNETLINK answers: Operation not permitted\n')
$ sudo setcap cap_net_admin+eip /usr/bin/python3.5
$ /usr/bin/python3.5 test-capabilities.py
CompletedProcess(args=['tc', 'qdisc', 'add', 'dev', 'eth0', 'root', 'pfifo'], returncode=2, stdout=b'', stderr=b'RTNETLINK answers: Operation not permitted\n')
$ sudo /usr/bin/python3.5 test-capabilities.py
CompletedProcess(args=['tc', 'qdisc', 'add', 'dev', 'eth0', 'root', 'pfifo'], returncode=2, stdout=b'', stderr=b'RTNETLINK answers: File exists\n')

if CAP_NET_ADMIN allows a process to modify network interfaces, and the +i flag given in setcap indicates that subprocesses should inherit the capabilties given to the executable, why am I still getting the operation not permitted error. I'd expect to get the File exists error, like I do above when running python via sudo.


text:
Q: How is The Culture's universe populated by humans if current human culture on earth exists contemporaneously with it? Does Iain M. Banks explain anywhere how in the world of the Culture the galaxy came to be populated by humans and humanoid races given that it can't be that the human race became a space-faring civilization and colonized the galaxy long before the time of the Culture novels.
This can't be the case because we know how the time portrayed in the novels maps to earth years. The Culture stories take place from 1331 CE to 2375 CE according to Wikipedia. In The State of the Art, Diziet Sma actually goes to earth in 1977.

A: He doesn't explain it because you're wrong. The galaxy of the Culture is never stated to be populated by humans; the organic citizens of the Culture are described as humanoid, but that absolutely does not imply they are human.
The use of the phrase "human" within the Culture and any writings around it, including Banks' own commentaries, is almost entirely used as a literary device of familiarity to allow the reader to more easily understand and empathise with the organic citizens of the Culture depicted in these writings. It would be difficult for a reader of a Culture novel (a human) to become invested in the actions of a non-human sentient being that experiences life entirely differently to us, for example.

A: There seems to be a heavy amount of convergent evolution towards a humanoid form in the Culture universe, but the people in the stories are indeed biologically different from Earth humans. This is spelled out for example in the novella "The State of the Art" from the story collection by the same name, in which several members of the Culture visit Earth in 1977, and after the ship's Mind absorbs a great deal of information about human society from orbit, some humanoid members of the ship undergo surgical modification so they can travel to the surface and not be seen as alien. From p. 105:

A fraction of this avalanche of data (it felt like a lot but it was actually pifflingly small, the ship assured us) was stuffed into the heads of those of us sufficiently close in physique to pass for human on Earth, after a little alteration (I got a couple of extra toes, a joint removed from each finger and a rather generalized ear, nose and cheekbone job. The ship insisted on teaching me to walk differently as well)

p. 115 mentioned another humanoid crew member named Li whose physique was too different to travel to the surface:

Li was one of those who just wouldn't have passed for Earth-human without a vast amount of physical alteration (hairy, and the wrong shape; imagine Quasimodo crossed with an ape)

Another character named Linter wants to stay on Earth, and to that end he asks the ship to "give me a set of guts more like the locals" (p. 154). Before that happened, another character had worried not just that he might be killed in some accident with primitive technologies like trucks and planes, but also "What if you're only injured and they take you to hospital? You'll never get out again; they'll take one look at your guts or your blood and they'll know you're an alien. You'll have the military all over you. They'll dissect you." (p. 131) So presumably his internal organs also differed from a human's in obvious ways.
In addition, the novel Matter includes this comment in chapter 10 about a character from a less developed society who joins the Culture:

She learned about pan-humanity, about the great diasporic welter of human-like, human-ish and humanoid species scattered throughout so much of the galaxy ... There were bogglingly large numbers just of these pan-humans (of which, of course, she was one), but they still formed less than a single per cent of all the aggregated life-mass of the greater galaxy.

And in chapter 5 of the novel Surface Detail, a character from a humanoid species called the Sichultians meets a strange man at a party:

The man looking at her appeared terribly old. He was either a much-altered Sichultian or a pan-human alien; the human type had proved to be one of the galaxy's more repetitively common life-forms.

This answer also mentions a line from Excession about an alien planet that is said to be "one of the twenty or so planets that could fairly claim to have been one of the home worlds of the Culture".

A: The term "human" here doesn't mean terran homo sap.  In the Culture the term is used to cover all manner of roughly humanoid species.  The Culture is largely run by vast AI Minds, and to them we're all nearly indistinguishable meat pops.
Banks discusses it here.

A: It's quite clear that "human" as used in the Culture novels does not refer to homo sapiens, but rather it is a shortened form of "pan-human" which the Culture uses to refer to intelligent beings with a roughly human body plan.  (Bilaterally symmetric, two arms, two legs, two eyes, head separated from torso, etc.)
There is a huge variety of what falls under the heading of "human" within the Culture:

Lenipobra was the CAT's best excuse for a medic and was rarely seen without a small screenbook which contained one of the more up-to-date pan-human medical textbooks. He proudly showed this to Horza, including a few of the moving pages, one of which showed in vivid colour the basic techniques for treating deep laser burns in the most common forms of digestive tracts.
Consider Phlebas, "4. Temple of Light"

In fact the description of the crew of the Clear Air Turbulence goes to some lengths to describe the variations in what is considered "human."

*

*Yalson is slim, with dark skin and fair hair, and is lightly furred over her entire body;

*the Bratsilakins are heavy-set and thickly furred;

*Dorolow has strange ears and a very high voice (which she says is deep);

*Aviger has great joint mobility;

*Gow and kee-Alsorofus have grey skins and solid black eyes;

*Lenipobra has extremely long arms and frequently goes about on all fours.

A snippet of the conversation between the drone Jase and Fal 'Ngeestra points to additional structural variations:

"Assuming that we are going to win the war..." Jase said thoughtfully, "... it could lengthen the proceedings by a handful of months."
"And how many's that supposed to be?" Fal said.
"Somewhere between three and seven, I suppose. It depends whose hand you're using."
Consider Phlebas, "state of play: one"

Even Horza, the Changer, is considered "human" when we see from Balveda's viewpoint:

Xoxarle seemed to have hoped some pan-human compassion would make Horza stop and save her, and so give the Idiran a few precious extra moments to make his escape; but the Idiran had made the same mistake about Horza that his whole species had made about the Culture. They were not that soft after all; humans could be just as hard and determined and merciless as any Idiran, given the right encouragement...
Consider Phlebas, "13. The Command System: Terminus"

Note that there is no single "human species:"

[...]the Culture, that seemingly disunited, anarchic, hedonistic, decadent melange of more or less human species, forever hiving off or absorbing different groups of people[...]
Consider Phlebas, "2. The Hand of God 137"

Jase felt pleasure at the girl's words (if not the snort), but at the same time detected in them a tinge of that mixture of contempt and patronising smugness the Culture found it so difficult not to exhibit when surveying the mistakes of less advanced societies, even though the source civilisations of its own mongrel past had been no less fallible.
Consider Phlebas, "state of play: one"

Pan-humanity doesn't even meet the biological definition of "species" since most random pairings aren't genetically compatible (without technological assistance):

[...]theirs - they both knew - an almost inevitably barren cross-matching of species and cultures thousands of light-years apart[...]
Note: speaking of Horza and Yalson


text:
Q: How can i hide a token in the firebase function? i have created subscription form on my gatsby website.
I wanted sent request to activeCampaign with contact data but i couldn't due to cors policy. So I have created firebase function to which i sent data from form and in headers api  active campaign token. Everything works but when i  go to on my firebase function adress i see activeCampaign token in website.
So if someone gets the address of my firebase function, they will also get an api token for the active campaign. How can I hide this token?


text:
Q: PostgreSQL Services Can someone give a detailed explanation of how the postgresql service(s) works on Ubuntu [16.04]? The behavior that leads me to ask is the following. I use the command sudo systemctl start postgresql to start my postgresql service. When I run systemctl list-units | grep post I see
UNIT                           LOAD   ACTIVE SUB       DESCRIPTION
postgresql.service             loaded active exited    PostgreSQL RDBMS
postgresql@9.6-main.service    loaded active running   PostgreSQL Cluster 9.6-main
system-postgresql.slice        loaded active active    system-postgresql.slice

and when I run sudo systemctl stop postgresql both postgresql.service and postgresql@9.6-main.service disappear. What is each of these three services doing?

A: I assume postgresql@9.6-main.service is registered service for PostgreSQL Cluster 9.6-main cluster. This is the one that actually controls postgres on your system.
I assume postgresql.service is the effect desribed here
I assume system-postgresql.slice is a postgres slice unit
none of above are critical for running postgres. You can start/stop the cluser with just pg_ctl, without registering it with your services. But if you wonder which service runs it in your case - then it is postgresql@9.6-main.service


text:
Q: using TEMLATEPATH (of wordpress) in JS I use wordpress and I wanted to ask, is there a way to use the TEMPLATEPATH in my JS.
Like this:
jQuery ("#ajax").load ("<?php echo TEMPLATEPATH;?>" + "/aaa.txt");

The problem is the result of TEMPLATEPATH is C:\XAMPP\HTDOCS ... And therefore i have browser error: Cross origin requests are only supported for HTTP.

A: You can use PHP to print a JavaScript variable with the templatepath.
Or the other option is to print this JavaScript code using PHP itself.

A: There isn't a great deal of information provided. Are you using Wordpress on localhost? With a file:// protocol?
Anyway, try replacing TEMPLATEPATH with get_template_directory_uri().


text:
Q: Trying to build a model in sparqlML in java but getting Exception in thread "main" java.lang.NoClassDefFoundError I am trying to build a ML model using sparqlML in Java but while building the query, I am getting an exception:
Exception in thread "main":
java.lang.NoClassDefFoundError:com/hp/hpl/jena/sparql/lang/sparql/TokenMgrError

The code that throws the exception:
QueryML query = QueryFactoryML.create(queryString);
QueryExecutionML qe = QueryExecutionFactoryML.create(query, dataset);
Model trainModel = qe.execCreate();
trainModel.write(System.out, "RDF/XML-ABBREV");