text:
Q: Farthest equal elements in an array Suppose you have an unsorted array, how will you find 2 equal elements such that they are the farthest in the array. For eg 8 7 3 4 7 5 3 9 3 7 9 0 the ans will be 7(9) - 7(1) = 8.
I have thought of the following
initialise max = 0
using hashing, store the elements along with its index
whenever there is a collision, compare the current index with the hashed one
if it is greater, set max = current index - hashed one and copy element along with index to some other location.

runs in time - O(n) and space - O(n). Is this correct? Is there a better solution.

A: O(n) running time and O(n) space seems to be optimal AFAIK.
Here's python implementation:
#!/usr/bin/python
hashindex = {}

l = [8,7,3,4,7,5,3,9,3,7,9,0]

max_diff = 0
value = 0

for i in range(len(l)):
    indices = hashindex.get(l[i], None)
    if indices:
        hashindex[l[i]] = (indices[0], i)
    else:
        hashindex[l[i]] = (i, i)
    diff = hashindex[l[i]][1] - hashindex[l[i]][0]
    if diff > max_diff:
        max_diff = diff
        value = l[i]

print max_diff, value

A: I very much doubt this is the "correct" answer but if I were given this problem at work, I would do a quick sort along the lines of sort by value then by index. Then I would walk through my ordered array and for each value, grab the first and last index. That would become a candidate max distance. Each time I encountered a new value, I would compare it against my current max distance and then store only the max. In this way, run time would be
sort + walk  = total
N Log N + N = N Log N
Ex.:
Values in unordered array:
1,2,3,1,5,3,3,3
1,1,2,3,3,3,3,5 = Value
0,3,1,2,5,6,7,4 = Index
1's = max of 3-0 = 3
2's = x
3's = max of 7-2 = 5
Max of 5
Keep in mind this is probably NOT the textbook answer, but it still runs in N Log N so I'd use it at work with no qualms for anything under a million elements.
Have you thought of any other potential answers to the problem? How about ways to improve this one?

A: Here is my idea of the best solution:
Since the two elements is going to be the farthest apart, I would make a loop that looks at the start of the array, and at the end of the array at the same time, and look inwards, the first corresponding elements that they find, will be the farthest apart.
For example:
8 7 3 4 7 5 3 9 3 7 9 0

First look at 8, 0, and store them in set A, and in set B respectively.
Look at 7, 9, and store them in the same sets fashion.
Look at 3, 7, and same as above. Now this 7 is already in the opposite set, A.
Therefore they must be the farthest apart. Just calculate the distance between the the 7 elements.

Now that I think about it, you just need to make some kind of check to make sure that the farthest elements are now within a set itself.
So, if either of sets have 1/3 of all the elements, you have to also start checking if the largest distance is not within the set itself.

A: My solution in Java:
    int[] testArr = {1,2,3,5,1,7,5,4,3,1,2,3,2,3};
    int maxLen = 0;
    int minidx = 0;
    int maxidx = 0;
    int numVal = testArr[0];
    int counter = 0; //Just to check how many times its entering inside the below if condition
for (int ii=0;ii<testArr.length-maxidx;ii++) {

    for (int jj=testArr.length-1;jj>=ii+maxidx;jj--){

        if(testArr[ii]==testArr[jj] /*&& maxLen<(jj-ii)*/){

            System.out.println(counter++);

            minidx = ii;
            maxidx = jj;
            maxLen = jj-ii;
            numVal = testArr[ii];

            break;

        }
    }
}

System.out.println(maxLen +" "+minidx+" "+maxidx+" "+numVal);

A:
runs in time - O(n) and space - O(n). Is this correct?

Yes.

Is there a better solution.

I highly doubt it.
JavaScript implementation:
function furthest(a) {
  const first= {};

  return a.reduce((longest, elt, idx) => {
    if (!(elt in first)) first[elt] = idx;
    return Math.max(longest, idx - first[elt]);
  }, Infinity);

}

A: Solution in obj-c. Should be O(N). Just one pass over the array.
//NSMutableArray *numbers = [[NSMutableArray alloc] initWithArray:@[@3,@2,@1,@7,@1,@2,@3,@6,@5,@4,@4,@5,@6,@7]];
//int solution = [self maxDistanceBetweenPairs:numbers];
//NSLog(@"%d", solution);

- (int)maxDistanceBetweenPairs:(NSMutableArray *)A {
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    __block int max = 0;

    int i = 0;
    for (NSNumber *num in A) {
        if ([dictionary objectForKey:num]) {
            int first = [[dictionary objectForKey:num] intValue];
            if (i - first > max) {
                max = i - first;
            }
        } else {
            [dictionary setObject:[NSNumber numberWithInt:i] forKey:num];
        }
        i++;
    }

    return max;
}


text:
Q: Creating Couchbase views in code: First query returns 0 rows, index builds in background I am creating a view in code using the Couchbase Java API 2.1.2 like this:
DefaultView view = DefaultView.create(viewName, jsMapFunctionAsString);
List<View> views = new ArrayList<>();
views.add(view);
DesignDocument doc = DesignDocument.create(name, views);
bucket.bucketManager().insertDesignDocument(doc);

Calling ViewResult result = bucket.query(ViewQuery.from(name, viewName)) directly after inserting the document, viewResult.success() always returns true, but both iterators rows() and iterator return 0 rows (there are definitely results present. When I execute the view in the web interface, it returns correct values).
The workaround I found after several hours is to call query twice with enough waiting time in between like
ViewResult result = bucket.query(ViewQuery.from(name, viewName));
Thread.sleep(10000);
result = bucket.query(ViewQuery.from(name, viewName));

The second call will then return the correct result.
It seems as if Couchbase has to build the index for the query first but returns directly, even before the index has been built.
Waiting 10 seconds is of course not optimal, maybe creating the index will take more time in the future.
So my question is, how can I make sure, that I only wait until the index has been built?
Is this a bug in the API?

A: You can use the stale method and set it to false in the ViewQuery, this will force to wait for the indexation to finish before returning results.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I have a problem about YouTube API with ESP8266 I try to make youtube subscribe counter but it a problem with youtube api library here the error message
Arduino: 1.8.12 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"

The sketch name had to be modified.
Sketch names must start with a letter or number, followed by letters,
numbers, dashes, dots and underscores. Maximum length is 63 characters.
C:\Users\Um Sythat\Documents\Arduino\libraries\arduino-youtube-api-master\src\YoutubeApi.cpp:95:11: error: DynamicJsonBuffer is a class from ArduinoJson 5. Please see arduinojson.org/upgrade to learn how to upgrade your program to ArduinoJson version 6

  DynamicJsonBuffer jsonBuffer;

           ^

C:\Users\Um Sythat\Documents\Arduino\libraries\arduino-youtube-api-master\src\YoutubeApi.cpp: In member function 'bool YoutubeApi::getChannelStatistics(String)':

C:\Users\Um Sythat\Documents\Arduino\libraries\arduino-youtube-api-master\src\YoutubeApi.cpp:95:20: error: 'jsonBuffer' was not declared in this scope

  DynamicJsonBuffer jsonBuffer;

                    ^

C:\Users\Um Sythat\Documents\Arduino\libraries\arduino-youtube-api-master\src\YoutubeApi.cpp:97:10: error: 'ArduinoJson::JsonObject' has no member named 'success'

  if(root.success()) {

          ^

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).
Invalid library found in C:\Program Files (x86)\Arduino\libraries\libraries: no headers files (.h) found in C:\Program Files (x86)\Arduino\libraries\libraries
Invalid library found in C:\Program Files (x86)\Arduino\libraries\youtube_control_arduino: no headers files (.h) found in C:\Program Files (x86)\Arduino\libraries\youtube_control_arduino
Invalid library found in C:\Program Files (x86)\Arduino\libraries\libraries: no headers files (.h) found in C:\Program Files (x86)\Arduino\libraries\libraries
Invalid library found in C:\Program Files (x86)\Arduino\libraries\youtube_control_arduino: no headers files (.h) found in C:\Program Files (x86)\Arduino\libraries\youtube_control_arduino

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I already download youtube api library and arduino json library and import it to arduino ide I always get error from it i dont know why it gone like this someone who know please help me. I like to hear from you.
And here my code :
/*******************************************************************
 *  Read YouTube Channel statistics from the YouTube API           *
 *                                                                 *
 *  By Brian Lough                                                 *
 *  https://www.youtube.com/channel/UCezJOfu7OtqGzd5xrP3q6WA       *
 *******************************************************************/

#include <YoutubeApi.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

#include <ArduinoJson.h> // This Sketch doesn't technically need this, but the library does so it must be installed.

//------- Replace the following! ------
char ssid[] = "xxx";       // your network SSID (name)
char password[] = "yyyy";  // your network key
#define API_KEY "zzzz"  // your google apps API Token
#define CHANNEL_ID "UCezJOfu7OtqGzd5xrP3q6WA" // makes up the url of channel

WiFiClientSecure client;
YoutubeApi api(API_KEY, client);

unsigned long api_mtbs = 60000; //mean time between api requests
unsigned long api_lasttime;   //last time api request has been done

long subs = 0;

void setup() {

  Serial.begin(115200);

  // Set WiFi to station mode and disconnect from an AP if it was Previously
  // connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  // Attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  IPAddress ip = WiFi.localIP();
  Serial.println(ip);

}

void loop() {

  if (millis() - api_lasttime > api_mtbs)  {
    if(api.getChannelStatistics(CHANNEL_ID))
    {
      Serial.println("---------Stats---------");
      Serial.print("Subscriber Count: ");
      Serial.println(api.channelStats.subscriberCount);
      Serial.print("View Count: ");
      Serial.println(api.channelStats.viewCount);
      Serial.print("Comment Count: ");
      Serial.println(api.channelStats.commentCount);
      Serial.print("Video Count: ");
      Serial.println(api.channelStats.videoCount);
      // Probably not needed :)
      //Serial.print("hiddenSubscriberCount: ");
      //Serial.println(api.channelStats.hiddenSubscriberCount);
      Serial.println("------------------------");

    }
    api_lasttime = millis();
  }
}

A: I would ditch the libraray - it uses
#include <ArduinoJson.h>

and the error tells us whats wrong
 error: DynamicJsonBuffer is a class from ArduinoJson 5 <=== you have probably version 6.x.x installed

which is a memory hog. Often one single function is used by libraries and the rest is useless. To solve your problem, you have to
downgrade ArduinoJson.h to version 5.13.5

The other reason I do not like it, breaking changes in nearly all major releases (real big breaking). So another option you have  (if skilled enough) replace the ArduinoJson functions with

*

*a lighter JSON library

*or replace it with self written JSON functions - often a simple buffer and some char handling does the trick

Read the issues and PRs on github to inform yourself about missing updates and other problems. Development stopped March 2018 since then no adaption to the (breaking) changes in the youtube API


text:
Q: overload operator [] to give a specific index from array of objects I have class XOBoard that present an array that is size n*n,each cell of the array is an Object called Cell.
Each Cell object is defined by
class Cell {
    private:
        char ch;
    public:
        Cell(char ch = '.');
        char getCellValue();
        void setCellValue(char nch);
};

Board is defined this way:
class XOBoard {
    private:
        int n;
        Cell **Board;
};
XOBoard::XOBoard(int n) { //constructor
    this->n = (n >= 3) ? n : 3;
    Board = new Cell*[n];
    for (int i = 0; i < n; i++) {
        Board[i] = new Cell[n];
    }
}

I wanted to get to a specific Cell value by using this method: board1[{1,2}], but I want to check if the values that sent to me is withing the range(n), but unfortantly I was unable to get to the Board array, and to n variable.
Here is the code:
XOBoard& operator[](list<int> list){
            int x = list.front(), y = list.back();
            return Board[x][y].getCellValue();
        }

Thanks a head!

A: As mentioned in the comments, using operator[] for multidimensional subscripting is unconventional, but if you want that, you should make sure you get the correct amount of values (2 in this case) and that you return the correct type (a Cell& in this case).
Also be aware of shadowing. If you try to construct a Board with a value less than 3, you'll set this->n to 3 but go on with the construction using the erroneous n (that may even be a negative value).
More comments inline:
#include <iostream>
#include <stdexcept>
#include <tuple>

class Cell {
private:
    char ch;

public:
    Cell(char nch = '.') : // after the colon comes the member initializer list
        ch(nch)            // which is usually good to use
    {
        // if(ch is not valid) throw ...
    }

    char getCellValue() const { return ch; }

    // a convenient conversion operator to automatically
    // convert a Cell to a char where a char is needed
    // (like when streaming a Cell to std::cout)
    operator char() const { return ch; }

    // void setCellValue(char nch); // replaced by operator=
    Cell& operator=(char nch) {
        // if(nch is not valid) throw ...
        ch = nch;
        return *this;
    }
};

class XOBoard {
private:
    size_t n;       // use an unsigned type for sizes/indices
    Cell** Board;

public:
    // constructor
    XOBoard(size_t xy_size) :          // a member initializer list again
        n(xy_size >= 3 ? xy_size : 3), // assign to "n" here
        Board(new Cell*[n])            // the correct n is now used
    {
        // if the below construction fails, a bad_alloc will be thrown.
        // you need to add code to clean up what you've already allocated to take
        // care of that situation.
        for(size_t i = 0; i < n; i++) {
            Board[i] = new Cell[n];
        }
    }

    // Copying or moving need careful handling of the pointers.
    // Read "The rule of three/five/zero". Until then, disable it.
    XOBoard(const XOBoard&) = delete;
    XOBoard& operator=(const XOBoard&) = delete;

    // destructor
    ~XOBoard() {
        for(size_t i = 0; i < n; i++) delete[] Board[i];
        delete[] Board;
    }

    // added for convenience
    size_t size() const { return n; }

    // return a Cell& and use a std::pair since you
    // expect exactly 2 values
    Cell& operator[](std::pair<size_t, size_t> pos) {
        auto& [x, y] = pos;
        if(x>=n || y>=n)
            throw std::out_of_range("{"+std::to_string(x)+","+std::to_string(y)+"}");
        return Board[x][y];
    }

};

int main() {
    try {
        XOBoard a{2};                   // trying an invalid size
        std::cout << a.size() << '\n';
        a[{2, 2}] = 'a';
        std::cout << a[{2, 2}] << '\n';
        Cell x = 'b';
        a[{2, 2}] = x;
        std::cout << a[{2, 2}] << '\n';
        a[{2, 3}] = 'c';                // index out of bounds
    } catch(const std::out_of_range& ex) {
        std::cerr << "out_of_range exception: " << ex.what() << '\n';
    }
}

Output:
3
a
b
out_of_range exception: {2,3}

You should try to avoid raw pointers and actual multidimensional arrays. It's often better to emulate dimensionality by allocating a 1d array and provide an interface to the user that calculates the correct element to work on.


text:
Q: neo4j can't create NEW relationships between existing nodes when I -
CREATE (c:Church{name: "Sts. Peter and Paul", address: "3745 S Paulina St Chicago IL 60609"})

and then I -
MATCH (p:Priest{name: "Fr. Thomas J OGorman" }), (c:Church {name: "Sts. Peter and Paul"})
MERGE (p)-[:POSTED {posting:1982-83}]->(c)

It works fine,
However, when I enter the identical statement, but change variables, like church, I then get (no changes, no records)
Tried creating indexes and variations which didn't help.
For instance:
MATCH (p:Priest {name:'Fr. Thomas J OGorman'}), (c:Church {name:'St  Barnabas'})
MERGE (p)-[:POSTED {posting:1977-82}]->(c)

I then get (no changes, no records)
Suggestions please? Thanks.


text:
Q: Build fail with dlib I am attempting to import dlib into a file to detect faces. I followed the instructions on davisking's github repo.
So I have the following error when I try to run python setup.py install --no USE_SSE4_INSTRUCTIONS:
In file included from /Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/fonts.cpp:16:
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:313:21: error: use of undeclared identifier 'XAllocColor'
                    XAllocColor(d, cmap, &xcol);
                    ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:319:36: error: use of undeclared identifier 'XmbTextExtents'; did you mean 'XTextExtents'?
                            return XmbTextExtents(fs, str, len, ink, logical);
                                   ^~~~~~~~~~~~~~
                                   XTextExtents
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:318:43: note: 'XTextExtents' declared here
                        inline static int XTextExtents (XFontSet fs, char *str, int len, XRectangle *ink, XRectangle *logical){
                                          ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:322:36: error: use of undeclared identifier 'XwcTextExtents'; did you mean 'XTextExtents'?
                            return XwcTextExtents(fs, str, len, ink, logical);
                                   ^~~~~~~~~~~~~~
                                   XTextExtents
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:321:43: note: 'XTextExtents' declared here
                        inline static int XTextExtents (XFontSet fs, wchar_t *str, int len, XRectangle *ink, XRectangle *logical){
                                          ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:325:29: error: use of undeclared identifier 'XmbDrawString'; did you mean 'XDrawString'?
                            XmbDrawString(d, w, fs, gc, x, y, str, num_bytes);
                            ^~~~~~~~~~~~~
                            XDrawString
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:324:44: note: 'XDrawString' declared here
                        inline static void XDrawString(Display *d, Window w, XFontSet fs, GC gc, int x, int y, char *str, int num_bytes){
                                           ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:328:29: error: use of undeclared identifier 'XwcDrawString'; did you mean 'XDrawString'?
                            XwcDrawString(d, w, fs, gc, x, y, str, num_bytes);
                            ^~~~~~~~~~~~~
                            XDrawString
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:327:44: note: 'XDrawString' declared here
                        inline static void XDrawString(Display *d, Window w, XFontSet fs, GC gc, int x, int y, wchar_t *str, int num_bytes){
                                           ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:334:29: error: use of undeclared identifier 'XOpenDisplay'
                        d = XOpenDisplay(NULL);
                            ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:337:33: error: use of undeclared identifier 'XOpenDisplay'
                            d = XOpenDisplay(":0.0");
                                ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:369:29: error: use of undeclared identifier 'XFreeFontSet'
                            XFreeFontSet(d, fs);
                            ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:371:30: error: use of undeclared identifier 'XCreateFontSet'
                        fs = XCreateFontSet(d, fontset, &mlist, &mcount, &def_str);
                             ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:376:34: error: use of undeclared identifier 'XExtentsOfFontSet'
                        extent = XExtentsOfFontSet(fs);
                                 ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:379:25: error: use of undeclared identifier 'XFreeStringList'; did you mean 'XwcFreeStringList'?
                        XFreeStringList(mlist);
                        ^~~~~~~~~~~~~~~
                        XwcFreeStringList
/Users/karishmaasthana/anaconda2/include/X11/Xutil.h:777:13: note: 'XwcFreeStringList' declared here
extern void XwcFreeStringList(
            ^
In file included from /Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/fonts.cpp:16:
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:379:41: error: cannot initialize a parameter of type 'wchar_t **' with an lvalue of type 'char **'
                        XFreeStringList(mlist);
                                        ^~~~~
/Users/karishmaasthana/anaconda2/include/X11/Xutil.h:781:1: note: passing argument to parameter here
);
^
In file included from /Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/fonts.cpp:16:
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:388:29: error: use of undeclared identifier 'XFreeGC'
                            XFreeGC(d, gc);
                            ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:389:29: error: use of undeclared identifier 'XFreePixmap'
                            XFreePixmap(d, pix);
                            ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:393:103: error: use of undeclared identifier 'XDefaultDepth'
                        pix = XCreatePixmap(d, DefaultRootWindow(d), pix_width_prev, pix_height_prev, XDefaultDepth(d, DefaultScreen(d)));
                                                                                ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:394:30: error: use of undeclared identifier 'XCreateGC'
                        gc = XCreateGC(d, pix, 0, NULL);
                             ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:398:21: error: use of undeclared identifier 'XSetForeground'
                    XSetForeground(d, gc, backcolor);
                    ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:399:21: error: use of undeclared identifier 'XSetBackground'
                    XSetBackground(d, gc, backcolor);
                    ^
/Users/karishmaasthana/workspace/dlib/dlib/gui_widgets/nativefont.h:400:21: error: use of undeclared identifier 'XFillRectangle'
                    XFillRectangle(d, pix, gc, 0, 0, width, height);
                    ^
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.
make[2]: *** [dlib_build/CMakeFiles/dlib.dir/gui_widgets/fonts.cpp.o] Error 1
make[1]: *** [dlib_build/CMakeFiles/dlib.dir/all] Error 2
make: *** [all] Error 2
error: cmake build failed!

I tried with both USE_SSE4_INSTRUCTIONS on and off. I also tried with turning on and off DUSE_AVX_INSTRUCTIONS.
Anyone have any suggestions for what I could try?

A: XQuartz missing. Install it from here https://www.xquartz.org/


text:
Q: What is wrong with my VBA code - it's copying and pasting charts from one sheet repeatedly to Word instead of looping through them all? I'm writing some VBA code to export some charts from Excel to a bookmark in a Word document that is already open. It's meant to send the charts from only sheets in Excel that contain ".atf" in the name, ignoring the other sheets. It inserts the charts at the bookmark in reverse order, as the number of sheets with charts will vary and each set of charts should be on their own page. However, what happens is that only the charts from the first sheet that contains ".atf" get copied and pasted repeatedly for the total number of sheets. Can someone help get this running correctly? Any other improvements also gratefully received!
Here's my code:
Private Sub CommandButton3_Click()

With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
    .EnableEvents = False
    .DisplayAlerts = False
    .DisplayStatusBar = False
End With

Dim WS As Worksheet
Dim appWD As Object, wddoc As Object
Dim check As Boolean

Set appWD = GetObject(, "Word.Application")
Set wddoc = appWD.Documents(1)
wddoc.Application.ScreenUpdating = False

For Each WS In Worksheets
    'Export figures unless none present
    If WS.Name Like "*.atf" Then check = True: Exit For
Next

    If check = True Then
        For i = Sheets.Count To 1 Step -1
            If WS.Name Like "*.atf" Then

                Word.Application.Documents(1).Activate
                wddoc.Bookmarks("qfigs1").Range.Select

                With wddoc.ActiveWindow.Selection
                    .Collapse Direction:=wdCollapseStart
                    .InsertBreak Type:=wdPageBreak
                    .Font.Bold = True
                    .TypeText Text:="File "
                    .TypeText WS.Range("A2").Value
                    .TypeText Text:=" Recording Quality Figures"
                    .InsertParagraph
                End With

                WS.ChartObjects("Chart 3").Copy
                With wddoc
                    .ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
                    .ActiveWindow.Selection.InsertParagraph
                    .ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
                    .ActiveWindow.Selection.Range.PasteSpecial _
                        DataType:=wdPasteEnhancedMetafile, Placement:=wdInLine, _
                        Link:=False, DisplayAsIcon:=False
                    .ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
                    .ActiveWindow.Selection.InsertParagraph
                    .Application.CutCopyMode = False
                End With

                WS.ChartObjects("Chart 2").Copy
                With wddoc
                    .ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
                    .ActiveWindow.Selection.InsertParagraph
                    .ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
                    .ActiveWindow.Selection.Range.PasteSpecial _
                        DataType:=wdPasteEnhancedMetafile, Placement:=wdInLine, _
                        Link:=False, DisplayAsIcon:=False
                    .ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
                    .ActiveWindow.Selection.InsertParagraph
                    .Application.CutCopyMode = False
                End With

                WS.ChartObjects("Chart 1").Copy
                With wddoc
                    .ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
                    .ActiveWindow.Selection.InsertParagraph
                    .ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
                    .ActiveWindow.Selection.Range.PasteSpecial _
                        DataType:=wdPasteEnhancedMetafile, Placement:=wdInLine, _
                        Link:=False, DisplayAsIcon:=False
                    .ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
                    .ActiveWindow.Selection.InsertParagraph
                    .Application.CutCopyMode = False
                End With

            ElseIf WS.Name Like "*.atf" = False Then
                Resume Next

            End If
        Next
    Else
        MsgBox "No figures to export"
        Exit Sub
    End If

wddoc.Application.ScreenUpdating = True
Set wddoc = Nothing

With Application
    .ScreenUpdating = True
    .Calculation = xlCalculationAutomatic
    .EnableEvents = True
    .DisplayAlerts = True
    .DisplayStatusBar = True
End With

MsgBox "All figures exported"

End Sub

A: Solution:
Add Set WS = Sheets(i) after this line For i = Sheets.Count To 1 Step -1
Also consider:

*

*Sheets and Worksheets are not quite the same. (see Define sheets and worksheets in VBA).
In your case you probably want to use Worksheets.

*Remove the ElseIf, you don't need it.

*Remove the check above, you don't need it.

*Fix the indentation of the For i loop.

*The block of code for copying charts repeats, so you can do
Dim ChartName As Variant

For Each ChartName In Array("Chart 3", "Chart 2", "Chart 1")
    WS.ChartObjects(ChartName).Copy
    With wddoc.ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
         .ActiveWindow.Selection.InsertParagraph
         .ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
         .ActiveWindow.Selection.Range.PasteSpecial _
             DataType:=wdPasteEnhancedMetafile, Placement:=wdInLine, _
             Link:=False, DisplayAsIcon:=False
         .ActiveWindow.Selection.Collapse Direction:=wdCollapseStart
         .ActiveWindow.Selection.InsertParagraph
         .Application.CutCopyMode = False
    End With
Next


text:
Q: DB Manager connection to PostgreSQL failed I try to load a postgis raster layer. I would like to add the raster by connection with DB Manager an drag and drop into canvas.

Connection with DB Manager failed with error: UnicodeDecodeError:
  'ascii' codec can't decode byte 0xfc in position 34: ordinal not in
  range(128)

Connections to other databases are possible. Also it is possible to add shapes.


text:
Q: Debian package, installation of dependencies I'm building a Debian package which require others packages, such as libboost-all-dev or libqt4-dev by example. I've tried to use Pre-Depends and to put  apt-get install PKGS in preinst, but it doesn't work.
How can I launch automatically the installation of the dependencies ?
EDIT : My control file:
Package: myPackage
Version: 1.0
Section: base
Priority: optional
Depends: libboost-all-dev,libqt4-dev,libvtk6-dev,libcppunit-dev,libhdf5-dev,libann-dev,wx-common,libwxbase2.8-dev
Architecture: all
Maintainer: Corentin D <***@***.***>
Description: ...
Homepage: none

I'm trying to install the package using
dpkg -i package-name.deb

A: Don't use the preinst script for that! Beside from the fact that it does not work because just a single instance of dpkg can run at a time the installation of the dependencies is a job for apt. Use the control file to list your binary dependencies as described in the Debian policy: http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
Further note that if you install a local package using dpkg -i package-name.deb, dpkg will not(!) install the dependencies listed in the control file. You still need to install them manually. If you want dependencies installed properly, you need to:

*

*Setup an Debian package repository (or use a ppa on Ubuntu)

*Place the .deb there

*Add the repository to your sources.list

*apt-get update or aptitude update

*apt-get install package-name or aptitude install package-name


text:
Q: Public Bug portal for TFS My company is transitioning it's scrum workflow into TFS.  Presently we have a public site where people can submit bug reports.  We would love to have those bug reports go directly into TFS.  Is there any add-on, or 3rd party product that supports a public bug portal into TFS?

A: There's some capability built in for that within Team Web Access.  This MSDN article can point you in the right direction:
http://msdn.microsoft.com/en-us/library/cc668124.aspx


text:
Q: Is there a way to generally transform a weighted arithmetic mean to a weighted geometric mean? I was wondering under what general conditions and how it's possible to transform a weighted arithmetic mean to a weighted geometric mean.
Assume there are positive weights $a_1,\dots,a_n$ that sum up to $1$ (i.e. $a_1+...+a_n=1$ and $a_i\geq0$ $\forall i\in\{1,\dots,n\}$) such that:
$$y=\sum_{1\leq i\leq n}a_i\cdot x_i$$
Under what conditions and how can positive weights $g_1,\dots,g_n$ that also sum up to $1$ be calculated such that:
$$y=\prod_{1\leq i\leq n}x_i^{g_i}$$
Addendum: The above formulation of the question has to be specified a little bit further: The famous theorem on the (in)equality of weighted arithmetic and geometric means states: Given positive weights $w_1,\dots,w_n$ that sum up to one it holds that: For all positive $x_1,\dots,x_n$:
$$\sum\limits_{i=1}^nw_i\cdot x_i\geq\prod\limits_{i=1}^nx_i^{w_i}$$
... with equality iff $x_1=\dots=x_n$. Note that the weights are fixed here.
Now, I am interested in a result on varying the weights, especially I am interested whether a statement of the following form holds:
$\forall x_1\in(0,1],\dots,x_n\in(0,1]$
$\forall a_1\in[0,1],\dots,a_n\in[0,1]$  ($a_1+\dots+a_n=1$)
$\exists g_1\in[0,1],\dots,g_n\in[0,1]$  ($g_1+\dots+g_n=1$)
such that the equivalence holds -- for short:
$$\forall x\forall a\exists g\sum\limits_{i=1}^na_i\cdot x_i=\prod\limits_{i=1}^nx_i^{g_i}~~\text{where for the $x_i$s,$a_i$s,$g_i$s hold the restrictions as stated above}$$
And if so, is there a way to calculate solutions for the $g_i$s with Mathlab, Maple, Wolfram etc.? If not, which restrictions on the $a_i$s and/or the $x_i$s are necessary?
I'd be very happy for any hints.
Thanks a lot, Christian

A: Take the logarithm of the second identity. You have
$$\log y=\sum_{i=1}^n g_i\log x_i=\log\sum_{i=1}^n a_ix_i.$$
With the condition
$$\sum_{i=1}^n g_i=1$$
this is a linear system of $2$ equations in $n$ unknowns, which is $n-2$ times indeterminate.


text:
Q: Query params match in Istio Virtual Service In a Istio virtual service, I have this working match block:
 - match:
   - uri:
       prefix: "/whatever"

It's working fine. But now, besides uri, I need to match also 2 query params as well. I tried this:
 - match:
   - uri:
       prefix: "/whatever"
     queryParams:
       app-id:
         exact: "whatever"
       token:
         exact: "thisisthetoken"

It doesn't work. It doesn't redirect to destination. What am I doing wrong?

A: If you look at HTTPMatchRequest part of Istio docs, table row describing queryParams says:

Note: prefix matching is currently not supported.

So there you go. You can't match query parameters with prefix HTTP match.

A: In my virtualservice.yaml, I defined queryParams directly under "- match" section and it worked fine.
If I define queryParams  under uri and save the changes, it is automatically getting moved out of the  uri section and it doesn't work after that.
Probably it means that the queryParams are global for all uris and not for sepecific uri


text:
Q: Exit queue with condition, Collection to filter destinations I am simulating a distribution system in AnyLogic where products are transported with different vehicles around the world.
At the beginning the products are produced in one of many plants. Each product owns a variable v_destination1 (String) taht shows the next destination.
The agents (products) are in the agent type "plant", more specifically in a queue block.
I want to write a code which calls a vehicle to enter the plant and pickup products.
The difficulty is that the code must contain the following condition:
- the vehicle is called, if there are a minimum of 10 products with the same destination (variable
   v_destination1) in the queue block
These product agent should leave the queue block and enter a pickup block.
I have the following ideas but i dont know how to continue:
1.1 Creating a collection (c_waitingTruck) with all product that are in the queue
1.2 int count (c_waitingTruck, p -> p.v_destination1 ... --> Here I dont know how to write the correct condition
1.3 if (count >= 10) Checking if die minimum of 10 products is reached.
2.1 Creating a collection (c_waitingTruck) with all product that are in the queue
2.2 filter (c_waitingTruck, c -> c.v_destination1 ... --> same as in 1.2
2.3 if (filter.size() >= 10) {
Can someone help me? I would be really glad for any advice.

A: Don't use a queue, use a wait block called wait.
In the on enter of the wait block, check if the amount is satistifed
List <Product> products=findAll(wait,a->a.v_destination1.equals(agent.v_destination1);
if(products.size()>=10){
    //call truck, however you do that
   // then release your products into the queue that comes before the pickup block
    for(Product p : products){
        wait.free(p);
    }
}

I didn't test this code, so it might have an error, but that's the idea at least


text:
Q: Is It possible to call angularjs app by post request? Is it possible to open angular application from another application as widget or as post request? (I did it as get request)

A: No you can't. Your Angular app is running in a javascript context client side.
The only way to do what you described will be to handle the POST request with a backend and display the view that contains your angular app.


text:
Q: How to have different names for my API DTO's (based on the generator) with Nswag? I have a .NET 5.0 ASP.NET Core project and I am using Nswag to generate an API client.
Let's say I have the following API model:
public class GetFooListResponseModel
{
    public string Bar { get; set; }
}

What I would like is 2 things. Let's start with the basic one.

*

*How do I make the generated API Client's model name a different one than the one in my project? For example, I want the generated typescript model to be called Foo instead of GetFooListResponseModel.

*Could I make them have different names based on the client it is generating? For example, for my C# Client I am completely fine with the existing model name, but the typescript one needs to be changed. If this is not possible it's no big deal, but it would be nice.

Thank you very much!

A: You can use SchemaNameGenerator to customise the model name. You can refer shadowsheep's answer . To generate completely new Model name you can use CustomeAttribute with SchemaNameGenerator.
public class ClientModelAttribute : Attribute
{
    public string Name { get; set; }
    public ClientModelAttribute(string name)
    {
        Name = name;
    }
}

  internal class CustomSchemaNameGenerator : ISchemaNameGenerator
{
    public string Generate(Type type)
    {
        var attrs = type.GetCustomAttributes(typeof(ClientModelAttribute),true);

        foreach (var attr in attrs)
        {
            if(attr is ClientModelAttribute)
            {
                ClientModelAttribute clientModel = attr as ClientModelAttribute;
                return clientModel.Name;
            }
        }

        return type.FullName;
    }
}

Model Class with CustomAttribute
[ClientModel("Foo")]
public class WeatherForecast
{
    public DateTime Date { get; set; }

    public int TemperatureC { get; set; }

    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

    public string Summary { get; set; }
}

update ConfigureServices
services.AddSwaggerDocument(cfg => { cfg.SchemaNameGenerator = new CustomSchemaNameGenerator(); });

swagger.json
 "paths": {
"/WeatherForecast": {
  "get": {
    "tags": [
      "WeatherForecast"
    ],
    "operationId": "WeatherForecast_Get",
    "responses": {
      "200": {
        "x-nullable": false,
        "description": "",
        "schema": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/Foo"
          }
        }
      }
    }
  }
}

A: Sometimes, the best solution is the simplest.
Try creating a windows/message asking the user what they would like their module name to be that would trigger once the program starts?

A: You can simply create a injectable service called 'FooService' for communicating with backend services using HTTP Request. Specify the model/class (you can create any name you want) being returned from your API in getFooListResponse(). The naming not necessary must be the same with GetFooListResponseModel, as long the attributes and its data type of the model/class are same.
foo.service.ts
@Injectable()
export class FooService
{
  constructor(
  protected http: HttpClient
  ) {}

  getFooListResponse() {
    const endpointUrl = "myEndpointUrl";
    return this.http.get<Foo>(endpointUrl);
  }
}

foo.model.ts
export class Foo {
    public Bar: string;
}


text:
Q: Test if BigDecimal can change integral part of other BigDecimal I need a way to express that into valid java code: I have 2 BigDecimals, and I want to know if the smaller BigDecimal can (when added to the bigger BigDecimal once) change the integral part of the bigger BigDecimal. Example:
0.6; 0.4 ->true

0.6; 0.39 ->false

Is there any efficient way of doing that, or do I have to test?

A: You can do something like this:
BigDecimal b1 = new BigDecimal("0.90");
BigDecimal b2 = new BigDecimal("0.20");
if(b1.add(b2).intValue() > Math.max(b1.intValue(), b2.intValue())){
    System.out.println("The integral has changed");
}else {
    System.out.println("The integral is the same");
}

How the intValue() method works:

Converts this BigDecimal to an int. This conversion is analogous to the narrowing primitive conversion from double to short  ...
  Specification: any fractional part of this BigDecimal will be discarded ...

A: I've edited my answer after realizing Titus' answer was simpler. Credit goes to him/her.
 public static boolean integral(BigDecimal a, BigDecimal b) {

    BigDecimal greater;

    if (a.compareTo(b) == 1) {
        greater = a;
    } else {
        greater = b;
    }

    BigDecimal sum = a.add(b);

    return (sum.intValue() != greater.intValue());
}

A: private static boolean isNonFractionalChanged(BigDecimal a, BigDecimal b) {
    BigInteger aInt = a.toBigInteger();
    BigInteger aNewInt = a.add(b).toBigInteger();

    return aInt.compareTo(aNewInt) != 0;
}

The above works even for very big numbers.
BigDecimal a = new BigDecimal("0.90");
BigDecimal b = new BigDecimal("0.20");
System.out.println(a + " + " + b + " = " + a.add(b) + " : " + isNonFractionalChanged(a, b));

BigDecimal bigA = new BigDecimal(Integer.MAX_VALUE + ".90");
System.out.println(bigA + " + " + b + " = " + bigA.add(b) + " : " + isNonFractionalChanged(bigA, b));


text:
Q: Converting XSD files to Ruby classes I am planning to convert a large amount of XSD documents to Ruby classes and it is very tiresome to do it by hand. I would like to find an automated way of doing this instead.
I have found a gem called rxsd (https://github.com/movitto/RXSD) but it doesn't  work (it only generates empty classes). However, it does have some infrastructure that might be worth building on.
We are currently using libxml for parsing the schema files which is documented here https://xml4r.github.io/libxml-ruby/rdoc/
Any suggestions? Has anyone had to do this before?


text:
Q: vue-select library set default value not working properly This is the library that I'm using.
vue-select
And I have this kind of data
[
    { text: "AAA", value: 1 },
    { text: "BBB", value: 2 },
]

<v-select
    id="modal-job_type"
    :value="1" // v-model also doesnt work for me
    item-value="value"
    name="job_type"
    :options="jobTypeOptions"
    label="text"
/>

I expect to see "AAA" selected.
But instead I see "1" text.
What is wrong?

A: I guess you need to set a value of options to v-model, instead of the index. (Though, I couldn't find a page where it is clearly stated in the official document.)
It would look like;
const options = [
    { text: "AAA", value: 1 },
    { text: "BBB", value: 2 },
]
const selected = ref(options[1]) // Setting initial value

<v-select
    v-model="selected"
    label="text"
/>

Also, Vue Select does not have item-value property. It seems you are confused with Vuetify's v-select.
https://vuetifyjs.com/en/api/v-select/#props-item-value


text:
Q: Is there a way to load specific features from jQuery in real time? As I can see, loading jQuery every time I load a site is pretty slow. i.e.
<!-- jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- Site Scripts -->
<script type="text/javascript" src="js/myJS.js"></script>

Compared to downloading jQuery to my local file system and import it locally. i.e.
<!-- jQuery -->
<script type="text/javascript" src="js/jquery-someversion.min.js"></script>
<!-- Site Scripts -->
<script type="text/javascript" src="js/myJS.js"></script>

Obviously depends on my internet's speed at the time of loading the script.
I was wondering if there is a jQuery API of some sort that would allow me to "lazy load" it(jQuery) using HTML script tag. What I mean with lazy loading jQuery is: loading only the specific feature(s) I'm going to use, i.e.
<!-- jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js/events"></script>
<!-- Site Scripts -->
<script type="text/javascript" src="js/myJS.js"></script>

Changed the source: < script .... src="http://code.jquery.com/jquery-latest.min.js/events"/ >
I know that I can look up for the jQuery code of that specific feature and load it myself when needed, but I do NOT want to copy the features into my local file system every time jQuery has an update or whatever. If you are still not getting where I'm going, what I want is to have a way in which I know that the features are UP TO DATE and SUPPORTED (by jQuery) so later bug-fixes/improvements/changes/additions/cross-browser-support to jQuery are "automagically" implemented in my site.

A: You're always going to be slower fetching jquery-latest vs jquery-version--the server enforces it. For example:
http://code.jquery.com/jquery-latest.min.js

http://code.jquery.com/jquery-1.10.2.min.js

Note that there is now a very future dated Expires header sent. That means that once the first page is loaded, the browser is going to cache this version for a very long time making subsequent page calls have [almost] no latency.
By staying with the latest, however, you're forcing the browser to fetch this file for every page load. Of course that's going to add latency.

what I want is to have a way in which I know that the features are UP TO DATE and SUPPORTED (by jQuery) so later bug-fixes/improvements/changes/additions/cross-browser-support to jQuery are "automagically" implemented in my site.

Except when you write something that uses $.browser, .die() or .live then wonder why it's no longer working.
There's something to be said for spending the few minutes and updating your JS files (especially if it means your site worked yesterday and doesn't today and you don't know why).

A: if you will use a cdn path, then it will not redownload the file if it has been cached previously. It increases the chance that there will be a cache-hit.
(As more sites follow this practice, more users already have the file ready.)

A: You can create your own build of jQuery but you will have to host it yourself.
Follow the "How to build your own jQuery" guide for instructions:

Special builds can be created that exclude subsets of jQuery functionality. This allows for smaller custom builds when the builder is certain that those parts of jQuery are not being used. For example, an app that only used JSONP for $.ajax() and did not need to calculate offsets or positions of elements could exclude the offset and ajax/xhr modules.

A: You don't say so! jQuery's size is only 32KB!
http://code.jquery.com/jquery-latest.min.js
You will spent much more time loading multiple files than one. Furthermore, it will be a good idea to merge all you JS and CSS files into one JS and one CSS file.


text:
Q: Python : what is the equivalent python's requests.posts command for curl with --data-urlencode I am trying to post some data to the server using the requests.post using python. But the request I have is in curl command and I need to convert that to the python's requests.post. But the catch here is the curl command is with the --data-urlencode and I did not find any solution for converting this --data-urlencode into pythons code. Please help me to convert the below curl command to pythons command.
The curl command is :
curl https://example.com/api/version1/cert/abccsr \

    -u {API_KEY}:{API_KEY_SECRET} \
    -X POST \
    -d company="xyz" \
    -d emp_name="abcdef" \
    --data-urlencode "abccsr=azlkjdllksdl+jl8lksehsd8vYZ7lo..."

I tried with the below python command with --data-urlencode inside data. but its not working. I dont know exactly how to convert this data-urlencode into python requests.post. Please let me know how to convert this curl command with --data-urlencode into python's requests.
mno = "azlkjdllksdl+jl8lksehsd8vYZ7lokhkjhdohs99kjhgsadjkahgfjhgsjhgdsjhwggfuy48992lkjf+jgskjhgsdjgasd1983kjjgds9hd893;iyajhf9ljasiulfljgwwiugfejgqwoiug"

data = [
        ('company', 'xyz'),

        ('emp_name', 'abcdef'),
        ('employ_id', 'emp_'+str(i)),
        ('--data-urlencode', "abccsr=" + mno )
]

response = requests.post('https://example.com/api/version1/cert/abccsr', data=data, auth = ('API_KEY', 'API_KEY_SECRET'))

A: Just encode the data first, with quote_plus:
import urllib.parse
data = [
        ('company', 'xyz'),
        ('emp_name', 'abcdef'),
        ('employ_id', 'emp_'+str(i)),
        ("abccsr", urllib.parse.quote_plus(mno))
]


text:
Q: How protect .NET Web API with password without database and identity Given that in future I will implement a gateway with integrated security, I need a fast and simple way to protect a .NET 6 web service: its goal is to be an interface to search in a lucene.net index.
I have some particularity:

*

*The web service is in a corporate company and external authority like Azure, AWS or Auth0 is not an option

*I don't have any database or persistence layer

*I don't have to manage users list or profile, if caller service has the correct password or token should be able to use all my API without any registration

Now we have an older application with this logic:

*

*every action has user and password parameters

*user and password are stored in config file

*every call manually check for user and password with config file

I am wondering if there is a better way but just as simple?
I would like to not have to send password in every call and having to write an if in every action
Thanks


text:
Q: stopping page refreshes with bootstrap javascript collapsible panels I have a simple jade template written like -
div(ng-if="items.length!=0")
            .panel-group(ng-repeat="item in items",ng-model="item",id="{{item.ad._id}}")
                .panel.panel-default
                    .panel-heading
                        h4.panel-title
                            a(data-toggle="collapse",data-parent="#{{item.ad._id}}",ng-href="#{{item.ad.adId}}") {{item.ad.title}}
                    .panel-collapse.collapse.in(id="{{item.ad.adId}}")
                        .panel-body.
                            {{item.ad.description}}
                .panel.panel-default(ng-repeat="bid in item.bids")
                    .panel-heading
                        h4.panel-title
                            a(data-toggle="collapse",data-parent="#{{item.ad._id}}",ng-href="#{{bid.bidId}}") Bid by: {{bid.bidderId}} At {{bid.bid}}
                    .panel-collapse.collapse(id="{{bid.bidId}}")
                        .panel-body
                            a.pull-left.btn.btn-primary Accept
                            a.pull-right.btn.btn-primary Reject

The data set items is coming from an $http method that gets invoked from the page controller every time I reload the page.
Here, every time I click on any panel, the page issues new requests and reloads. How do I prevent that from happening?
A screenshot of what's happening is attached below to explain the problem in more detail -


text:
Q: iPhone stay connected to WiFi even if there is not internet We are developing an app to configure a WiFi enabled device. App connects to device over WiFi and allows config + shows some stats on the app. We want to ensure that when app on iPhone request to connect to device over Wifi the iPhone doesn't switch to mobile data network.
Is the a way to prevent iPhone to switch to mobile when connect to WiFi with no internet?
Thanks in anticipation


text:
Q: lxml and xpath in python: get pairs of h3 and email from html document in a list with possible missing e-mail Im quite new to this, so I don't really know if this is possible:
This webpage has titles under h3, easy to get with lxml:
titles=doc.xpath("//div/h3/a/text())

under those, i have the emails:
emails=doc.xpath("//div/p[text()='Email: ']/a/text()")

And I can merge them into a list with '|':
both=doc.xpath("//div/h3/a/text()|//div/p[text()='Email: ']/a/text()")

The problem is, some results don't have an e-mail, so i get a bad list, with some titles followed not by an email, but with another title, without even an empty list item. I can work this around with some processing, but I wonder if its possible to return a 'not-found' when the email is missing so I get workable pairs: title-email, title-not found, and so on
I tried a recipe I found here using:
emails=doc.xpath("concat(//div/p[text()='Email: ']/a/text(),substring('not-found',1 div not(//div/p[text()='Email: ']/a/text())))")

But this works only as a standalone with emails, if I mix it with '|' I get a XPathEvalError: Invalid type error.
for the record, this is what i tried:
emails=doc.xpath("//div/h3/a/text()|concat(//div/p[text()='Email: ']/a/text(),substring('not-found',1 div not(//div/p[text()='Email: ']/a/text())))")

I'm quite new to lxml and xpath, so maybe i'm missing an easy way to do this.

A: If you are not stuck with lxml, you can give a try to BeautifulSoup. I find it easier to use. I looked into that page but couldn't parse it fine because it has an xml header just before the html header, like:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ES" xml:lang="ES" >
...

I had to remove the first line (xml header) to test it. Said that, here you have the example with BeautifulSoup:
from urllib.request import urlopen
from bs4 import BeautifulSoup
from itertools import dropwhile
import re

html = urlopen('http://www.datosempresa.com/Categoria/peluqueria?pagina=4').read()
soup = BeautifulSoup(html, 'html')

for div in soup.find_all('div', attrs={'class':'resultados'}):
    title = div.find_next('h3').string
    email = list(dropwhile(lambda x: not re.match(r'(?i)email:', x), div.strings))
    print('{} - {}'.format(title, email[1] if email else 'Not found'))

It searches all <div> elements with a class attribute with resultados as value, extracts all strings from its childrens and remove all of them found before one that matches email: ignoring case. If the returning list is empty, just print Not found, otherwise the email will be the second element in the list, so extract it.
Run it like:
python3 script.py

That yields:
MANUELA RIVERO - oscarvp30@hotmail.com
SALON DE BELLEZA LIDIA - Not found
TRUKO & HAIR DESIGN - Not found
PACO PERFUMERIAS - pacoperfumerias@gmail.com
ESTHER CENDAGORTAGALARZA ESTILISTA - peluqueriaesthercendagortagalarza@hotmail.es
ADARIS - adaris@hotmail.es
N&K NAILS - info@nknails.com
PELUQUERIA NELA - wrunela@hotmail.es
PELUQUERIA NELA - wrunela@hotmail.es
PELUQUERIA HUMBERTO STAR - humbertostar@yahoo.es
COLLADOS PELUQUEROS - contacta@colladospeluqueros.com
ZEN NATURE ESTéTICA - contacta@colladospeluqueros.com
LA CASA DE MAR - Not found
DELGADO PERRUQUERS - Not found
(...output cut to save space...)


text:
Q: How can I force values of SSRS parameter to run in order entered? I have an SSRS report that takes multiple values for a parameter.  Currently, I can enter in the values for the parameter (order #s) in any order, but it will order them alphanumerically.  I do not want this, I want them to run in the order given.  How can I force this?
Let me know if you need more context.

A: You can change the order using the Report Data controls.

Reference
Let me know if this helps.


text:
Q: How to print two strings (large text) side by side in python? How do I write code in Python to do this? I want to read two strings that are multiple lines and much text, mainly to compare how similar they are (qualitatively.)
    s1 = 'I want to read these texts side by side and see how similar they really are'
    s2 = 'I really want to read these here texts side by side to see how similar they are (qualitatively)'
    print_side_by_side(s1,s2)

Output:
    I want to read these texts side by side and see ho   I really want to read these here texts side by sid
    w similar they really are                            e to see how similar they are (qualitatively)

A: Here's an approach using slicing:
def print_side_by_side(a, b, size=30, space=4):
    while a or b:
        print(a[:size].ljust(size) + " " * space + b[:size])
        a = a[size:]
        b = b[size:]

s1 = 'I want to read these texts side by side and see how similar they really are'
s2 = 'I really want to read these here texts side by side to see how similar they are (qualitatively)'
print_side_by_side(s1,s2)

Output:
I want to read these texts sid    I really want to read these he
e by side and see how similar     re texts side by side to see h
they really are                   ow similar they are (qualitati
                                  vely)

This can be generalized to work on any number of strings:
def side_by_side(strings, size=30, space=4):
    strings = list(strings)
    result = []

    while any(strings):
        line = []

        for i, s in enumerate(strings):
            line.append(s[:size].ljust(size))
            strings[i] = s[size:]

        result.append((" " * space).join(line))

    return "\n".join(result)

if __name__ == "__main__":
    strings = "aaaaaaaa", "bbbbbbbbbbbbbb", "ccccccc"
    print(side_by_side(strings, size=5, space=1))

Output:
aaaaa bbbbb ccccc
aaa   bbbbb cc
      bbbb

Note that if you're looking for more capability than this, Python has an industrial-strength solution for general diffing called difflib.

A: This is what I've done.  Let me know if there is a better way!
    def print_side_by_side(sa,sb):

        def populate_line(donor, receiver, lim):
            while donor and len(receiver)<lim:
                new_char = donor.pop(0)
                if new_char =='\n':
                    break
                receiver.append(new_char)
            while len(receiver) < lim:
                receiver.append(' ')

        la = list(sa)
        lb = list(sb)

        # number of chars per line; may have to tweak
        nline = 100
        na = nline//2
        nb = nline-na

        lines_a = []
        lines_b = []
        while la or lb:

            line_a = []
            line_b = []

            populate_line(la,line_a,na)
            populate_line(lb,line_b,nb)

            lines_a.append(line_a)
            lines_b.append(line_b)

        while len(lines_a) > len(lines_b):
            lines_b.append([' ' for k in range(nb)])
        while len(lines_b) > len(lines_a):
            lines_a.append([' ' for k in range(na)])

        assert len(lines_a) == len(lines_b)

        lines_a = [''.join(l) for l in lines_a]
        lines_b = [''.join(l) for l in lines_b]

        lines = [lines_a[k] + '   ' + lines_b[k] for k in range(len(lines_a))]

        print('\n'.join(lines))

A: Another approach in which you slice and zip the two strings in order to print them side by side is this:
s1 = 'I want to read these texts side by side and see how similar they really are'
s2 = 'I really want to read these here texts side by side to see how similar they are (qualitatively)'

maxChars = 40
maxLength = max(len(s1),len(s2))

s1 = s1.ljust(maxLength," ")
s2 = s2.ljust(maxLength," ")

s1 = [s1[i:i+maxChars] for i in range(0,len(s1),maxChars)]
s2 = [s2[i:i+maxChars] for i in range(0,len(s2),maxChars)]

for elem1, elem2 in zip(s1,s2):
    print(elem1.ljust(maxChars," "), end="    ")
    print(elem2)

Output:
I want to read these texts side by side     I really want to read these here texts s
and see how similar they really are         ide by side to see how similar they are
                                            (qualitatively)


text:
Q: Find the matrix A of the linear transformation T(f(t))=f(4) from P2 to P2 with respect to the standard basis for P2, {1,t,t2}.
Find the matrix A of the linear transformation T(f(t))=f(4) from P2 to
  P2 with respect to the standard basis for P2, {1,t,t2}. Note: You
  should be viewing the transformation as mapping to constant
  polynomials rather than real numbers, e.g. T(2+t−t2)=−4+0t+0t2.

This is a question from my linear algebra class. I have done some questions similar to this one but I am confused by the T(f(t))=f(4) part.
The answer is a 3 by 3 matrix.
Thanks.

A: Remember that $T$ maps polynomials to polynomials. A polynomial is a special type of function, and as such, we can substitute particular values into the given polynomial. In this case, the map $T$ takes a polynomial function, substitutes $t = 4$ into the polynomial to get a constant, and then turns that constant into the constant function.
For example, to compute $T(2t^2 - 1)$ we substitute $t = 4$ into the polynomial $2t^2 - 1$ to obtain the constant $2(4)^2 - 1 = 31$. So,
$$T(2t^2 - 1) = 0t^2 + 0t + 31.$$
To form the matrix, you need to compute $T(1), T(t),$ and $T(t^2)$, i.e. find the image of the basis under $T$. Then, you need to compute the coordinate column vectors for the resulting polynomials under the given basis.
Let's get you started. If we evaluate $T(1)$, we substitute $t = 4$ into the constant polynomial $1$ to get $1$ (the constant polynomial takes the value of $1$ at any $t$, including $t = 4$). So,
$$T(1) = 1 \cdot 1 + 0 \cdot t + 0 \cdot t^2.$$
Therefore, the coordinate column vector with respect to the basis $(1, t, t^2)$ is
$$\begin{bmatrix} 1 \\ 0 \\ 0 \end{bmatrix}.$$
This forms the first column of your matrix. Do the same with $t$ and $t^2$, and you'll get the other two columns.


text:
Q: Breaking phrase every 100 positions I want to include a line break "" to 100 characters, however, can not break words, if the letter is possição I break in near space, how can I do this?
The phrase is about 300 characters.

A: *

*Take 100 characters from the start of the string

*Reverse it

*Find the first space

*Calculate the break position from the start of the string using the results from step 3.

*If more than 100 characters left, repeat from step 1.


text:
Q: How to create a dynamic HTML table with Firebase? I'm trying to create an HTML table that can be updated in real time with firebase as my users use my app. I'm really struggling on getting this to work, I don't really know where to start.
basically, all it needs to do is create a new table row and update its cells in real time as the user is interacting with my app.
Does anyone know of any good tutorials that could point me in the right direction? Examples of code on creating the HTML table would also be great! thanks.
UPDATE:
OK! thanks to Isaiah Lee, I went out and looked up some tutorials for React. I'm 90% there but there is one problem I can't seem to figure out...
I'm able to update my table with new rows dynamically as the users use my app, but I can't get them to fill up with data. I feel like I'm really close but my inexperience with React is holding me back here...
for some reason, this loop here doesn't populate the td's with any data
render() {
return (

Talkeetna Numbers

          Driver
          Coach
          Time
          Total People
          AM Train
          PM Train
          MEX
          Employees
          Seats Left

        {this.state.rows.map(row =>

          {this.state.driver}
          {this.state.coach}
          {this.state.time}
          {this.state.totalPeople}
          {this.state.amTrain}
          {this.state.pmTrain}
          {this.state.THEMEX}
          {this.state.Employees}
          {this.state.seatsLeft}

)}

);

}
Heres my components function
componentDidMount()
{
  const logsRef = firebase.database().ref('logs');

  logsRef.on('child_added', snap => {

  this.addRow(snap.getKey());
  //rows.push(snap.getKey());
  console.log("adding key: ", snap.getKey());

   });

   console.log("loading rows...");

   for(var rowKey = 0; rowKey < this.state.rows.length; rowKey++)
   {

      const root = firebase.database().ref().child('logs/' + rowKey);
      const driverRef = root.child('Driver');
      const coachRef = root.child('Coach');
      const timeRef = root.child('Time');
      const totalPeopleRef = root.child('Total People');
      const AMTrainRef = root.child('AM Train');
      const PMTrainRef = root.child('PM Train');
      const MEXRef = root.child('MEX');
      const EmployeesRef = root.child('Employees');
      const seatsLeftRef = root.child('Seats Left');

      //sync with DB in real time
      driverRef.on('value', snap => {
        this.setState({
          driver: snap.val()
          })
        });
       coachRef.on('value', snap => {
         this.setState({
         coach: snap.val()
       })
       });
       timeRef.on('value', snap => {
       this.setState({
       time: snap.val()
          })
       });

       totalPeopleRef.on('value', snap => {
       this.setState({
        totalPeople: snap.val()
         })
       });

       AMTrainRef.on('value', snap => {
       this.setState({
       amTrain: snap.val()
          })
       });

      PMTrainRef.on('value', snap => {
      this.setState({
      pmTrain: snap.val()
        })
      });
      MEXRef.on('value', snap => {
        this.setState({
       THEMEX: snap.val()
        })
       });
      EmployeesRef.on('value', snap => {
      this.setState({
      Employees: snap.val()
       })
       });
       seatsLeftRef.on('value', snap => {
          this.setState({
          seatsLeft: snap.val()
          })
      });

     }

    }

A: Sounds like you should look into some frontend framework. In your particular use case, anything with 1-way binding will work (eg react). And of course, anything with 2-way binding will work as well (angular).
Egghead.io has really well done, bite-size tutorials that can get you running shortly: https://egghead.io/browse/frameworks
Edit:
Okay, it's been over a year since I've last been working with react, but I have some ideas that could help.
First, react is all about separating components and breaking things off into smaller bits. The idea is that you have some state change at the top level, those changes are propagated down into the nested components using props.
I'd recommend you have a top level component that listens for changes in Firebase (I havent worked with FB in a long time either), and then sends those down to components that render based on the data. I recommend reading this article written by Dan Abramov (creator of Redux), which discusses smart vs dumb components: https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
Again, I haven't used react in a while, so I'll use pseudocode to describe how you might want to design this.
Top Level Component
This component should be the only place your app is interacting with Firebase. You'll configure all the listeners here such that when new data is received, it simply propagates down to child components.
constructor() {

    this.firebaseRef = firebase
        .database()
        .ref('logs');

    this.state = {
        logs: []
    };

    // when the table first loads, use the
    // firebase ref to get all the current data
    // and initialize/render the table. After this,
    // you should only be listening for when a new row
    // (or "log") is added. Pseudocode:
    firebase.database().ref('logs')
        .all()
        .then(logs => {
            // project all the logs into the model we need and set to
            // component's row state
            this.state.logs = logs.map(logMapper);
        });
}

// takes in a log that you get from firebase and maps
// it to an object, modeled such that it contains all
// the information necessary for a single table row
logMapper(log) {
    return {
        driver: log.child('Driver'),
        time: log.child('Time'),
        ...
    };
}

componentDidMount() {
    const logsRef = firebase
        .database()
        .ref('logs');

    firebaseRef.on('child_added', log => {
        this.state.logs.push(logMapper(log));
    });
}

render() {
    return (

                Driver
                Coach
                Time
                Total People
                AM Train
                PM Train
                MEX
                Employees
                Seats Left

                {this.state.logs.map(row => <TableRow rowData="logs" />}

    );
}

Row Component
You have a separate component that receives a log object through props and renders a single row.
render() {
    return (

            {this.props.rowData.driver}
            {this.props.rowData.coach}
            {this.props.rowData.time}
            {this.props.rowData.totalPeople}
            {this.props.rowData.amTrain}
            {this.props.rowData.pmTrain}
            {this.props.rowData.THEMEX}
            {this.props.rowData.Employees}
            {this.props.rowData.seatsLeft}

    );
}

The above TableRow is an example of a dumb component. It doesn't hold any internal state, nor really modify anything. It just takes what it's given via props and renders what it's supposed to.
Again, you'll have to consider my examples above as pseudocode, it wouldn't work if you tried to copy and run it. But hopefully this gives you some insight into how to design components in react. Remember, "everything is a component".
Just a couple last notes:

*

*Components are more useful the more generic they are. The ideal
scenario is that you create a component, and if you need something
similar later, you can just take the component you already created
and plug it in with slight modifications (or in the best case
scenario, no change at all!). So if you see yourself needing a bunch
of similar tables in your app, you'll want to further generalize my
example. For example, the firebase ref explicitly connects with the
"logs" collection, making this table component only useful for that one object type.
You'll want to make the parent component receive either a table
name, or an already initialized firebase reference, that it can use.
That way, the component is not tied down to a specific firebase
table. The mapping function should also be passed in, as the one in
my example is hardcoded to map a "log" object, and you may be
wanting to grab other types from firebase.

*I learned a lot from reading and messing around, but honestly this one Udemy class I took really nailed down all the concepts for me: https://www.udemy.com/react-redux/
I'd highly recommend taking it, although you'd probably want to wait until Udemy has a site-wide sale where you can get the course for $10-20 bucks. I've taken several of his courses and they've all been well worth the money.

Good luck!


text:
Q: Validation rule in mysql? I have created a database for a computer inventory. My assignment says that I can only allow certain words to be entered into a field such as "Dell" and "IBM". Here's how I created the table:
Create table computer_inventory (
 assetnumber int(10) not null default 0,
 manufacturer char(3) ENUM('Dell', 'IBM', 'OtherCompany') NOT NULL default ' ',
 originalcost decimal(12,2) not null default 0,
 currentvalue decimal(12,2) not null default 0,
 boughtfrom varchar(20) not null default ' ',
 instock tinyint(1) not null default 0,
 currentuser varchar(20) not null default ' ',
 userphonenum varchar(13) not null default ' ',
 boughtdate datetime not null default '0000-00-00'
);

Now I am suppose to make it where a person can ONLY enter in "DELL" or "IBM" for manufacturer.

A: Take a look at the ENUM type for this particular use case.
This type of field allows you to explicitly state what is allowed in this column. For your case, you'd want 'Dell' and 'IBM' and any other company you want to allow.
CREATE TABLE tablename (
    company ENUM('Dell', 'IBM', 'OtherCompany')
);

This command will create a table (tablename) with a single field (company). In that field, only three values will be allowed. 'Dell', 'IBM' and 'OtherCompany'.
Edit:
Based on your edit, you can modify your manufacturer line to read as above.
manufacturer ENUM('Dell', 'IBM', 'OtherCompany') NOT NULL

One thing to note from the documentation:

If an ENUM column is declared NOT NULL, its default value is the first
  element of the list of permitted values.

In this case, that means if you don't pass a manufacturer, it will default to Dell

A: Two errors are in your code :

*

*in line three is not allow : char(3) because, you have declared values with more chars ( dell - 4 chars)

*in line three is not allow : default ' ' - because in your declared list of values isn't ' '. There can be only values from list ENUM('Dell', 'IBM', 'OtherCompany')

the right code :
Create table computer_inventory (
assetnumber int(10) not null default 0,
manufacturer ENUM('Dell', 'IBM', 'OtherCompany') NOT NULL,
originalcost decimal(12,2) not null default 0,
currentvalue decimal(12,2) not null default 0,
boughtfrom varchar(20) not null default ' ',
instock tinyint(1) not null default 0,
currentuser varchar(20) not null default ' ',
userphonenum varchar(13) not null default ' ',
boughtdate datetime not null default '0000-00-00')


text:
Q: Java - Mismatch and method is undefined error //  The section below is what raises the error, I am modifying a simple banking application i found online. I am very new to Java, about 3 days I've been dabbling in it, and thought this would be a good little activity to do to get me used to the syntax of the code and methods etc. I have been looking at this problem for about a day now and cant figure out what exactly the problem is. The only thing that would come to mind would be that the showMenu() method is possibly out of scope for the main section im referring it in, however im not to sure.
P.S. If i have missed anything out that could be of us, i apologise as i have never posted on here before!
EDIT - The new error is:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    The constructor BankApplication.BankAccount(String, String) is undefined
    The method showMenu() is undefined for the type BankApplication.BankAccount

    at BankApplication.main(bank.java:9)

public static void main(String[] args)
{
 BankAccount obj1 = new BankAccount("Ye Ma", "X Æ A-12");
 obj1.showMenu();
}

//The showMenu code
void showMenu()
{
    Scanner sc = new Scanner(System.in);

    System.out.println("Welcome to the Bank");
    System.out.println("Your Customer ID is: " + cID);
    System.out.println("");

    System.out.println("1. To view you Bank Balance.");
    System.out.println("2. To make a deposit.");
    System.out.println("3. To make a withdrawel.");
    System.out.println("4. To view your previous transaction.");
    System.out.println("5. To exit.");

    do
    {
        System.out.println("----------------------------------------------------------------------");
        System.out.println("        Choose an option        ");
        System.out.println("----------------------------------------------------------------------");
        System.out.println("");
        option = sc.nextInt();

        if(option == 1)
        {
            System.out.println("----------------------------------------------------------------------");
            System.out.println("  Your bank balance is: " + balance);
            System.out.println("----------------------------------------------------------------------");

            break;
        }
        else if(option == 2)
        {
            System.out.println("----------------------------------------------------------------------");
            System.out.println("How much would you like to deposit?");
            System.out.println("----------------------------------------------------------------------");
            int amount = sc.nextInt();
            deposit(amount);
            break;
        }
        else if(option == 3)
        {
            System.out.println("----------------------------------------");
            System.out.println("  How much would you like to withdraw?: ");
            System.out.println("----------------------------------------------------------------------");
            int amount = sc.nextInt();
            withdraw(amount);
            break;
        }
        else if(option == 4)
        {
            System.out.println("----------------------------------------------------------------------");
            System.out.println("Your previous transaction was: " + getPreviousTransaction(amount));
            System.out.println("----------------------------------------------------------------------");
            System.out.println("");
        }
        else if(option == 5)
        {
            System.out.println("**********************************");
            System.out.println("        END OF APPLICATION        ");
            System.out.println("**********************************");
        }

        else
        {
            System.out.println("Invalid option, please choose a valid option.");
        }
    }while(option != 5);

A: i think you are trying to call showMenu() which is not available in BankAccount class.


text:
Q: Understanding driving a relay with a transistor For an embedded application, I'd like to drive a relay using a transistor. At the moment I'm experimenting with a BC547, but only because I've still got some of them lying around.
The transistor I am using is rated at a max of 100mA continuous for the collector (or collector-emitter) current (if I exceed that it gets really hot and would eventually get destroyed, I guess). A typical relay that I'd probably use would have a coil resistance of e.g. 225 Ω and a nominal switching current of 53 mA at 12 V (I'd opt to use a 12 V relay, because I already have 3.3 V and 12 V in my circuit).
I'd guess that the nominal switching current simply equates to the voltage devided by the resistance, am I right? Hence I assume that it would be safe driving the relay with the transistor, because the current should not exceed the 53 mV, which is well below the maximum current the transistor can bear. Am I correct?
(I am aware that the description only holds for the static state when the relay is shut. I do know that there will be spikes induced by the coil when the relay switches, that have to be buffered using a diode.)

A: For reasons that have little to do with the static calculations in the other answers, I would use a beefier transistor such as the 600mA 2N4401 or a MOSFET. Switching an inductive load is harder on the transistor than switching a resistive load, even with the diode. At some point the full relay coil current is flowing through the transistor for a short period of time with more than 12V across it. SOA is unspecified on many of the small transistors.
Give a 2N4401 a few mA of base current and it will be happy switching your inductive 53mA load, and don't forget the diode across the coil. If you need to operate in extreme cold conditions, 5 or 6mA would be better.

A: Your calculations make sense.
You should also calculate the transistor's power dissipation to make sure it doesn't overheat. Note that when the relay is on, the voltage across the transistor is only about 0.2V (this is a typical number for silicon transistors), not the full 12V - the remainder is across the relay. The power dissipation should be about 0.2V x 0.053A = 0.0106W. I would expect that to be just fine without a heatsink, but if you want, you can calculate the temperature the transistor will reach, based on the thermal resistance specified in the datasheet.
(Note that the relay only gets 11.8V across it, not 12V, so the current is slightly lower than 53mA, but it's such a small difference, 53mA is good enough for this calculation)
This assumes the dissipation from base current (which controls the transistor) is much less than the dissipation from the collector current (which goes through the relay). If your base resistor is way too low, it could dissipate extra power in the base. If your base resistor is way too high, the transistor might not turn fully on, and the voltage across it might be more than 0.2V, which also increases power dissipation in the transistor.

A: A PN2222A has a4 Ohm Rce while the 2N290x series is about 7 Ohms but in order to achieve this with Vce=Vce(sat) they are rated with Ic/Ib=10
So try to achieve 10% to 5% of relay coil current if possible.  CMOS logic in the 74HC' family is about 50 Ohms so keep that in mind in series with your base R.
if you use only 1% then a higher Vce and power dissipation may occur.
A 1N4148 diode is sufficient for reverse BEMF clamping to Vcc.


text:
Q: Recital-style program code returns 0.0 when no output is needed I am trying to write a program that reads numbers from standard input but when the user enters zero, the program recites all the numbers entered (excluding the zero). My code so far works for most cases i can think of; except when the number 0 is inputted. This is my code thus far:
user_input = float(input("Number: "))
ls = []
bs = []
ls.append(user_input)

# Keep getting inputs
while user_input != 0.0:
    user_input = float(input("Number: "))

    # Don't add the 0
    if user_input != 0.0:
        ls.append(user_input)

if user_input == 0.0:
    bs.append(user_input)

# Print them all back out in order:
print("")
print("Your numbers were:")
i = 0
while len(ls) > i:
        print(ls[i])
        i += 1

When 0 is given as the input; this is returned
Number: 0

Your numbers were:
0.0

when i need:
Number: 0

Your numbers were:

A: As stated in comments, line number 3 should be :
if user_input > 0 :ls.append(user_input)


text:
Q: HTML/JS app within an Android App Im looking to create an application written in HTML/JS and wrapped within a Android App. The reason for this is that I need to access the device's components (such as the microphone and storage) but because of time restraints I do not have time to full learn Android development. I am fluent in HTML/JS so it would not take me very long to write the core of the application in these languages. My thought was to write the application in HTML/JS and use a webview within the Android app, then record sounds from the microphone using Java and send them to the HMTL/JS webview.
Can anyone tell me if this is possible and if so point me in the right direction of where to start. If not is there another way that I can do this?

A: Have a look at PhoneGap, they provide exactly what you want to create yourself.
Or one of a list of similar solutions.


text:
Q: How do I get the access token without using the browser When I go to the following URL in the browser with my own client_id:
https://account-d.docusign.com/oauth/auth?response_type=token&scope=signature&client_id=6d1a8594-xxxx-xxxx-xxxx-878e593de049&state=a39fh23hnf23&redirect_uri=http://localhost:8888/auth
I need to login and afterwards I get redirected to:
http://localhost:8888/auth#access_token=myAccessToken&expires_in=28800&token_type=bearer&state=a39fh23hnf23
Now I have a node.js application where I want to make API calls using my access token, until now I did the above manually every time to get my access token, of course, this isn't optimal. My question, therefore, is: how do I get my access token without using the browser?
Right now I have the following
sendRequestAccessToken(): Promise<any> {
const scope = 'signature';
const clientId = '*my client id*';
const state = 'a39fh23hnf23';
const url = `https://account-d.docusign.com/oauth/auth?
  response_type=token
  &scope=${scope}
  &client_id=${clientId}
  &state=${state}
  &redirect_uri=http://localhost:8888/auth
`;
return this.httpService.get(url).toPromise(); }

The response from this function contains a lot of data, but no access token.

A: Please review the SDK examples we have here: https://github.com/docusign/code-examples-node
In those samples, we have examples on how to use the tokens using the apis.


text:
Q: Fresh install /usr/share/X11/xkb/ folder online? I made a few changes in my /usr/share/X11/xkb/ folder to deal with a troublesome keyboard, I am now getting a new keyboard and want to completely reset this folder back to the defaults that were on my PC when ubuntu was freshly installed. Where do I find a copy of this folder?

A: If you only edited pre-existing files in /usr/share/X11/xkb/ (rather than adding new files), then I think it should be sufficient to re-install the xkb-data package - either using the Software application, or from the command line
sudo apt install --reinstall xkb-data

If you still believe you need to find a copy online, then you can search by package name at packages.ubuntu.com and select the appropriate package for your version from there.


text:
Q: The constructor SamplePagerAdapter(List) refers to the missing type List fltut.java
 public class fltut extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LayoutInflater inflater = LayoutInflater.from(this);
        List<View> pages = new ArrayList<View>();

        View page = inflater.inflate(R.layout.fltut, null);
        TextView textView = (TextView) page.findViewById(R.id.desc);
        textView.setText(getResources().getString(R.string.fld1));
        ImageView imgView = (ImageView) page.findViewById(R.id.img);
        imgView.setImageResource(R.drawable.fl1);
        TextView stpView = (TextView) page.findViewById(R.id.stp);
        stpView.setText("1/12");
        pages.add(page);

             ...

        View page12 = inflater.inflate(R.layout.fltut, null);
        TextView textView12 = (TextView) page12.findViewById(R.id.desc);
        textView12.setText(getResources().getString (R.string.fld12));
        ImageView imgView12 = (ImageView) page12.findViewById(R.id.img);
        imgView12.setImageResource(R.drawable.fl12);
        TextView stpView12 = (TextView) page12.findViewById(R.id.stp);
        stpView12.setText("12/12");
        pages.add(page12);

        SamplePagerAdapter pagerAdapter = new SamplePagerAdapter(pages); //ошибка здесь: The constructor SamplePagerAdapter(List<View>) refers to the missing type List
        ViewPager viewPager = new ViewPager(this);
        viewPager.setAdapter(pagerAdapter);
        //viewPager.setCurrentItem(1);

        setContentView(viewPager);

}

SamplePagerAdapter.java
import java.util.List;

import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;

public class SamplePagerAdapter extends PagerAdapter{

    List<View> pages = null;

    public SamplePagerAdapter(List<View> pages){
        this.pages = pages;
    }
}

При запуске fltut.java:

The constructor SamplePagerAdapter(List<View>) refers to the missing type List    attut.java

И приложение вылетает. Самое интересное - раньше работало без ошибки. Ничего не менял, но почему-то появилось ошибка.
Ну и вопрос - как исправить?
p.s. Сори за много кода, старался сократить как мог :)
A: List<View> pages = null;

на
List<View> pages;


text:
Q: Calculate the area of all those squares, whose 2 corners are on the parabola and 2 remaining are on the x axis You have a parabola $y=x^2-12x+36$. Calculate the area of all those squares, whose $2$ corners are on the given parabola and $2$ remaining are on the $x$-axis

A: You can start with the fact that if there is a square it has to be centred around the parabola. This means that it's around the point $(6,0)$. So we assume one corner is some $h$ distance to the left of it and one is $h$ distance to the right. This gives us the points $(6- h,0)$ and $(6+h,0)$. Now for it to be a square two vertical lines will go up from this point to meet the parabola. The vertical distance must be equal to the total horizontal distance which is $(6+h)-(6-h)=2h$.
To find out the vertical distance evaluate where the vertical lines will meet the parabola by putting in the $x=6-h$ and $x=6+h$.
$$y= (x-6)^2=(6-h-6)^2=h^2$$
So the vertical distance is $h^2$. Equating the vertical and the horizontal distances, we get
$$2h=h^2$$
$$h=2$$
and
$$h=0$$
$h=0$ is not allowed as it gives us a single point for all corners. When we put $h=2$, we get the $x$-axis points as $(4,0)$ and $(8,0)$. So the side of a square is $d=8-4=4$. Hence the area is $A=4\cdot4=16$


text:
Q: Java code snippet logic I cannot see what I am doing wrong here. Here is the code I am having trouble with :
String tempSummaryString = "SUMMARY:";
for(int z = 0; z<attributeList.size() ; z++)
{
    System.out.println(attributeList.get(z).substring(0,tempSummaryString.length()));
    if(attributeList.get(z).length() > tempSummaryString.length() &&
       attributeList.get(z).substring(0,tempSummaryString.length() == tempSummaryString)
    {
            event.setTitle(attributeList.get(z).substring(tempSummaryString.length(),attributeList.get(z).length()));
    }
}

Now my problem is that the program never goes into the if (does not execute the event.setTitle method). When I print the value of
attributeList.get(z).substring(0,tempSummaryString.length())

I get the following:

SUMMARY:

So I am stumped about why it is not entering the if! I don't get it!
Hopefully someone can point out a stupid mistake I am making because I really dont know what else to do

A: Don't compare strings using the == operator (as in attributeList.get(z).substring(0,tempSummaryString.length()) == tempSummaryString), use the String.Equals method instead.

A: You've fallen for the old == vs equals() problem. You are using ==, which unlike javascript, does an identity comparison (ie are these the same objects).
Try this:
attributeList.get(z).substring(0,tempSummaryString.length())
    .equals(tempSummaryString) // equals() not ==

Also, you should consider using the foreach syntax for your loop:
for (String attribute : attributeList) {
    if (attribute.substring... // forget about attributeList.get(z) and even z
}

A: Your problem is this: attributeList.get(z).substring(0,tempSummaryString.length())== tempSummaryString. You compare references, not string contents. Use String.equals(otherString) to that end.

A: You should compare the Strings with equals().
attributeList.get(z).substring(0,tempSummaryString.length()).equals(tempSummaryString)

A: You're comparing strings with ==, while you should use the String class' .equals() method.


text:
Q: How to set sound playback from external speaker? There is a kind of weird issue, I am using oboe lib https://github.com/google/oboe, for sound playback. Of course you can choose sound playback output according to android settings
https://developer.android.com/reference/android/media/AudioDeviceInfo
So, if I need to set exact output chanel I need to set it to oboe lib.
By the way output chanal that I need is TYPE_BUILTIN_SPEAKER, but on some devices (sometimes, not constantly) I hear the sound from
TYPE_BUILTIN_EARPIECE
How I am doing this, I have such method to get needed chanel id
fun findAudioDevice(app: Application,
                            deviceFlag: Int,
                            deviceType: Int): AudioDeviceInfo?
        {
            var result: AudioDeviceInfo? = null
            val manager = app.getSystemService(Context.AUDIO_SERVICE) as AudioManager
            val adis = manager.getDevices(deviceFlag)

            for (adi in adis)
            {
                if (adi.type == deviceType)
                {
                    result = adi
                    break
                }
            }

            return result
        }

How I use it
val id = getAudioDeviceInfoId(getBuildInSpeakerInfo())

private fun getBuildInSpeakerInfo(): AudioDeviceInfo?
    {
        return com.tetavi.ar.basedomain.utils.Utils.findAudioDevice( //
                getApplication<Application>(), //
                AudioManager.GET_DEVICES_OUTPUTS, //
                AudioDeviceInfo.TYPE_BUILTIN_SPEAKER //
        )
    }

private fun getAudioDeviceInfoId(info: AudioDeviceInfo?): Int
    {
        var result = -1

        if (info != null)
        {
            result = info.id
        }

        return result
    }

And eventually I need to set this id to oboe lib. Oboe lib is native lib, so with JNI I pass this id and set it
oboe::Result oboe_engine::createPlaybackStream()
{
    oboe::AudioStreamBuilder builder;
    const oboe::SharingMode sharingMode = oboe::SharingMode::Exclusive;
    const int32_t sampleRate = mBackingTrack->getSampleRate();
    const oboe::AudioFormat audioFormat = oboe::AudioFormat::Float;
    const oboe::PerformanceMode performanceMode = oboe::PerformanceMode::PowerSaving;

    builder.setSharingMode(sharingMode)
            ->setPerformanceMode(performanceMode)
            ->setFormat(audioFormat)
            ->setCallback(this)
            ->setSampleRate(sampleRate);

    if (m_output_playback_chanel_id != EMPTY_NUM)
    {
        //set output playback chanel (like internal or external speaker)
        builder.setDeviceId(m_output_playback_chanel_id);                  <------------- THIS LINE
    }

    return builder.openStream(&mAudioStream);
}

So, actually issue is that on some devices (sometimes, not constantly) I still hear that sound playback goes from internal speaker TYPE_BUILTIN_EARPIECE inspite of I set directly that I need to use TYPE_BUILTIN_SPEAKER
I checked a few times the flow, from moment that I get this id (it is acctually is 3) and up to the moment when I set it as a param to oboe lib, but still sometimes I hear sound from internal speaker.
So, question is - if I miss something here? Maybe some trick should be implemented or something else?


text:
Q: ZFS: How could my file got permanently corrupted? I'm trying to understand what could have gone wrong.
for context:
I have a mirrored set with 3 drives and non-ECC memory. Not sure what else to share.
I was under assumption that having a 3-way mirror would keep me relatively secure from incidental corruptions, like failing drives, or that memory corruption would be recoverable (from one of 2 remaining disks).
But I'm probably misunderstanding.
Can anyone explain what could have gone wrong so I can secure myself for the future?
$ sudo zpool status -v
  pool: dozer
 state: ONLINE
status: One or more devices has experienced an error resulting in data
    corruption.  Applications may be affected.
action: Restore the file in question if possible.  Otherwise restore the
    entire pool from backup.
   see: http://zfsonlinux.org/msg/ZFS-8000-8A
  scan: scrub repaired 0 in 8h36m with 1 errors on Sun Jan  6 02:12:32 2019
config:

    NAME                                          STATE     READ WRITE CKSUM
    dozer                                         ONLINE       0     0     1
      mirror-0                                    ONLINE       0     0     2
        ata-WDC_WD40EFRX-68N32N0_WD-WCC7K1ZKZLYK  ONLINE       0     0     2
        ata-WDC_WD40EFRX-68N32N0_WD-WCC7K6VCAZXL  ONLINE       0     0     2
        ata-ST4000DM000-1F2168_S301LW48           ONLINE       0     0     2

errors: Permanent errors have been detected in the following files:

        /dozer/path/to/my/file

A: You do understand that if any single non-RAIDed drive has a failure, you lose data and the same is true if one of the non-ECC memory chips has a failure: you lose data.
And even if you have:

*

*dual processors

*dual NICs

*dual hard drives

*ECC memory

*High-availability fail-over servers in a different data centre on a different continent

...any kind of uncorrectable error (Bug, human, Electro-Magnetic Pulse, .. ) can still lead to data loss.
And that's why, with all this nifty technology, we still have multiple off-line backups today.
Note: On-line backups / Data replication to a secondary Data Centre can be corrupted too in this way