text:
Q: Can't set the size of a frame inside a canvas I'm making a grid layout of text boxes, something that resembles Microsoft Excel.
I have made a canvas (Inside a frame) and used create_window to add a frame with 100 text boxes (each one inside of a frame) into the canvas, to be able to scroll them in and out of view, using scrollbars on the right side and the bottom, much like in Microsoft Excel. The reason the text boxes are each in their own frame, is so i can define their size in pixels by making the text boxes fill the frame. My issue is that when i set the size of the frame that holds the text box, it doesn't change the size of the frame at all. It is by default the size of the text box, as if the frame isn't even there. please help? Code Below:
    def __init__(self, master):
        master.title('Table Viewmode')
        #'widthxheight+Xoffset+Yoffset'
        master.geometry('800x600+500+200')

        self.tableContainer = Frame(master)
        self.tableContainer.pack(side="left", fill="both", expand=True)

        #Frame and Canvas
        self.tableCanvas = Canvas(self.tableContainer)
        self.tableFrame = Frame(self.tableCanvas)
        #Canvas stretch config
        self.tableCanvas.grid(row=0, column=0, sticky=N+S+E+W)#.pack(side="left", fill="both", expand=True)
        self.tableContainer.grid_columnconfigure(0, weight=1)
        self.tableContainer.grid_rowconfigure(0, weight=1)

        #Scrollbars
        self.yscrollBar = Scrollbar(self.tableContainer, orient=VERTICAL,
                                    command=self.tableCanvas.yview)
        self.yscrollBar.grid(row=0, column=1, sticky=N+S)
        self.tableCanvas.config(yscrollcommand=self.yscrollBar.set)
        self.xscrollBar = Scrollbar(self.tableContainer, orient=HORIZONTAL,
                                    command=self.tableCanvas.xview)
        self.xscrollBar.grid(row=1, column=0, sticky=W+E)
        self.tableCanvas.config(xscrollcommand=self.xscrollBar.set)
        self.xscrollBar.config()

        self.tableCanvas.create_window((4,4), window=self.tableFrame, anchor="nw")

        self.createTable(10,10)

        self.tableFrame.bind("<Configure>", self.frameConfigureHandler)

    #Lines of code in question
    def createTable(self, rows, columns):
        self.frameList = []
        for row in range(0, rows):
            for column in range(0, columns):
                frame = Frame(self.tableFrame)
                frame.config(width=10,height=10)
                text = Text(frame)#, height=1, width=2) I can change the size of the text boxes, this works fine.
                text.insert(END, str(row)+str(column))
                text.pack(side=LEFT, expand=True, fill=BOTH)
                frame.grid(row = row, column = column)

    def frameConfigureHandler(self, event):
        self.tableCanvas.configure(scrollregion=self.tableCanvas.bbox("all"))

A: frame.pack_propagate(False) this will stop the frame from conforming to the size of it's child and allow the size of the frame to be customised.


text:
Q: prevent sending http post request headers I want to send a raw http request without any header. Just data. I tried jQuery ajax and post functions. I also tried angular 8.
please note that I don't want to set content-type to something. I want to completely get rid of it. You can do that with postman

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does array size need to be const? I was taught that if we define array[N], then N should be a const variable or a const expression. But now i find the following code can be compiled and run correctly.(I use g++ 4.8.3, if i use vs2010, there will be a compiled error:error C2057: expected constannt express)
#include<iostream>
int main()
{
    int N;
    std::cin>>N;
    int A[N];
    for(int i=0;i<N;++i)
       std::cin>>A[i];
    for(int i=0;i<N;++i)
        std::cout<<A[i]<<" ";
    return 0;
}

Obviously N is not const type. I use g++ 4.8.3

A:
"Does array size need to be const?"

Yes, according the current c++ standard, array size specifiers need to be const expressions.
A number of compilers support VLA's (variable length arrays) allocation on the stack. It's a compiler extension and isn't portable code.
If you need a portable variant, you can use a std::vector<int> like follows
int N;
std::cin>>N;
std::vector<int> A(N);

A: It seems that the first compiler has its own language extension that allows to use Variable Length Arrays (that are introduced in C).
Nevertheless this feature is not C++ compliant. According to the definition of arrays in C++ the size of an array if it is present shall be a constant expression greater than zero:
D1 [ constant-expressionopt] attribute-specifier-seqopt

From the C++ Standard (8.3.4 Arrays)

*

*...If the constant-expression (5.19) is present, it shall be a converted constant expression of type std::size_t and its value shall
  be greater than zero.


text:
Q: Displaying two fullscreen windows on two monitors in Adobe AIR on Mac OS X (Mavericks) I'm on Mac OS X (Mavericks). Using Adobe AIR, I want to display separate fullscreen windows on each of my two monitors (builtin laptop retina display and external hdmi monitor).
I'm able to get a fullscreen window on my main monitor and an almost fullscreen window on the secondary one. When I say 'almost', I mean that the window is fullscreen except for the space at the top where the menu bar would be (the desktop's background image is showing):

At first I thought it was a problem with AIR but I'm starting to think it may be an OS X limitation. If I interact with the primary screen, everything is normal. However, if I click on the secondary screen, the menu bars on both screens appear. It is as though only the first screen is really in "fullscreen mode". It seems the second one is treated as a maximized chromeless window.
Do you guys know what's going on ? Here is the code I'm using:
package {

    import flash.display.NativeWindow;
    import flash.display.NativeWindowInitOptions;
    import flash.display.NativeWindowSystemChrome;
    import flash.display.Screen;
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageDisplayState;
    import flash.display.StageScaleMode;
    import flash.text.TextField;
    import flash.text.TextFormat;
    import flash.text.TextFormatAlign;

    public class TwoFullscreenNativeWindowsInTwoMonitors extends Sprite {

        public var secondWindow:NativeWindow;

        public function TwoFullscreenNativeWindowsInTwoMonitors() {

            // Make primary (default) window's stage go fullscreen
            stage.align = StageAlign.TOP_LEFT;
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
            stage.color = 0xC02A2A; // red

            // Create fullscreen window on second monitor (check if available first)
            if (Screen.screens[1]) {

                // Window
                var nwio:NativeWindowInitOptions = new NativeWindowInitOptions();
                nwio.systemChrome = NativeWindowSystemChrome.NONE;
                secondWindow = new NativeWindow(nwio);
                secondWindow.bounds = (Screen.screens[1] as Screen).bounds;
                secondWindow.activate();

                // Stage
                secondWindow.stage.align = StageAlign.TOP_LEFT;
                secondWindow.stage.scaleMode = StageScaleMode.NO_SCALE;
                secondWindow.stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
                secondWindow.stage.color = 0x387D19; // green

            }

        }

    }

}

UPDATE 1:
I managed to fill the menu bar space by using an ugly hack... That is, by waiting a second and then re-setting the window height. However, the second window is still not acting "fullscreen". If I click on it, the menu bar appears...
One can achieve a similar result by ticking off the "Displays have separate Spaces" checkbox in OS X Mission Control preference pane
UPDATE 2:
It seems this is a long standing bug known by Adobe since 2011...


text:
Q: angularjs $routeParams.x giving me a value of undefined I set up my routing as follows:
.when('/:countryName/:categoryName', {
    templateUrl: 'views/about.html'
  })

Problem is I am having trouble pulling the values from my $routeParams object
For example when I do this:
$scope.parameters = $routeParams;

$scope.parameters equals the following object
{"countryName":"Japan","categoryName":"Football"}
However if I try assign the following:
$scope.parameters = $routeParams.countryName;

$scope.parameters is undefined
PLUNKER of issue I am having
Why is this? What am I doing wrong?

A: You have to unserialize $routeParams with angular.toJson($routeParams);

A: You need to use a very short $timeout before you try to access $routeParams.
$timeout(function () {

    console.log("$routeParams.x: ", $routeParams.x);

    continueAppLoad();

}, 100);


text:
Q: Space and Tab characters show up weirdly in Word 2010 Each time I hit the spacebar, it puts a dot mid line, and when I hit tab key I get an arrow which points to the right of the line.
How do I get rid of those marks?

A: You have the hidden characters visible. It is either under Options or Preferences where you can change the See Hidden Characters.

A: in "home" tab, click on the key shown in the image below with red circle.


text:
Q: Linux Shell script Sed inserting I need to write a shell script to insert a parameter string after every big letter in a file.
$parameter="4"

Example input.txt
AppLe
House

Example output.txt
A4ppL4e
H4ouse

I've tried to use
sed '/[A-Z]/i\$1\'

Can anyone help me?
THX

A: With GNU/BSD/busybox sed which support the -i option:
param=4
sed -i'' -e 's/\([[:upper:]]\)/\1'"$param"'/g' input.txt

This replaces each uppercase letter inside the captured group \(...\) globally with the first captured group \1 and the value of variable param in-place.

With standard sed you need a temporary file or sponge from the moreutils package:
param=4
sed 's/\([[:upper:]]\)/\1'"$param"'/g' input.txt > temp && mv temp input.txt

param=4
sed 's/\([[:upper:]]\)/\1'"$param"'/g' input.txt | sponge input.txt

A: Use a file editor like ed to edit files:
printf "%s\n" 'g/[[:upper:]]/s/\([[:upper:]]\)/\1'"$param"'/g' w | ed -s input.txt

or if you like heredocs better
ed -s input.txt <<EOF
g/[[:upper:]]/s/\([[:upper:]]\)/\1${param}/g
w
EOF


text:
Q: PHP MySQL Database backend Can someone please tell me what is wrong with this line?
VALUES('$_POST[POS]','$_POST[GP]','$_POST[Goals]','$_POST[Assists]','$_POST[Points]','$_POST[Polarity]','$_POST[PPG]','$_POST[SHG]','$_POST[PIM]','$_POST[Hits]','$_POST[Shots]','$_POST[Shots %]')";

It's in context with:
<?php
 $con = mysql_connect("localhost","ernie","gomes");
 if (!$con)
   {
   die('Could not connect: ' . mysql_error());
   }

mysql_select_db("ernie", $con);

$sql="INSERT INTO statplayer (POS, GP, Goals, Assists, Points, Polarity, PPG, SHG, PIM, Hits, Shots, Shot %)
VALUES('$_POST[POS]','$_POST[GP]','$_POST[Goals]','$_POST[Assists]','$_POST[Points]','$_POST[Polarity]','$_POST[PPG]','$_POST[SHG]','$_POST[PIM]','$_POST[Hits]','$_POST[Shots]','$_POST[Shots %]')";

if (!mysql_query($sql,$con))
   {
   die('Error: ' . mysql_error());
   }
 echo "1 record added";

mysql_close($con)
 ?>

A: As the comments to the question have been suggesting, it seems to be due to the space in Shots %. This needs to be quoted, in both SQL and PHP. Your error is a PHP error, but I think you'll get an SQL error once you fix it.
See below for how to put quotes around that name.
$sql="INSERT INTO statplayer (POS, GP, Goals, Assists, Points, Polarity, PPG, SHG, PIM, Hits, Shots, `Shot %`)
VALUES('$_POST[POS]','$_POST[GP]','$_POST[Goals]','$_POST[Assists]','$_POST[Points]','$_POST[Polarity]','$_POST[PPG]','$_POST[SHG]','$_POST[PIM]','$_POST[Hits]','$_POST[Shots]','."$_POST['Shots %']."')";

or
$sql="INSERT INTO statplayer (POS, GP, Goals, Assists, Points, Polarity, PPG, SHG, PIM, Hits, Shots, `Shot %`)
VALUES('$_POST[POS]','$_POST[GP]','$_POST[Goals]','$_POST[Assists]','$_POST[Points]','$_POST[Polarity]','$_POST[PPG]','$_POST[SHG]','$_POST[PIM]','$_POST[Hits]','$_POST[Shots]','{$_POST['Shots %']}')";

But please read about SQL Injection and how to prevent it. Your code is completely vulnerable.

A: It looks like there are many problems with your code, but we all have to start somewhere. At the top of your script, put the following to turn on error reporting:
error_reporting(-1);

You should do this for every file you have in order to produce better code. To answer your question, the reason it's failing is because you need to put curly braces around your array variables, like this:
$string = "Some text with a {$array['var']} variable";

Also, notice that 'var' has quotes around it. You cannot do $array[var] (without quoting 'var' or else you're going to get a notice that var has not been defined. Also, it is not recommended to use spaces or characters like '%' in your variable names. I have therefore changed it in the example below to 'ShotPercent' instead.
As many other people have mentioned, your script is vulnerable to SQL injection, so I would highly recommend you ditch the mysql_* functions completely. They are outdated. Instead, use PDO. Something like this should work:
<?php

$host = 'localhost';
$dbname = 'ernie';
$user = 'ernie';
$pass = 'gomes';

try {
    $dbh = new LoggedPDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $dbh->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC );
} catch(PDOException $e) {
    die("DB connection error: ".$e->getMessage());
}

$sql="INSERT INTO statplayer (POS, GP, Goals, Assists, Points, Polarity, PPG, SHG, PIM, Hits, Shots, ShotPercent)
    VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )";
$sth = $dbh->prepare($sql);

try {
    $sth->execute(array($_POST['POS'], $_POST['GP'], $_POST['Goals'], $_POST['Assists'], $_POST['Points'], $_POST['Polarity'], $_POST['PPG'] , $_POST['SHG'], $_POST['PIM'], $_POST['Hits'], $_POST['Shots'],$_POST['ShotPercent']));
} catch(PDOException $e) {
    die(echo $e->getMessage());
}

echo $sth->rowCount() .' record(s) added';


text:
Q: Windows authentication not loading user I have configured my Business Application to use Windows Authentication. From everything that I have read I don't need to change anything, and it should just load the currently logged in user.  This is not the case.  In the Application_Loaded method, the User is empty.

Even when I upload the project to a server, I still get an empty user.  Can anyone help me out?

A: After looking at this for a whole day, I've finally found the problem.  I had to remove all of the <roles>, <profile> and <membership> from the web.config.  I also added [ProfileUsage(IsExcluded=false)] to the FriendlyName property in the User class.


text:
Q: PostgreSQL Admin Tool for mac os X I'm looking for desktop admin tool similar to phpPgAdmin  for POstgreSQL in Mac os X . Any recomendation?

A: PgAdmin is a good admin tool, and works with Mac OS X. PhpPgAdmin should also work on OS X, although you'd need to install and set up PHP, which I can offer no advice on.

A: PgAdmin on Mac OS X is not the same as other OSs.
For example, you can't just paste text in SQL Query Editor, it gets broken and you have to paste in scratch pad first, then copy & paste in editor. Although for administer database, tables, indexes, I still use it.
I prefer create tables, indexes and so on by commands, so I prefer Aqua Data Studio. I have tried others, but none of them satisfied me. Although Aqua is expensive, it has a student "mode" that you can try for a while, or if you are one, use as you need. Version 4.7 does not limit the time you use.
It shows databases, table structures, indexes and so on, but the really good part, to me, is the editor. When you use it, and know how to work properly, the shortcuts and "extras" are very helpful. Just make a query and hit Apple + R to export a nice XLS report. Select table name and hit Apple + D and it shows the table structure right on results panel. Type INSERT INTO schema.table ( AND hit Apple + Alt + C and you get all fields typed, or SELECT FROM schema.table JOIN schema.table2 AND, get your cursor right after the SELECT word, hit Apple + Alt + X to get all field "table-qualified".
Also, it has a nice import/export tool. If you receive a file which contains data you need to import and work on it, you can parse it (from CSV, XLS, SQL file or other types) and populate an existing table and even create a new table to suit the new data.
Although it has a little bug (as related here: https://serverfault.com/questions/226736/postgresql-jdbc-parse-too-slow-on-first-query), it works really fine. And can connect to other databases as well.

A: Still in its alpha version but http://inductionapp.com/ seems like a good option as well


text:
Q: Javascript animate div to position of other divs? Alright, so I haven't been able to find an answer that suits what I am looking for. I am in need of a simple script that can animate a colored div to the position of a menu selection or navigation button. I want it to animate to the position of the div that the cursor is hovering over, but I don't want it to follow the cursor, I just want it to slide over to a portion of text on the menu to act as a highlight, or selector. Here is a JSFiddle. Oh, and one more thing. I would like the highlight to slide back to its original position(the selected menu item) after the menu has been hovered off of. EXAMPLE: (if 'about' selected, and 'home' hovered, slide to 'home', but slide back to 'about' if hovered off without selection). Any help is greatly appreciated!
http://jsfiddle.net/hbv63znv/

var main = function() {
    $('.menu-item1').hover(function() {
      $('.hover').animate({
          left: ''
      });
    });
}

$(document).ready(main);

/*
Had to remove a few of the buttons to fit it in the JSFiddle page but I want to make the highlight slide to the position of each selection. I also want it to conform to the size(width) of the button. It would also be very nice if it automatically did all the animations by itself, by this I mean that the highlight would automattically conform to the size of the button instead of having a fixed width and position to slide to(This would allow me to change the text of the menu and I wouldnt have to change any of the javascript.
*/
/*Initial body */
body {
  left: 0;
  margin: 0;
  overflow: hidden;
  position: relative;
}

/* Initial menu */
.menu {
  position: fixed;
  left: 30%;
  right: 30%;
  width: 40%;
  text-align: center;
  background-color: black;
  padding-left: 10px;
  padding-right: 10px;
  -webkit-transform: skew(20deg);
  -moz-transform: skew(20deg);
  -o-transform: skew(20deg);
}

/* Basic styling */

.content {
  background-color: #E0E0E0;
  height: 100%;
  -webkit-background-size: cover;
     -moz-background-size: cover;
       -o-background-size: cover;
          background-size: cover;
}

.menu ul {
  list-style: none;
  margin: 0;
  padding-left: 5px;
  padding-right: 5px;
  -webkit-transform: skew(-20deg);
     -moz-transform: skew(-20deg);
       -o-transform: skew(-20deg);
}

.hover {
  height: 100%;
  width: 100px;
  background-color: #303030;
  position: absolute;
  margin-left: 30px;
}

.menu li {
  font-family: 'Open Sans', sans-serif;
  line-height: 45px;
  padding-bottom: 3px;
  padding-left: 30px;
  padding-right: 30px;
  padding-top: 3px;
  display: inline
}

.menu a {
  color: #fff;
  font-size: 15px;
  text-decoration: none;
  text-transform: uppercase;
}

.icon-close {
  cursor: pointer;
  padding-left: 10px;
  padding-top: 10px;
}

.icon-menu {
  color: #fff;
  cursor: pointer;
  font-family: 'Open Sans', sans-serif;
  font-size: 16px;
  padding-bottom: 25px;
  padding-left: 25px;
  padding-top: 25px;
  text-decoration: none;
  text-transform: uppercase;
}

.icon-menu i {
  margin-right: 5px;
}
h1 {
  top: 80px;
  position: absolute

}

Home

Gallery

About

Contact

Fullscreen to see the menu in the right form

A: Maybe something like this?
Javascript
var main = function() {
  $('.menu-item').hover(function() {
    var $el = $(this);
  $('.hover').animate({
      left: $el.offset().left - $('.menu').offset().left
  });
});

$('.hover').css({
    left: $('.menu-item:first').offset().left - $('.menu').offset().left
});
}

JSFIDDLE

A: Give all menu items the same class, then pass the offsetLeft of the event target (the menu item you are hovering over) into the animate call.
Updated Fiddle: http://jsfiddle.net/hbv63znv/7/

Home

Gallery

var main = function() {
    $('.menu-item').hover(function() {
      var that = this;
      $('.hover').animate({
          left: that.offsetLeft
      });
    });
}


text:
Q: Need SSIS Expression help for find keyword in filename I need help for below scenario.
I have file names like this
abc_assessment_20200303121212.csv
fgcdv_assessment_20200303121212.csv
xycv_assessment_20200303121212.csv

Now I need to right expression into SSIS package to identify files which contains "assessemnt" as keyword.
I used below expression but it didn't work
substring( @[User::FileName],1, FINDSTRING( @[User::FileName],"_",2)-1)=="assessment"

A: There is no debugging capability in the SSIS Expression language. Therefore, when you don't write a complex expression correctly the first time, it's an indicator you're doing too much in one step.
Let's break down your expression.
FINDSTRING
In the innermost operation, you are using findstring to find the position of the second underscore
FINDSTRING( @[User::FileName] ,"_",2)

If FileName is xycv_assessment_20200303121212.csv that would yield a value of 16.
How did I know this? I created a variable called SecondUnderscore and it is simply the Findstring operation.
SubString
Building on that, I create a second variable called SubString which uses the SecondUnderscore variable
substring( @[User::FileName],1, @[User::SecondUnderscore] -1)

I see quite clearly that my value is "xycv_assessment"
BooleanCheck
This operation compares the results of SubString to my sentinel value of assessment.
@[User::SubString] == "assessment"

It still yields a False as xycv_assessment is clearly not the same as assessment.
Final thoughts
String comparison is case sensitive so be aware that Assessment will not match assessmenT etc. The Lower() expression will help avoid that situation
If you need to find the pieces xycv vs asessment vs date string, then keep going this route but find the place of your first underscore and slice the pieces out.
Otherwise, take @Tyron78's example and just check for the presence of the string assessment. If findstring is greater than zero, it's in the file name.


text:
Q: Custom ID when registering Fitbit For my system, my users have their own unique ID (participant_id) that I've provided them.
I have a flask server that registers my users with Fitbit.
@app.route('/fitbit_authorize')
def homepage(): #probably need to send participant_id here
    return 'Authenticate with fitbit' % FITBIT_AUTHORIZATION_URL

Fitbit sends a post request regarding the successfulness of my participant registration to the following where I get their user access/refresh tokens for oauth:
@app.route('/fitbit_callback')
def fitbit_callback():
    error = request.args.get('error', '')
    if error:
        return "Error: " + error
    state = request.args.get('state', '')
    code = request.args.get('code')
    token = fitbit_access.get_full_token(code)

I was wondering how can I retrieve the authorizer's original ID (participant_id) in the callback. Is there anyway for me to pass additional information in the fitbit authorization process or what would be the best way for me to retrieve their participant_id?

A: Good question.
Oauth2 allows for you to include state information in the authorization request---You can include the participant_id in the state parameter: https://dev.fitbit.com/build/reference/web-api/oauth2/

state: Provides any state that might be useful to your application
  when the user is redirected back to your application. This parameter
  will be added to the redirect URI exactly as your application
  specifies. Fitbit strongly recommend including an anti-forgery token
  in this parameter and confirming its value in the redirect to mitigate
  against cross-site request forgery (CSRF).

In addition to providing the participant_id, you should provide an anti-forgery token to help fight CSRF.


text:
Q: Concatenate two strings using write() to stdout in C I'm trying to get two strings written to stdout character by character by two different processes, father and child, being the use of read() and write() compulsory, with the following code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

char buf1[100];
char buf2[100];
int i;

pid_t t;

int main()
{
    printf("String1:\n");
    read(0, buf1, 100);
    printf("String2:\n");
    read(0, buf2, 100);

    t = fork();

    if (t > 0) {
        wait(NULL);
        for (i = 0; i < strlen(buf2); i++) {
            write(1, &buf2[i], 1);
            sleep(1);
            }
        }
    else {
        for (i = 0; i < strlen(buf1); i++) {
            write(1, &buf1[i], 1);
            sleep(1);
            }
        exit(0);
        }
    return(0);
}

I manage to get two processes writing each one a single string to stdout, but I'm failing in merging those two strings into one. I've tried to use the ANSI Escape Codes to get the cursor ready for the second string where the first string ends, but how could I integrate them into the buffers inside write()?
Now, with the above mentioned code, I can obtain this output:
String1:
Hyper
String2:
loop
Hyper
loop

I'd like to obtain:
String1:
Hyper
String2:
loop
Hyperloop

Thank you in advance

A: @chux already addressed the main issue. Here is the corresponding working code with the following other changes:

*

*localized or eliminated variables

*added the missing includes to get this to compile on Linux

*replaced the write per character with a sleep with just a single write for the entire string

*guard against buffer overflow

*define LEN instead of inline magic values, also use STDOUT_FILENO

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

#define LEN 99
#define str(s) xstr(s)
#define xstr(s) #s

int main() {
    char buf1[LEN+1];
    char buf2[LEN+1];

    printf("String1:\n");
    scanf("%" str(LEN) "s", buf1);
    printf("String2:\n");
    scanf("%" str(LEN) "s", buf2);

    if (fork() > 0) {
        wait(NULL);
        write(STDOUT_FILENO, buf2, strlen(buf2));
    } else {
        write(STDOUT_FILENO, buf1, strlen(buf1));
        exit(0);
    }
    return(0);
}

and here is the output (note there is no newline after the last line):
String1:
Hyper
String2:
loop
Hyperloop

Not sure why you print a letter at a time, but the better alternative is just printf("%s", buf) (where but is either buf1 or buf2).

A: I think I've found a solution. The last byte read by read() or written by write() correspond to the newline. So writing all the bytes of the first buffer but one is crucial to get the results I want. In this way, the first buffer's for loop would be as follows:
for (i = 0; i < strlen(buf1)-1; i++) {
            write(1, &buf1[i], 1);
            sleep(1);
            }

And being the complete code like this:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

char buf1[100];
char buf2[100];
int i;

pid_t t;

int main()
{
    printf("String1:\n");
    read(0, buf1, 100);
    printf("String2:\n");
    read(0, buf2, 100);

    t = fork();

    if (t > 0) {
        wait(NULL);
        for (i = 0; i < strlen(buf2); i++) {
            write(1, &buf2[i], 1);
            sleep(1);
            }
        }
    else {
        for (i = 0; i < strlen(buf1)-1; i++) {
            write(1, &buf1[i], 1);
            sleep(1);
            }
        exit(0);
        }
    return(0);
}

Thanks a lot to the helpers!


text:
Q: How to paste a character with Microsoft Keyboard Macro system? I have a SideWinder X4 keyboard, and it supports the awesome Mouse and Keyboard Center app.
I write a lot of location-based text/code, and frequently have to open the Character Map app, find the degrees symbol ° , copy, and paste into whatever I'm doing.
How do I just make a macro to paste in this single character when I smash the appropriate key?

A: Thanks to @LPChip, I figured out
On your keyboard, press Alt + 0176.

Note: This method works only for keyboards that include a 10-key numeric pad.

So I set up the macro to press these keys.


text:
Q: Javascript "(index):87 Uncaught ReferenceError" Please help,
My javascript code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="~/Scripts/jquery-1.9.1.js"></script>

<script type="text/javascript">
    $(function() {
        var url = "../Account/DeconnecterUtilisateur";
        var statutLogin = @HttpContext.Current.User.Identity.Name;
        $.getJSON(url, { usr: id }, function (data) {
            console.log(data);
        })
    });
</script>

is throwing this error message

(index):87 Uncaught ReferenceError: patrice is not defined

And I can not get arround it.
My aim is to call within my account controller a method that will log off the user when ever that specifc view(that cobtains the script) is loaded.

A: Rewrite to this:
var statutLogin = '@HttpContext.Current.User.Identity.Name';

Notice you need the apostrophes above since c# is generating js code before the script runs.


text:
Q: How to stop slapd within Dockerfile? I try to build my own Docker container with slapd and Dockerfile.
Installation of slapd is OK and then I need to stop slapd in order to add a custom database.
For that I need to run slapadd command on a non running slapd. Nevertheless RUN pkill slapd produces the following error:
Step 7 : RUN service slapd start ; ldapadd -Y EXTERNAL -H ldapi:/// -f xxx.ldif
---> Using cache
---> 53e1e1a59517
Step 8 : RUN pkill slapd
---> Running in efc0058a4bfe
The command '/bin/sh -c pkill slapd' returned a non-zero code: 1

Do you know why and how I can stop properly slapd with Dockefile?

A: You are splitting your slapd operations over multiple RUN directives: that is not practical, as each RUN will create an intermediate container, and commit that container as an intermediate image.
It is best to group all your operation in one script, that you COPY first in your image, and then RUN that script.
That way, inside one intermediate container, you can start/stop slapd, add your ldif files, do other tests, before the intermediate container stops and is committed as a new intermediate image.


text:
Q: Navbar buttons are left aligned and stack on smaller resolutions I'm having some issues with my Navbar. It collapses on <768px but from 768 onwards it will do this stupid thing until it can fill the page properly:

I have tried entering nav-justified to the HTML but it just stacks each button.
Ideally I'm looking for any solution that doesn't look stupid, but unfortunately I need to leave every single link on this menu so even culling some isn't an option.
I think best bet would be to have it all center align so that if it has to stack it is at least in the middle.
Anyone else had this issue before?

A: Here are a few ways to solve this problem.
1) Reduce the font size
2) Utilize dropdown menus.
3) Add another (permanently exposed) bar for frequent/common links.
See working example.

.navbar.navbar-custom,
.navbar.navbar-custom2,
.navbar.navbar-custom3 {
  background: white;
  border-radius: 0;
  border: none;
  border-bottom: 3px solid red;
}
/**NAV One**/

.navbar.navbar-custom .navbar-nav > li > a {
  font-size: 12px;
}
/**NAV Three**/

.navbar-default.nav-top {
  background: white;
  border-top: 3px solid red;
}
.navbar-default.nav-top ul {
  display: inline-block;
  float: right;
}
.navbar-default .navbar-top li {
  float: left;
  font-size: 12px;
}
.navbar-default .navbar-top li a {
  color: #555;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-nv1" aria-expanded="false"> Toggle navigation

      </button> NAV 1

HOME

TRAINING

HEALTH

SAFETY

TRAINING CALENDAR

ABOUT

CONTACT

NAV One + Smaller Text

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-nv2" aria-expanded="false"> Toggle navigation

      </button> NAV 2

HOME

TRAINING CALENDAR

ABOUT

CONTACT

 SERVICES

TRAINING

HEALTH

SAFETY

NAV Two + Dropdown

ABOUT

CONTACT

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-nv3" aria-expanded="false"> Toggle navigation

      </button> NAV 3

HOME

TRAINING

HEALTH

SAFETY

TRAINING CALENDAR

NAV Three + Upper Links

A: Would it be as simple as changing the @media queries higher like maybe around 800-900? Then change it to dropdown menu as suggested by vanburenx?


text:
Q: can anyone help me with before '&' token error? In the below code
void tread(gonptr &head){

    int coefficient, exponent;

    scanf("%d",&n);

I'm having this kind of error when compiling

main.c:59:25: error: expected ';', ',' or ')' before '&' token
  void pwrite(PolyPointer &head){

can anyone help?

A: As per the code visible in the error message, you need to change
void pwrite(PolyPointer &head)

to
void pwrite(PolyPointer *head)

In C, there is no reference thing, it's all about pointers.
As pointed out by Mr. @zenith in the comments,the same is applicable for tread() also.
N.B : Code related to tread() function is irrelevant to this particular error message, anyway.


text:
Q: Fetching a variable from a group I am working with Ansible and I am trying to fetch a variable defined in a group like this in the inventory:

server1:
  host: www.server1.com

my_group:
 hosts:
   server1:
   server2:
 vars:
   var1: 100.100.1.1
   var2: abc

I tried fetching it like this in the playbook:
- hosts: localhost
  tasks:
  - name: netcat
    shell: nc -zv {{ hostvars['server1']['host'] }} {{ hostvars[item].var1 }}
    with_items: "{{ groups['my_group'] }}"

But it's not working.
How can I use this var var1?


text:
Q: Error while doing composer install/composer install --ignore-platform-reqs Problems come one by one, when one problem is solved new problems appear. I'm a novice programmer, I'm very confused with this error.
So when I finished the clone project, then I did

composer install --ignore-platform-reqs

Here an error appears.
At first appears a warning like this
Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Package operations: 122 installs, 0 updates, 0 removals
  - Downloading almasaeed2010/adminlte (v3.2.0)
  - Downloading laravel/pint (v1.5.0)
 0/2 [>---------------------------]   0%  - Downloading almasaeed2010/adminlte (v3.2.0)
  - Downloading laravel/pint (v1.5.0)
  - Downloading almasaeed2010/adminlte (v3.2.0)
//This is a warning// A connection timeout was encountered. If you intend to run Composer without connecting to the internet, run the command again prefixed with COMPOSER_DISABLE_NETWORK=1 to make Composer run in offline mode.
  - Downloading laravel/pint (v1.5.0)
  - Downloading almasaeed2010/adminlte (v3.2.0)
  - Downloading laravel/pint (v1.5.0)
//This is a warning// Failed to download almasaeed2010/adminlte from dist: curl error 28 while downloading https://codeload.github.com/ColorlibHQ/AdminLTE/legacy.zip/bd4d9c72931f1dd28601b6bfb387554a381ad540: Operation timed out after 300000 milliseconds with 2642368 out of 29084334 bytes received
    Now trying to download from source
  - Syncing almasaeed2010/adminlte (v3.2.0) into cache
 1/2 [==============>-------------]  50%    //This is a warning// Failed to download laravel/pint from dist: curl error 28 while downloading https://codeload.github.com/laravel/pint/legacy.zip/e0a8cef58b74662f27355be9cdea0e726bbac362: Operation timed out after 602688 milliseconds with 2614603 out of 12086799 bytes received
    Now trying to download from source

....
....
....
  - Installing almasaeed2010/adminlte (v3.2.0): Cloning bd4d9c7293
//This is a error// Install of almasaeed2010/adminlte failed
  - Installing jeroennoten/laravel-adminlte (v3.8.6): Extracting archive
  - Installing laravel/pint (v1.5.0): Cloning e0a8cef58b
//This is a warning// Install of laravel/pint failed
  - Installing symfony/yaml (v6.2.5): Extracting archive

And at the end an error message appears like this:
120/120 [============================] 100% //This is a error//The following exception is caused by a process timeout Check https://getcomposer.org/doc/06-config.md#process-timeout for details

In Process.php line 1204:

//This is a error//  The process "git clone --no-checkout -- https://github.com/ColorlibHQ/AdminLTE.git D:\Desktop\Beasiswa\pencairan\vendor\almasaeed2010\adminlte && cd /D D:\Desktop\Beasiswa\pencairan\vendor\almasaeed2010\adminlte && git remote add composer -- https://github.com/ColorlibHQ/AdminLTE.git && git fetch composer && git remote set-url origin -- https://github.com/ColorlibHQ/AdminLTE.git && git remote set-url composer -- https://github.com/ColorlibHQ/AdminLTE.git" exceeded the timeout of 300 seconds.

My composer.json
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^8.0.2",
        "guzzlehttp/guzzle": "^7.2",
        "jeroennoten/laravel-adminlte": "^3.8",
        "laravel/framework": "^9.19",
        "laravel/sanctum": "^3.0",
        "laravel/tinker": "^2.7",
        "laravel/ui": "^4.2"
    },
    "require-dev": {
        "barryvdh/laravel-ide-helper": "^2.12",
        "fakerphp/faker": "^1.9.1",
        "laravel/pint": "^1.0",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^6.1",
        "phpunit/phpunit": "^9.5.10",
        "spatie/laravel-ignition": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true,
        "allow-plugins": {
            "pestphp/pest-plugin": true
        }
    },
    "minimum-stability": "stable",
    "prefer-stable": true
}

Help,Where is the fault? And how to fix it. Thankyou!


text:
Q: How to simplify this code in VB.NET I have following code for 3 DataGridView Controls in my VB.NET winform application. How can I simplify this code?
    With DataGridView1
        .Columns.Add("Column 0", "TaskName")
        .AutoResizeColumns()
    End With

    With DataGridView2
        .Columns.Add("Column 0", "TaskName")
        .AutoResizeColumns()
    End With

    With DataGridView3
        .Columns.Add("Column 0", "TaskName")
        .AutoResizeColumns()
    End With

A: Apologies if this isn't valid VB.Net:
AddColumn(DataGridView1)
AddColumn(DataGridView2)
AddColumn(DataGridView3)

Private Sub AddColumn(ByVal dgv As DataGridView)
    dgv.Columns.Add("Column 0", "TaskName")
    dgv.AutoResizeColumns()
End Sub

A: You could;
For Each o As DataGridView In New DataGridView() {DataGridView1, DataGridView2, DataGridView3}
    o.Columns.Add("Column 0", "TaskName")
    o.AutoResizeColumns()
Next

A: Public NotInheritable Class GridViewHelper

Public Shared Function BuildDataGridView(view as DataGridView) as DataGridView
With View
    .Columns.Add("Column 0", "TaskName")
    .AutoResizeColumns()
End With
Return view
End Function

End Class

Of course, you can add TryCast() and so on to make sure the correct object is passed in etc.


text:
Q: saving username password in option.html and loading them automatically I have created 2 extensions for websites that i do not own and they do not have an api.
when you open the extension, there will be a login screen, but when you close it, you'll be logged out, i want to either save the cookies so when you reopen the extension you'll be logged in or to save the password like lastpass and create an option page, but:
1- I do not want to host the database on my vps, coz i don't want to pay to maintain the extension if i have many users, and i don't want to keep protecting my database from hackers till death :)
2- I do not want to host it on any paid service
unfortunately, lastpass doesn't have an api, so i'm thinking of storing the username and password on the user's pc, and i do not care if he got hacked because it is his responsibility to keep his pc secured and not mine :) any idea or tutorial on how to do it?
and by the way the websites are created using .net framework

A: You can store information between browser restarts in localStorage.


text:
Q: IPC Remoting problem We are receiving the following error using IPC.
"Failed to connect to an IPC Port: The system cannot find the file specified."
The issue is happening on a Windows 2003 server.
Of course it only happens in production.  We are unable to reproduce this in our development environment.
The Windows service that is attempting to use IPC is running as Local System.
Is there some sort of permission that needs to be changed?

A: We were attempting to access the channel before it was spun up.  So we would receive the 'not found' error.  Wrapping the access code in some 'is it really ready' code fixed the problem.

A: For me DTA was working fine. But Suddenly I started getting this same error.
For me the fix was this:
-> Go To Task Manager
-> Go To Processes Tab
-> Find and kill the DTA process. For me this process is named as 'DTASHELL.exe'

Now try to launch DTA. It should work now :-)

A: We had this problem in production code. It was failing on a small percentage of user's systems.
The error turns out to be in the microsoft code that we were using. It generates the IPC channel using the username.
ipc://APP_USER_000:SingeInstanceIPCChannel/SingleInstanceApplicationService
with certain characters in the username, this generates an invalid channel URL, so the receiving app fails to create the channel in the first place.
our fix is to use a hash of the username, rather than the first characters in the username.
(we were using the code here: http://blogs.microsoft.co.il/blogs/arik/archive/2010/05/28/wpf-single-instance-application.aspx )

A: Please post the code you use to initialize the server channel and publish the object, and the client code with the uri you use when you try to access the remote object.
A common pitfall is when you initialize the channel with a dictionary, and set the name of the channel using
dic["name"] = "channelName";
//used for retrieving the channel - ChannelServices.GetChannel("channelName");

instead of
dic["portName"] = "channelName";
//used as the identifier for the named pipe -
//The client should get the object from the uri : ipc://channelName/objectName


text:
Q: AdMod Set up I'm soooo close I just need a little assistance The app looks great but still no ads. I have 13 requests and 100% fill rate so I know its sending but I can't get any to show up. I redesigned the app and kept it simple a few divs and buttons. I'm hoping I just have something out of place or maybe you have a better (Still Simple) way of doing it. I need to get this working for 3 more apps. Your expertise is greatly appreciated thank you.
MANIFEST:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.appsclamation.wowmedesigns"
android:versionCode="1"
android:versionName="1.0" >
<meta-data android:value="true" android:name="ADMOB_ALLOW_LOCATION_FOR_ADS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="18" />

<application
android:label="@string/app_name" >
<activity
    android:name=".DefaultActivity"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 <activity
   android:name="com.google.ads.AdActivity"
  android:configChanges="keyboard|keyboardHidden|orientation|
  screenLayout|uiMode|screenSize|smallestScreenSize" />
  </application>
  </manifest>

MAIN:
   <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
 android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >

   <com.google.ads.AdView android:id="@+id/adView"
    ads:adUnitId="My_ID"
    ads:adSize="BANNER"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    ads:loadAdOnCreate="true"/>
   </LinearLayout>

Thanks in advance...
DefaultActivity: (Source Code?)
 package com.appsclamation.wowmedesigns;

import android.app.Activity;
import android.os.Bundle;
import com.phonegap.*;

public class DefaultActivity extends DroidGap
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.setIntegerProperty( "splashscreen", R.drawable.splash );
        super.loadUrl("file:///android_asset/www/index.html", 1000);
    }
}

I was under the impression that if you use the LoadonCreate in the MAIN you did not need to do anything else.

A: You just need to do this in your mainactivity:
Adview adView = (AdView) findViewById(R.id.adView);
        adView.loadAd(new AdRequest());

In your manifest:
<activity
            android:name="com.google.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />

In layout used in your mainactivity:
<com.google.ads.AdView
                android:id="@+id/adView"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                ads:adSize="SMART_BANNER"
                ads:adUnitId="@string/ADMOB_PublisherId"
                ads:loadAdOnCreate="true" />

where ADMOB_PublisherId would be your ID generated after registering your application


text:
Q: python argument with or without value, specified or not Scenario is as follows:
I need to implement a command line argument system that allows both
-p <value>
and
-p
(no value for -p given)
Is there any way to achieve this using argparse, or will I have to manually parse sys.argv?
Thank u so much!!!

A: This will set args.param to None when the option is not specified (or specified without parameter) and to the specified value otherwise
import argparse

UNSPECIFIED = object()

parser = argparse.ArgumentParser()
parser.add_argument('-p', action='store', dest='param', default=UNSPECIFIED, nargs='?')

args = parser.parse_args()

if args.param == UNSPECIFIED:
    print("Param unspecified")
else:
    print(args.param)

A: What you need is three states,   absent, present, present with value.
The argparse module provides at least two simple ways to do this.
For the simplest, and most flexible, you only need add action='store' and nargs='*'.
#!/usr/bin/python

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-p', action='store', nargs='*')

args = parser.parse_args()

if args.p is not None:
    print( '-p present' )
else:
    print( '-p not present' )

print( '-p value', args.p )

Here is your output for this method:
# ./testpar.py
-p not present
-p value None

# ./testpar.py -p
-p present
-p value []

# ./testpar.py -p something
-p present
-p value ['something']

# ./testpar.py -p something anotherthing
-p present
-p value ['something', 'anotherthing']

For the second method, you can set a specific value for the second of the three states, const=somevalue and nargs='?'.   This method supports one value only, and the value for 'const' has to be something that would not be a valid input by the user.
#!/usr/bin/python

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-p', action='store', const='NoValue', nargs='?')

args = parser.parse_args()

if args.p:
    print( '-p present' )
else:
    print( '-p not present' )

print( '-p value', args.p )

And here is your output for the three cases,
# ./testpar.py
-p not present
-p value None

# ./testpar.py -p
-p present
-p value NoValue

# ./testpar.py -p something
-p present
-p value something


text:
Q: SUDS fails in GUI, but works in unittest I have a weird problem with SUDS in python.
I am writing an application, that uses a SOAP service. And for approximately 2 months everything was going fine. All of a sudden, it stopped working. Here is the weird part though.
If I run the unittest for the suds manager I wrote, everything goes well and the test passes like usual. If I run the code in the GUI application it fails, with the following traceback:
ERROR:suds.client:<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://service.skip.fiskistofa.is/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <ns1:Body>
      <ns0:getLandings>
         <from>2013-10-11</from>
         <to>2013-10-01</to>
      </ns0:getLandings>
   </ns1:Body>
</SOAP-ENV:Envelope>
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 808, in __bootstrap_inner
    self.run()
  File "/home/fintor/bin/python/aflafrettir/gui/gui.py", line 332, in run
    landings = self.manager.get_landings(self.date_from, self.date_to)
  File "/home/fintor/bin/python/aflafrettir/landings/manager.py", line 66, in get_landings
    return self.call_method('getLandings', date_from, date_to)
  File "/home/fintor/bin/python/aflafrettir/landings/manager.py", line 49, in call_method
    return getattr(self.client.service, method)(*args)
  File "/home/fintor/.virtenvs/aflafrettir/lib/python2.7/site-packages/suds/client.py", line 542, in __call__
    return client.invoke(args, kwargs)
  File "/home/fintor/.virtenvs/aflafrettir/lib/python2.7/site-packages/suds/client.py", line 602, in invoke
    result = self.send(soapenv)
  File "/home/fintor/.virtenvs/aflafrettir/lib/python2.7/site-packages/suds/client.py", line 649, in send
    result = self.failed(binding, e)
  File "/home/fintor/.virtenvs/aflafrettir/lib/python2.7/site-packages/suds/client.py", line 702, in failed
    r, p = binding.get_fault(reply)
  File "/home/fintor/.virtenvs/aflafrettir/lib/python2.7/site-packages/suds/bindings/binding.py", line 265, in get_fault
    raise WebFault(p, faultroot)
WebFault: Server raised fault: 'Couldn't create SOAP message due to exception: XML reader error: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character 'C' (code 67) in prolog; expected '<'
 at [row,col {unknown-source}]: [1,1]'

The code that fails, is running in a thread within the GUI application(PySide), the relevant code is here:
class Worker(Thread):
  signal = AflafrettirSignal()

  def __init__(self, queue, manager, date_from, date_to):
    super(Worker, self).__init__()
    self.queue = queue
    self.manager = manager
    self.date_from = date_from
    self.date_to = date_to
    self.daemon = True

  def run(self):
    landings = self.manager.get_landings(self.date_from, self.date_to)

    for l in landings:
      tmp = Landings()
      tmp.set_variable(l)
      tmp.calc_total_catch()
      self.queue.put(tmp)

    self.signal.work_done.emit(True)

and it's called in the gui like so:
manager = LandingsManager()
manager.set_credentials(self.username, self.password)
manager.get_client()
worker = Worker(self.queue, manager, date_from, date_to)
worker.start()

Finally, here is the code from the unittest module, which is working fine:
manager = LandingsManager()
manager.set_credentials(usern, passw)
manager.get_client()
data = manager.get_landings('2013-10-01', '2013-10-11')

I have verified that the username and password is the same when I set the credentials as well as the date from and date to when I call the get_landings method.
Like I said, it is a weird problem, and I am not sure what causes this to fail in one place, and work in another. I hope that someone can enlighten me regarding the cause.
EDIT:
I figured out what was wrong. The password contained a carriage return, and the SOAP service did not like that.


text:
Q: Remove a layer from a ggplot2 chart I'd like to remove a layer (in this case the results of geom_ribbon) from a ggplot2 created grid object. Is there a way I can remove it once it's already part of the object?
library(ggplot2)
dat <- data.frame(x=1:3, y=1:3, ymin=0:2, ymax=2:4)
p <- ggplot(dat, aes(x=x, y=y)) + geom_ribbon(aes(ymin=ymin, ymax=ymax), alpha=0.3)
     + geom_line()

# This has the geom_ribbon
p

# This overlays another ribbon on top
p + geom_ribbon(aes(ymin=ymin, ymax=ymax, fill=NA))

I'd like this functionality to allow me to build more complicated plots on top of less complicated ones. I am using functions that return a grid object and then printing out the final plot once it is fully assembled. The base plot has a single line with a corresponding error bar (geom_ribbon) surrounding it. The more complicated plot will have several lines and the multiple overlapping geom_ribbon objects are distracting. I'd like to remove them from the plots with multiple lines. Additionally, I'll be able to quickly create alternative versions using facets or other ggplot2 functionality.

Edit: Accepting @mnel's answer as it works. Now I need to determine how to dynamically access the geom_ribbon layer, which is captured in the SO question here.

Edit 2: For completeness, this is the function I created to solve this problem:
remove_geom <- function(ggplot2_object, geom_type) {
  layers <- lapply(ggplot2_object$layers, function(x) if(x$geom$objname == geom_type) NULL else x)
  layers <- layers[!sapply(layers, is.null)]

  ggplot2_object$layers <- layers
  ggplot2_object
}

Edit 3: See the accepted answer below for the latest versions of ggplot (>=2.x.y)

A: As this problem looked interesting, I have expanded my 'ggpmisc' package with functions to manipulate the layers in a ggplot object (currently in package 'gginnards'). The functions are more polished versions of the example in my earlier answer to this same question. However, be aware that in most cases this is not the best way of working as it violates the Grammar of Graphics. In most cases one can assemble different variations of the same figure in the normal way with operator +, possibly "packaging" groups of layers into lists to have combined building blocks that can simplify the assembly of complex figures. Exceptionally we may want to edit an existing plot or a plot output by a higher level function that whose definition we cannot modify. In such cases these layer manipulation functions can be useful. The example above becomes.
library(gginnards)
p1 <- delete_layers(p, match_type = "GeomText")

See the documentation of the package for other examples, and for information on the companion functions useful for modifying the ordering of layers, and for inserting new layers at arbitrary positions.

A: @Kamil Slowikowski Thanks! Very useful. However I could not stop myself from creating a new variation on the same theme... hopefully easier to understand than that in the original post or the updated version by Kamil, also avoiding some assignments.
remove_geoms <- function(x, geom_type) {
  # Find layers that match the requested type.
  selector <- sapply(x$layers,
                     function(y) {
                       class(y$geom)[1] == geom_type
                     })
  # Delete the layers.
  x$layers[selector] <- NULL
  x
}

This version is functionally identical to Kamil's function, so the usage example above does not need to be repeated here.
As an aside, this function can be easily adapted to select the layers based on the class of the stat instead of the class of the geom.
remove_stats <- function(x, stat_type) {
  # Find layers that match the requested type.
  selector <- sapply(x$layers,
                     function(y) {
                       class(y$stat)[1] == stat_type
                     })
  # Delete the layers.
  x$layers[selector] <- NULL
  x
}

A: @Kamil and @Pedro Thanks a lot! For those interested, one can also augment Pedro's function to select only specific layers, as shown here with a last_only argument:
remove_geoms <- function(x, geom_type, last_only = T) {
  # Find layers that match the requested type.
  selector <- sapply(x$layers,
                     function(y) {
                       class(y$geom)[1] == geom_type
                     })
  if(last_only)
    selector <- max(which(selector))
  # Delete the layers.
  x$layers[selector] <- NULL
  x
}

Coming back to @Kamil's example plot:
set.seed(3000)
d <- data.frame(
  x = runif(10),
  y = runif(10),
  label = sprintf("label%s", 1:10)
)

p <- ggplot(d, aes(x, y, label = label)) + geom_point() + geom_point(color = "green") + geom_point(size = 5, color = "red")

p

p %>% remove_geoms("GeomPoint")

p %>% remove_geoms("GeomPoint")  %>% remove_geoms("GeomPoint")

A: For ggplot2 version 2.2.1, I had to modify the proposed remove_geom function like this:
remove_geom <- function(ggplot2_object, geom_type) {
  # Delete layers that match the requested type.
  layers <- lapply(ggplot2_object$layers, function(x) {
    if (class(x$geom)[1] == geom_type) {
      NULL
    } else {
      x
    }
  })
  # Delete the unwanted layers.
  layers <- layers[!sapply(layers, is.null)]
  ggplot2_object$layers <- layers
  ggplot2_object
}

Here's an example of how to use it:
library(ggplot2)

set.seed(3000)
d <- data.frame(
  x = runif(10),
  y = runif(10),
  label = sprintf("label%s", 1:10)
)

p <- ggplot(d, aes(x, y, label = label)) + geom_point() + geom_text()

Let's show the original plot:
p

Now let's remove the labels and show the plot again:
p <- remove_geom(p, "GeomText")
p

A: If you look at
p$layers
[[1]]
mapping: ymin = ymin, ymax = ymax
geom_ribbon: na.rm = FALSE, alpha = 0.3
stat_identity:
position_identity: (width = NULL, height = NULL)

[[2]]
geom_line:
stat_identity:
position_identity: (width = NULL, height = NULL)

You will see that you want to remove the first layer
You can do this by redefining the layers as just the second component in the list.
p$layer <- p$layer[2]

Now build and plot p
p

Note that p$layer[[1]] <- NULL would work as well. I agree with @Andrie and @Joran's comments regarding in wehat cases this might be useful, and would not expect this to be necessarily reliable.


text:
Q: edit django form widget rendering I have a Django form where one of the fields is defined as:
widgets = {
    'name': forms.CheckboxSelectMultiple()
}

The template renders them in a loop with:
{% for field in form %}
    <fieldset class="article-form__field">
        {{ field.label_tag }} {{ field }}
    </fieldset>
{% endfor %}

This is rendered as:
<fieldset class="article-form__field">
    Category:

<input id="category-name_0" name="category-name" type="checkbox" value="GEN" /> General information

<input id="category-name_1" name="category-name" type="checkbox" value="FOO" /> Food and drinks

</fieldset>

In short: <input>. However, I would like the output to be <input>.
Is that possible, and if so, how?
Full code is here.

A: {% for field in form %}
    <fieldset class="article-form__field">
    {% if field.name != "category-name" %}
        {{ field.label_tag }} {{ field }}
    {% else %}
        {{ field.label_tag }}

        {% for checkbox in field %}

                    {{ checkbox.choice_label }}

                {{ checkbox.tag }}

        {% endfor %}

    {% endif %}
    </fieldset>
{% endfor %}

*

*CheckboxSelectMultiple

*RadioSelect (how to customize rendering is described here)


text:
Q: GPT 2 - TypeError: Cannot cast array data from dtype('O') to dtype('int64') according to the rule 'safe' I am working with gpt2, python 3.9 and tensorflow 2.5 and when connecting to flask (flask run in terminal) I get a following message:

TypeError: Cannot cast array data from dtype('O') to dtype('int64') according to the rule 'safe'

Here is the code in generator.py
#!/usr/bin/env python3

import fire
import json
import os
import numpy as np
import tensorflow.compat.v1 as tf

# import model, sample, encoder
  from text_generator import model
  from text_generator import sample
  from text_generator import encoder

class AI:
 def generate_text(self, input_text):
    model_name = '117M_Trained'
    seed = None,
    nsamples = 1
    batch_size = 1
    length = 150
    temperature = 1
    top_k = 40
    top_p = 1
    models_dir = 'models'
    self.response = ''

    models_dir = os.path.expanduser(os.path.expandvars(models_dir))
    if batch_size is None:
        batch_size = 1
    assert nsamples % batch_size == 0

    enc = encoder.get_encoder(model_name, models_dir)
    hparams = model.default_hparams()
    cur_path = os.path.dirname(__file__) + '/models' + '/' + model_name
    with open(cur_path + '/hparams.json') as f:
        hparams.override_from_dict(json.load(f))

    if length is None:
        length = hparams.n_ctx // 2
    elif length > hparams.n_ctx:
        raise ValueError("Can't get samples longer than window size: %s" % hparams.n_ctx)

    with tf.Session(graph=tf.Graph()) as sess:
        context = tf.placeholder(tf.int32, [batch_size, None])
        np.random.seed(seed)
        tf.set_random_seed(seed)
        output = sample.sample_sequence(
            hparams=hparams, length=length,
            context=context,
            batch_size=batch_size,
            temperature=temperature, top_k=top_k, top_p=top_p
        )

        saver = tf.train.Saver()
        ckpt = tf.train.latest_checkpoint(cur_path)
        saver.restore(sess, ckpt)

        context_tokens = enc.encode(input_text)
        generated = 0
        for _ in range(nsamples // batch_size):
            out = sess.run(output, feed_dict={
                context: [context_tokens for _ in range(batch_size)]
            })[:, len(context_tokens):]
            for i in range(batch_size):
                generated += 1
                text = enc.decode(out[i])
                self.response = text

    return self.response

  ai = AI()
  text = ai.generate_text('How are you?')
  print(text)

Any help is appreciated  ps I have also added below the entire traceback
     * Serving Flask app 'text_generator' (lazy loading)
 * Environment: development
 * Debug mode: on
2021-09-14 19:58:08.687907: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Traceback (most recent call last):
  File "_mt19937.pyx", line 178, in numpy.random._mt19937.MT19937._legacy_seeding
TypeError: 'tuple' object cannot be interpreted as an integer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/dusandev/miniconda3/bin/flask", line 8, in <module>
    sys.exit(main())
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 990, in main
    cli.main(args=sys.argv[1:])
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 596, in main
    return super().main(*args, **kwargs)
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/core.py", line 1062, in main
    rv = self.invoke(ctx)
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/core.py", line 1668, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/click/core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 845, in run_command
    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 321, in __init__
    self._load_unlocked()
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 346, in _load_unlocked
    self._app = rv = self.loader()
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 402, in load_app
    app = locate_app(self, import_name, name)
  File "/Users/dusandev/miniconda3/lib/python3.9/site-packages/flask/cli.py", line 256, in locate_app
    __import__(module_name)
  File "/Users/dusandev/Desktop/AI/text_generator/__init__.py", line 2, in <module>
    from .routes import generator
  File "/Users/dusandev/Desktop/AI/text_generator/routes.py", line 2, in <module>
    from .generator import ai
  File "/Users/dusandev/Desktop/AI/text_generator/generator.py", line 74, in <module>
    text = ai.generate_text('How are you?')
  File "/Users/dusandev/Desktop/AI/text_generator/generator.py", line 46, in generate_text
    np.random.seed(seed)
  File "mtrand.pyx", line 244, in numpy.random.mtrand.RandomState.seed
  File "_mt19937.pyx", line 166, in numpy.random._mt19937.MT19937._legacy_seeding
  File "_mt19937.pyx", line 186, in numpy.random._mt19937.MT19937._legacy_seeding
TypeError: Cannot cast array data from dtype('O') to dtype('int64') according to the rule 'safe'

A: The problem is the line None, in your code. This is causing the tuple (None,) as the input to the np.random.seed(seed). It accepts integer, but you are sending the tuple.


text:
Q: Automatically putting selected people in a group on a course in moodle I'm new to moodle and VBA in excel which made me wonder if I could use my list in excel to select people for groups on a course automatically since there are a lot of courses to get through.

A: Yes, you can use "Upload users" tool in Moodle to upload csv file that places users into groups.
What you need is a csv file with columns (for example)
username,course1,group1
And then upload it in the "upload users" and select "Update existing users only".
This is very powerful tool and can be used for lots of different bulk actions on users.
You can find examples in https://docs.moodle.org/30/en/Upload_users


text:
Q: converting js into react autocomplete search input form quite new to this react thing but i previously wrote a simple js script for my own search input for autocomplete
$(function () {
    $("#search_item").autocomplete({
        minLength: 1,
        source: function (req, resp) {
            var collected;
            $.getJSON("https://api.test.com/items/autocomplete?q=" + req.term, function (json) {
                console.log(json);
                resp(json.data);
            })
        }
    });
});

html
 <form action="/api/search">

                    <input id="search_item" type="text" class="form-control" placeholder="Search for..." name="item_search_keyword">

                        <button class="btn btn-secondary" type="submit" id="btnSubmit">Search!</button>

            </form>

trying to convert this into React with a simple input search bar but not so familiar with React. Possible if anyone can give me some help?

A: I think the best answer to this is that you need to convert your mind to React first, before converting the code.
It is not just a small change to migrate code like that to React. React follows a fundamentally different approach, which is not compatible with your example. E.g. you should not touch the DOM directly.
Imagine you are not writing javascript / DOM anymore, but you are writing a different language (i.e. React) now.
As a vague direction for a solution: I guess you would create a React component like <MyInputWithAutoComplete>, which returns e.g. your input-group, and handles your autocomplete logic with a useEffect.


text:
Q: Google Maps API - Geocoding + Heatmap I am trying to build an app where I can insert an array with postcodes, do a geocoding API process (which works) in order to transform the postcodes into long/lat, and then create a heatmap using those long/lat combinations (which doesn't work). I have used the following code:
<!DOCTYPE html>

    <title>Heatmap</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

      <input id="address" type="textbox" value="Sydney, NSW">
      <input id="submit" type="button" value="Geocode">

Ideal result: The array of postcodes would be used to create a heatmap.
EDIT:
I have managed to fix the errors in the console but now it is still not showing the heatmap on the map.

A: There are a couple issues here:

*

*The requests to geocode the points happen asynchronously. Because of this, the heat map needs to be added after all points have been geocoded. One way to do this is to check if the length of heatmapData is equal to the length of the array of addresses. So in the callback of geocoder.geocode(), add this check:
} else {
  alert('Geocode was not successful for the following reason: ' + status);
}
if (heatmapData.length == listAddress.length ) {
  //call heatmap() here
  heatmap()
}

*The variable map is visible within the scope of initMap(), so when the code in function heatMap() adds the heatmap, it can't resolve map. To avoid that issue, declare map before outside of function initMap(). See the example below:
var map, heatmapData = [];
function initMap() {
    map = map = new google.maps.Map(document.getElementById('map'), {
 // ...
}
function heatMap() {
    //map and heatmapData are now visible
}

See these changes demonstrated in this plunker.


text:
Q: Weaker version of Well-Ordering principle?
Given a set $S$, I want to find a total antisymmetric relation $R$ on $S$:

$\forall i,j\in S$ either $iRj$ or $jRi$ or both.
In the case both, we have $i=j$, therefore any two distinct elements of $S$ have a fixed direction.
The Axiom of Choice/Well-Ordering Principle can work it out. But this is so muck weaker than AC/WO. So I am wondering if this is gonna work in ZF-system.

A: This would imply a statement which is probably close in strength to the full Axiom of Choice.  That would be what we think of informally as the "choice of one sock from each pair in an infinite drawer": given a collection of sets $\{ A_\lambda : \lambda \in \Lambda \}$ such that $|A_\lambda| = 2$ for each $\lambda$, then by the assumption that your statement is true, find a total antisymmetric relation on $\bigcup_{\lambda \in \Lambda} A_\lambda$.  Then, for each $\lambda$, we can choose the element of $A_\lambda$ which is smaller than the other in this order, and thus construct a choice function for $(A_\lambda)_{\lambda \in \Lambda}$.
Actually, a very similar argument will work in the more general case that each $A_\lambda$ is a finite set, if you strengthen the statement to assert the existence of a total order on every set (i.e. a partial order which also satisfies the given condition of being total antisymmetric).


text:
Q: How to group route of journey (Set cover problem) I have this issue need to solve:
Input:

*

*List of route between city, all route will start from same origin

*Set of all city

Output:

*

*Group of path that can visit all city, if not found then return group cover the most of city with minimum of route.

Example:
Testcase 1:
Input

*

*Route List:
1.Newyork -> Washington -> Los Angeles -> Chicago
2.Newyork -> Houston -> Alaska
3.Newyork -> Dallas
4.Newyork -> Houston -> Washington -> Chicago -> Los Angeles -> Alaska
5.Newyork -> Alaska
6.Newyork -> Chicago
7.Newyork -> Los Angeles

*City: Newyork, Washington, Los Angeles, Chicago, Alaska, Dallas, Houston
Output:
1.Newyork -> Houston -> Washington -> Chicago -> Los Angeles -> Alaska
2.Newyork -> Dallas
This is best group because with only 2 route it can visit all given cities
Testcase 2:
Input

*

*Route List:
1.Newyork -> Washington -> Los Angeles -> Chicago
2.Newyork -> Houston -> Alaska
3.Newyork -> Dallas
4.Newyork -> Alaska
5.Newyork -> Chicago
6.Newyork -> Los Angeles

*City: Newyork, Washington, Los Angeles, Chicago, Alaska, Dallas, Houston
Output:
1.Newyork -> Washington -> Los Angeles -> Chicago
2.Newyork -> Houston -> Alaska
3.Newyork -> Dallas
This is best group because with 3 routes it can visit all given cities
Testcase 3:
Input

*

*Route List:
2.Newyork -> Houston -> Alaska
3.Newyork -> Dallas
4.Newyork -> Alaska
5.Newyork -> Chicago
6.Newyork -> Los Angeles

*City: Newyork, Washington, Los Angeles, Chicago, Alaska, Dallas, Houston
Output:
1.Newyork -> Houston -> Alaska
2.Newyork -> Chicago
3.Newyork -> Dallas
4.Newyork -> Los Angeles
This is best group because with 4 routes it can visit 6/7 cities (except Washington)
implementation
public static void main(String[] args){
    List<List<String>> allRoutes = new ArrayList<>();
    allRoutes.add(List.of("Newyork","Washington","Los Angeles","Chicago"));
    allRoutes.add(List.of("Newyork","Houston","Alaska"));
    allRoutes.add(List.of("Newyork","Dallas"));
    allRoutes.add(List.of("Newyork","Houston","Washington","Chicago","Los Angeles","Alaska"));
    allRoutes.add(List.of("Newyork","Alaska"));
    allRoutes.add(List.of("Newyork","Chicago"));
    allRoutes.add(List.of("Newyork","Los Angeles"));
    Set<String> cities = new HashSet<>(List.of("Newyork","Houston","Washington","Chicago","Los Angeles","Alaska"));

    List<List<String>> result = findBestRoute(allRoutes, cities);
    //expected allPaths:
    //`Newyork -> Houston -> Washington -> Chicago -> Los Angeles -> Alaska`\
    //`Newyork -> Dallas`

  }

private static void findBestRoute(List<List<String>> allRoutes, Set<String> cities){
   //implementation
}

So any advice for algorithm i can use?


text:
Q: Is there a way to stop moving forward while aiming? I'm playing Assassin's Creed Origins on PS4 and every time I aim with the bow my character starts moving forward. I don't push the analog forward and to counter act this I need to run backwards against the forward movement. Am I doing something wrong or is it a setting that I'm missing?

A: The problem is the controller's left stick is slightly worn, and due to the sensitivity while aiming the slight forward position of the controller's left stick results in you moving forward. I verified this by switching controllers. Try cleaning your controller, or you may need to replace it.

A: It's on the defaults aim (free aim) so that's why it's not making your Character. It's happend to me it's nothing to to with controllers it's the settings i have 2 of them and both brand new so its not worn out


text:
Q: Object literal may only specify known properties, and ''app-id'' does not exist in type 'Headers' Below is my code to get data from remote server.
import * as React from 'react';
import { useEffect, useState } from 'react';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import TextField from '@mui/material/TextField';
import { styled } from '@mui/material/styles';

const URL = process.env.REACT_APP_URL;
const API = process.env.REACT_APP_API;
const APPID = process.env.REACT_APP_APPID;

const PageTitle = styled(Typography)({
    fontSize: '30px',
    marginBottom: '20px',
});

const SearchField = styled(TextField)({
    width: '100%',
});

export default function Search() {
    const [filterableData, setfilterableData] = useState();

    useEffect(() => {
        async function fetchData() {
            const response = await fetch(`${URL}${API}`, {
                method: 'GET',
                headers: {
                    'app-id': APPID,
                },
            });         const data = await response.json();
            console.log(data);
        }
        fetchData();
    });

    const search = (event) => {
        console.log(event.target.value);
    };

    return (
        <Container maxWidth="lg">
            <PageTitle>Search</PageTitle>
            <SearchField
                id="outlined-search"
                label="Enter search query"
                type="search"
                onChange={search}
            />
        </Container>
    );
}

It throws below error.
Type '{ 'app-id': string | undefined; }' is not assignable to type 'HeadersInit | undefined'.
  Type '{ 'app-id': string | undefined; }' is not assignable to type 'undefined'.  TS2322

    26 |            const response = await fetch(`${URL}${API}`, {
    27 |                method: 'GET',
  > 28 |                headers: {
       |                ^
    29 |                    'app-id': APPID,
    30 |                },
    31 |            });

Searched over the internet and the solutions I got was related to making interface etc. But none of those solutions worked for me. Any idea how to solve this?

A: You should try to use Headers class

const headers = new Headers();
if(APPID) {
  headers.set('app-ip', APPID);
}

async function fetchData() {
  const response = await fetch(`${URL}${API}`, {
    method: 'GET',
    headers
});

A: headers: {
  'app-id': APPID as string,
},

above solved my problem.

A: It seems a bug in lib.dom.d.ts, but you still have some choices to figure it out.

*

*Type assertion.

    fetch({
        headers: {'app-id': APPID} as Headers
    })

*

*Ignore it.

    fetch({
      // @ts-ignore
      headers: {'app-id': APPID}
    })

*

*Use Headers Api.
fetch({
    headers: new Headers({'app-id': APPID})
  })

if you want to make older browsers compatible, you should import a Headers polyfill first.
Note that code below has not been tested.
  (function(){
    if(typeof Headers !== 'function') {
      window.Headers = function(headers: Record<string, string>){return headers}
    }
  })()

For the solutions listed above, I recommend type assertions the most.

A: the issue is that APPID can be undefined as this is an enviroment variable. You should test is is not undefined or force it using  ! if you are sure it is defined (i.e. tested before the function is called)
const url = process.env.REACT_APP_URL;
const API = process.env.REACT_APP_API;
const APPID = process.env.REACT_APP_APPID;

async function fetchData():Promise<void> {
  const response = await fetch(`${url}${API}`, {
      method: 'GET',
      headers: {
          'app-id': APPID ?APPID:"", // or 'app_id':APPID!
      },
  });         const data = await response.json();
  console.log(data);
}
fetchData();


text:
Q: 2 list overlaping when they are placed horizontally with scroll=false I have 2 list i want to display it horizontally i used height 10 % for both the lists allowing it to hide rest of the content of the lists.
By Doing scroll=false for the lists and by using layout='vbox' for the parent layout both the lists are overlapped in  such case what should i do?
thanks Raj

A: First you have to add these lists as an item panel and set height to those panels.
ie
var panel1= new Ext.Panel({
layout:'fit',
height:'10%',
items:[list1]
});

var panel2= new Ext.Panel({
layout:'fit',
height:'10%',
items:[list2]
});

Then add these panels to your main panel with vbox layout.


text:
Q: How to use derived class shared variables in shared methods of base class I am trying to add shared members in derived classes and use that values in base classes...
I have base
class DBLayer
    public shared function GetDetail(byval UIN as integer)
    dim StrSql = string.format("select * from {0} where uin = {1}", tablename, uin)
    ....
    end function
end class

my derived class
class User inherits dblayer
    public shared tabledname as string = "users"
end class

class item inherits dblayer
    public shared tabledname as string = "item"
end class

class category inherits dblayer
    public shared tabledname as string = "category"
end class

Currently there is an error using the tablename variable of a derived class in my base class.

A: I'd create
Protected MustInherit Readonly Property TableName as string

in the base class. And then each of the child classes would need to override it and return the correct name from the property.
So in one of the child classes it would be:
Protected OverRides Readonly Property TableName as string
   Get
       Return "users" ' or category or item etc
   End Get
End Property

A: Class User
    Inherits DBLayer
    Public Shared Shadows Function TableName() As String
        Return "users"
    End Function
    Public Overrides Function GetTableName() As String
        Return User.TableName
    End Function
End Class

MustInherit Class DBLayer
    MustOverride Function GetTableName() As String

    Public Function GetDetail(ByVal UIN As Integer)
        Return GetDetail(UIN, GetTableName)
    End Function

    Public Shared Function GetDetail(ByVal UIN As Integer, ByVal TableName As String)
        Dim StrSql As String = String.Format("select * from {0} where uin = {1}", TableName, UIN)
        Return StrSql
    End Function

End Class

Class DBLayer

    Private _tableName As String
    Public Property TableName() As String
        Get
            Return _tableName
        End Get
        Set(ByVal value As String)
            _tableName = value
        End Set
    End Property

    Public Sub New(ByVal tableName As String)
        _tableName = tableName
    End Sub
    Public Function GetDetail(ByVal UIN As Integer)
        Return GetDetail(UIN, Me.TableName)
    End Function

    Public Shared Function GetDetail(ByVal UIN As Integer, ByVal TableName As String)
        Dim StrSql As String = String.Format("select * from {0} where uin = {1}", TableName, UIN)
    End Function

End Class


text:
Q: Recursively hydrate all related objects in Propel Is there a simple way to recursively hydrate all related objects when performing a query?
Let's say I have the following tables:
Song
Composer
Century

When I do a SongPeer::doSelectJoinAll() only the related composers are hydrated, so if I then do something like $song->getComposer()->getCentury(), a new query will be performed.
I want to perform only one query to the DB so when I call $song->getComposer()->getCentury() within a loop on all my songs objects, it doesn't end up in n additional queries.
Hope I'm clear :)
Thanks

A: Are you using Propel 1.2 ? The one with creole ?
If so, try to implement your own doSelectJoinAll on SongPeer to manually add join on other table (like century).
If you are using the latest version, you just have to explicit joinWith the table in your query:
<?php
$song = SongQuery::create()
  ->joinWith('Song.Composer')
  ->joinWith('Composer.Century');
$century = $song->getComposer()->getCentury();


text:
Q: Cropping the SSIS Designer view In a SQL Server Integration Services project, the designer view has created a large amount of unused space above the space I'm actually using. Notice the size of the right scrollbar in the following zoomed out view.

When starting the project, the designer's view always starts in the upper left corner, meaning I have to scroll to the bottom to see any of my work. Is there any way to clip the designer's working space to what I'm actually using? I've verified there is absolutely nothing above the containers here.

A: Click on the Fit to Window view (the square-ish box at the bottom of the slider). Then select all your tasks. Drag all of them together to the left-top corner. After sometime, enlarge the view to 100% (the dark line on the slider). Do it couple times till you have what you want.

A: Format -> Auto Layout -> Diagram
This will Auto size your boxes and bring them back to top left. Doing it manually is annoying and almost impossible.

A: Select all controls and cut it. Click Fit View on Windows bottom right corner. It will resize. Then paste your control back.


text:
Q: About views in CodeIgniter I am just on the beginning to learn CodeIgniter, I have one controller named home.php and I have 2 views named photo.php and body.php and I want to call the first view in the other. and finally calling body.php on acceuil.php.
How can I do this?

A: In the first view page ie in body.php you just write
$this->load->view('photo.php');

A: you can do it like this
in your first view body.php
$ci =& get_instance();//you have to do this because you are in output library
$ci->load->view('photo.php');

A: You can also load the parent view and pass the child view as a parameter like this
$childview = $this->load->view('childview.php');
$this->load->view('parentview.php', array('childview' => $childview))

and than in parentview.php you just need to echo the variable $childview.

A: In your body.php view
$this->load->view($content);
Here you can put whatever bod content

And in your controller
$data['content']='views/photo.php';
$this->load->view('body.php',$data);

Above method good for complex view structures like seperate header,footer and body files.But for your one can just do this way as well.
In your body.php
$this->load->view('photo.php');

And in your controller just load
$this->load->view('body.php');


text:
Q: How to test add method in Kotlin object Singleton class I'm trying to do some testing in my object kotlin class, but I can getting an error in my thenReturn method when I try to pass the object. I get a Require: Unit! Found checkout. Someone can point me how is possible to test it??
If I remove thenReturn method I get this error:
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, which is not supported
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

I refer this link but I can't get it.
object CheckoutRepository: CheckoutContract.Model {

    var checkout: MutableList<Checkout> = mutableListOf<Checkout>()

    override fun addProductToShoppingCart(checkoutProduct: Checkout){
        checkout.add(checkoutProduct)
    }

    override fun getProductsInShoppinCart() : List<Checkout>?{
        return checkout
    }

    override fun cleanCheckout(){
        checkout.clear()
    }
}

@Test
    fun test_with_mock() {
        val mock = mock<CheckoutContract.Model>()

        var checkout = Checkout("VOUCHER", "voucher", 35.0, 5)
        mock.addProductToShoppingCart(checkout)

        val answer = mock.getProductsInShoppinCart()
        `when`(mock.addProductToShoppingCart(checkout)).thenReturn(checkout)

        assertNotNull(checkout)
        assertEquals(checkout, answer)
    }

A: In your function addProductToShoppingCart don't have any return type.
if you want check Checkout class make the change in the functions then test case will pass
override fun addProductToShoppingCart(checkoutProduct: Checkout):Checkout{
    checkout.add(checkoutProduct)
return checkout
}


text:
Q: How to select multiple images in expo I am working on react native application and I am using expo lib. I want functionality to select multiple images from gallery but I am failed because I am new to React Native . Could someone please help me how to select multiple images in expo .
code
    let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        quality: 1,
        allowsMultipleSelection: true,
        base64: false,
    });

A: It seems like that allowsMultipleSelection only works for web, as stated in their documentation:

allowsMultipleSelection (boolean) -- (Web only) Whether or not to
  allow selecting multiple media files at once.

To be able to do this on Android/iOS you probably should use this library - expo-image-picker-multiple.

A: I know this was posted a couple years ago but I just ran into this issue and luckily Expo's ImagePicker has been upgraded in SDK 46.0 to allow multi-image selection on iOS 14+, Android, and Web! To upgrade to this SDK version just follow this guide: https://blog.expo.dev/expo-sdk-46-c2a1655f63f7
I did this and am now able to use ImagePicker in my app on iOS to select multiple images at once!!

A: For expo users, i worked in a library for this purpose... Under the hood uses expo-media-library (if you don't want use the library you can check the code to do your picker), the package is called expo-image-multiple-picker


text:
Q: Differentiating between the iOS Simulator and Device in LLDB In Xcode, you can set breakpoints with conditions that evaluate the description of the thrown exception to determine whether or not to stop on that breakpoint. This is particularly helpful when working with Core Data, since Core Data throws exceptions internally as a control flow mechanism, and you want to stop on your exceptions, but not Core Data's. (Note: if you're wondering how to filter exceptions as described, it's answered on the SO question Ignore certain exceptions when using Xcode's All Exceptions breakpoint).
However, these filters often rely on the contents of a register, since the address of the exception is stored there. In the simulator (running on Intel architecture), the register is $eax, but on the device (ARM architecture) it's $r0.
Is it possible to craft an expression that differentiates between the two architectures so that one expression uses the correct register regardless of architecture currently in use?

A: lldb provides convenience register names for architectures that pass values in registers -- arg0 for the first argument, for instance.  However, the standard i386 ABI does not pass arguments in registers, they are passed on the stack (given the small number of general purpose registers available, this is not surprising).
The fact that eax (a volatile/non-callee-saved reg in the i386 ABI) has a value of relevance on entry to objc_exception_throw shows that the Objective-C runtime (libobjc) is doing some non-standard function calls between its internal routines, likely for efficiency.  You couldn't call a routine using a non-standard ABI like this from another module.
If you were talking about two ABIs that do pass arguments in registers, say x86_64 and arm, then you'd be fine with lldb's arg0 convenience variable.
If you were using lldb on the command line you could write a python function that gets r0 or eax, depending on the architecture, and gets the exception name to decide whether the breakpoint should continue or not.  But I don't think Xcode (today) gives you a way to put a python command on a breakpoint and control whether the process resumes or not.


text:
Q: How to print the contents of an OSX textclipping file from terminal? In OSX (I'm on 10.7.x, Lion), you can grab some text from most any app and drag it to the desktop to get a "snippet.textClipping" file.  The file is not just raw text, though -- the text is hidden away, somewhere (in a resource?)  I've tried poking around with DeRez, but haven't been able to bend it to my will.  What I'm looking for is the ability to get what one might think would be the output from
cat mysnippet.textClipping
NOTE: These clippings were made under an older version of OSX.  Maybe Leopard.  Maybe older, it's been a while.  :)
Thanks!
P.S. I've got a folder with 1600+ of them, that's why I'm looking to script this, not just manually copy/pasting them into a text file.
P.P.S.  Yes, if I just select-all then drag into an open, empty text document, it does as you'd expect.  But I still want to do it via script, so I can put the name of the clipping first and a blank line ahead of each, etc.

A: Here's something ugly that could work:
DeRez -only TEXT foo.textClipping | perl -ne 'm|/\* (.*) \*/| && print $1; END {print "\n"}'

Basically, it extracts the text from the C-style comments in the DeRez output and prints it all on one line. I got the idea from another Stack Overflow question (which I cannot find now).


text:
Q: enable password check for single-user mode I've been trying to find out how to activate that I'm prompted for a password when i boot in single user mode under linux, but I can't find it.
Where can I set this option?

A: You'll need to add an entry to your /etc/inittab
su:S:wait:/sbin/sulogin

should do it.
This will force sudo, which requires a login password.


text:
Q: dar focus() ou click() em um campo texto webview C# Estou desenvolvendo um webbrowser em UWP(windows universal application) usando a linguagem C#, para atribuir valor a um campo de texto que esta no webview eu usei o seguinte script:
string functionString = String.Format("document.getElementById('chatMessageSend').innerText = '{0}';", textbox.Text);
await Webview_uol.InvokeScriptAsync("eval", new string[] { functionString });

Na pagina HTML o que tenho é isso:

Porém como o site usa NG-click() ou angularjs se não me engano, não consigo de forma alguma dar focus() ou mesmo click() no campo de texto. O campo somente valida para clicar se de fato eu usar o mouse, via código não esta funcionando, alguém pode me ajudar com isso?

O site é o bate papo uol, em especifico essa sala: https://batepapo.uol.com.br/beta/Cidades-e-regi%C3%B5es/Cear%C3%A1/L/Limoeiro-do-Norte/Limoeiro-do-Norte-(2)  apos entrar nela meu programa tem que enviar uma mensagem para a sala de bate papo, já consigo preencher o campo e ate clicar no botão, porem a mensagem não vai pois precisa de algum tipo de validação o qual eu ainda não consegui fazer...


text:
Q: How do I get this variable to be defined? I have this code:
  <% @registered_friends.each do |friend| %>

<%= render 'profiles/fb_follow_form' %>

  <% end %>

It renders a partial in a different directory with this line:
<% if current_user != nil && current_user.following?(friend) %>

However my app is telling me that friend is undefined? How do I give myself access to the variable?

A: Changing
<%= render 'profiles/fb_follow_form' %>

to
<%= render 'profiles/fb_follow_form', :friend => friend %>

should do it


text:
Q: Redis sets the object as empty json "{}" while using Spring Boot I'm trying to set an object on redis. RedisTemplate configuration is shown below.
@Bean
fun redisTemplate(): RedisTemplate<String, Any> {
    val redisTemplate = RedisTemplate<String, Any>()
    redisTemplate.connectionFactory = jedisConnectionFactory()
    redisTemplate.defaultSerializer = GenericJackson2JsonRedisSerializer()
    redisTemplate.keySerializer = StringRedisSerializer()
    redisTemplate.hashKeySerializer = GenericJackson2JsonRedisSerializer()
    redisTemplate.valueSerializer = GenericJackson2JsonRedisSerializer()

    redisTemplate.afterPropertiesSet()
    return redisTemplate
}

here is my setting line
redisUtil.redisTemplate().opsForValue().set("CATEGORIES", tree)
and the result is
127.0.0.1:6379> keys *
1) "CATEGORIES"
127.0.0.1:6379> GET CATEGORIES
"{}"
127.0.0.1:6379>

A: If you want to store an object you can use hash
Pet pet = new Pet();
pet.setHeight(10);
pet.setName("tommy");

ObjectMapper oMapper = new ObjectMapper();

template.opsForHash().putAll("pet", oMapper.convertValue(pet, Map.class));

Pet pet1 = oMapper.convertValue(template.opsForHash().entries("pet"), Pet.class);
System.out.println(pet1.getName());
System.out.println(pet1.getHeight());
System.out.println(pet1.getWeight());

RedisTemplate configuration
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(jedisConnectionFactory());
template.setEnableTransactionSupport(true);
return template;
}

If you want to store it as a key value pair
Pet pet = new Pet();
pet.setHeight(10);
pet.setName("tommy");

template.opsForValue().set("pettest", pet);
Pet pet2 = (Pet) template.opsForValue().get("pettest");
System.out.println("boo boo");
System.out.println(pet2.getName());

result of get pettest in redis
{"@class":"com.cisco.rediscluster.Pet","name":"tommy","height":10}


text: Q: Volume control problem When you change the sound through the system mixer, the speaker value changes, but the headphone value remains the same, because of this the sound is distorted, but if you change both of these values at the same time, then everything is fine and the sound changes smoothly. Is it possible to do something so that when changing the value of the system mixer, both of these values changed?