text:
Q: Can I have multiple facebook strategies for passport? I want to handle the following passport-facebook related operations differently.

*

*Sign-Up with Facebook

*Log-In with Facebook

*Connect existing account to Facebook

For 'sign-up' I want to do/check:

*

*If the user already exists (based on facebook oauth id), redirect to log-in.

*If the user already exists (based on email address from facebook profile), prompt the user to sign in with email, then connect their facebook account.

*Create a new user & sign them in.

For 'log-in' and 'connect account' I want to perform a series of other checks/operations.
I've looked at the passport documentation for facebook and the passport-facebook module and a bunch of related Stack Overflow questions, but am still struggling with how to implement this.
How can I implement different facebook strategies (via passport) with different callbackURLs and options?

A: After a good deal of digging, this is what I ended up doing:

Create 3 separate passport strategies.
Each with different names (facebookSignUp vs facebookLogIn vs facebookConnect) and different callbackURL paths (.../sign-up/clbk vs .../log-in/clbk vs .../connect/clbk).
// facebook strategy 1 (sign-up with facebook)
passport.use('facebookSignUp', new FacebookStrategy({
        clientID: FACEBOOOK_APP_ID,
        clientSecret: FACEBOOK_APP_SECRET,
        callbackURL: 'http://website/auth/facebook/sign-up/clbk'
    },
    function(accessToken, refreshToken, profile, clbk) {
        return clbk(profile);
    }
));

// facebook strategy 2 (log-in with facebook)
...

// facebook strategy 3 (connect facebook to existing account)
...

Create routes for each strategy.
Initial request route & callback route after facebook authentication. So 2 routes per strategy.
var member = require('../member');              // member module controller

// sign-up with facebook
app.route('/auth/facebook/sign-up')
    .get(member.facebookSignUp);                // passport redirect to facebook for authentication

// sign-up with facebook callback
app.route('/auth/facebook/sign-up/clbk')
    .get(
    member.facebookSignUpClbk,                  // parse facebook profile to create new user & check for existing account -> redirect to log-in route
    member.checkEmail,                          // check if email is already used -> throw error 'please log in with email, then connect facebook in settings'
    member.checkUrl,                            // get unique url
    member.signUp,                              // create new user & sign-in
    member.email.welcome,                       // send welcome email
    member.facebookRedirectDashboard            // redirect to member dashboard
);

// log-in with facebook
app.route('/auth/facebook/log-in')
    .get(member.facebookLogIn);                 // passport redirect to facebook for authentication

// log-in with facebook callback
app.route('/auth/facebook/log-in/clbk')
    .get(
    member.facebookLogInClbk,                   // authenticate user and log-in & check if user exists (fb oauth id or email address) -> throw error 'please sign up with facebook or log in with email'
    member.lastLogin,                           // update user's last login field
    member.facebookRedirectDashboard            // redirect to dashboard
);

// connect facebook profile to existing account
...

// connect facebook profile to existing account clbk
...

Where the actual passport authentication is performed in the following files/functions.
member.facebookSignUp just calls passport.authenticate(), which redirects to facebook.
// member.facebookSignUp
exports.facebookSignUp = function(req, res, next) {
    passport.authenticate('facebookSignUp', {          // use the 'facebookSignUp' strategy
        display: null,                                 // null = let facebook decide (or 'page' (default), 'popup', 'touch', etc)
        scope: [
            'public_profile',                          // profile returned by default, but specified here anywhere
            'email',                                   // ask for email address
            'user_location'                            // ask for location
        ]
    })(req, res);
};

member.facebookSignUpClbk gets executed after facebook authorizes the user and redirects to the callback route. It is where everything else happens.
// member.facebookSignUpClbk
exports.facebookSignUpClbk = function(req, res, next) {

    // parse profile & plug into req.body for new user creation in later fxn
    function parseProfile(profile) {
        // user doc
        req.body = {};
        // facebook profile data
        req.body.facebook = (profile._json) ? profile._json : {id: profile.id};
        // name
        ...
        // email
        ...
        next();
    }

    // check existing users (mongoose/mongodb)
    function checkUser(profile) {
        User.findOne({query}, function(err, userDoc) {
            if (err) {
                return res.redirect(
                    'http://'+req.headers.host+
                    '?header=Sign-Up Error!'+
                    '&message=We had trouble signing you up with Facebook. Please try again'
                );
            } else if (userDoc) {
                // redirect to log-in fxn
                return res.redirect('http://website/auth/facebook/log-in');
            } else {
                parseProfile(profile);
            }
        });
    }

    // passport authentication
    function passportAuth() {
        passport.authenticate('facebookSignUp', function(profile) {
            if (!profile || !profile.id) {
                return res.redirect(
                    'http://'+req.headers.host+
                    '?header=Sign-Up Error!'+
                    '&message=We had trouble signing you up with Facebook. Please try again or sign-up via email.'
                );
            } else {
                checkUser(profile);
            }
        })(req, res);
    }

    // start process
    passportAuth();
};

member.facebookLogIn, .facebookLogInClbk, .facebookConnect, & .facebookConnectClbk are set up in a similar way, just different logic in the 'Clbk' functions depending on what I'm trying to do.

Hope this helps!


text:
Q: Returning values from a function :( Please can someone explain what's going wrong here?
Unfortunately, I have been tasked to complete this using a function; otherwise, I would've used a built-in function like count()
Thanks!
scores = [3,7,6,9,4,3,5,2,6,8]
y = int(input("What score are you searching for in the scores array?  "))
a = len(scores)
z = False
def count1(c,b):
    for d in range(0,c):
        if scores[d] == y:
            print("yes")
            b = True
            return(b)

        else:
            print("no")
count1(a,z)

if z == True:
    print(y, "occurs in the array")
else:
    print(y, "does not occur in the array")

my code^
Python 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:\Users\18skeffingtonc\
What score are you searching for in the scores array?  3
yes
3 does not occur in the array

the output, after entering what should be a valid input^

A: The basic fix to your immediate problem is to modify the line count1(a, z) to read z = count1(a, z).
That way, you give z to your count1, allow count1 to modify z, and then overwrite the old value of z with the new value generated by your count1.
That said, you have a lot going on in your code that you don't really need. One concise way to do what you're attempting would be:
scores = [3,7,6,9,4,3,5,2,6,8]

def count1(scores):
    y = int(input("What score are you searching for in the scores array?  "))
    print (f'{y} is {"" if y in scores else "not "}in the array.')

count1(scores)

Trying this out:
What score are you searching for in the scores array?  3
3 is in the array.

What score are you searching for in the scores array?  12
12 is not in the array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing release apk file path Android release apk is created in
...\Foo\Foo\build\outputs\apk\release\foo.apk

how can I change this path?
I want to save my apk for some projects in specific path.
Is this possible ?

A: Yes this is possible. you can set where your apk is to be generated,
in your Project level build.gradle add the path you need inside allprojects :
allprojects {
    buildDir = "/D:/Foo/Bar/Android/Build/"
    ...
}

This will create your apk alongwith the generated, intermediates, temp etc. folders inside the Build folder in the specified path. If you wish to have it generated in a folder with the Project Name etc use:
buildDir = "/D:/Foo/Bar/Android/Build/${rootProject.name}/${project.name}"

For more reference you can check this answer.
UPDATE:
I couldn't find any way to directly generate the release apk into some specific folder, But if its ok to save a copy of this apk into another folder you can achieve this using gradle's Copy task. In your APP level gradle you can try the below code I tested out.
afterEvaluate {
    // to execute the copy task every time a release build is generated
    packageRelease.finalizedBy(copyRelease)
}

task copyRelease(type: Copy) {
    // set your paths here
    def sourcePath = file ("/release/app-release.apk").absolutePath
    def destinationPath = "/D:/Foo/Bar/Android/Build/"
    // set a name for your build if you are going to rename it
    def releaseName = "${rootProject.name}.apk"

    from "$sourcePath"
    into "$destinationPath"
    //use the below line if you wish to rename the apk
    rename { releaseName }
}

Even though it suggested to add this inside android {...} block simply adding it outside seems to work. So even though apk doesn't get directly generated to your folder the task does copy the same to save it into the folder of your choice.
Incase you need it for debug builds, use packageDebug instead and change your paths accordingly.
Hope this is what you were looking for.


text:
Q: Test for a player using a command Okay, I've a problem. I need a command that tests for a player running a specified command.
For example, check whether a player is using /gamemode 1 (in order to reset them)

A: Gamemode can be reset by

/gamemode 0 @a[m=1]

M=0 denotes that they are in creative mode. If to want, you can add a

/tellraw @a[m=1] {"text":"","extra":[{"text":"Creative is not allowed","color":"white","italic":"true"}]}

that is powered just before the above command, to tell players to not use creative.
/scoreboard
If you are using a scoreboard (ie, to track total kills), you could use two deathCount (or whatever they are) objectives, and check both of them on a 20Hz clock to see if they are always equal.
/give is harder to track.
You could make a scoreboard objective for every item they could get, and clear items if the player doesn't have enought 'points' for that item.
/setblock is almost impossible to detect.
The only real method here is to /testforblock every block in your map, but that is mega-laggy if you have a map of reasonable size.
The best solution: Don't let anyone be an op.

A: Actually very simple to do, all you need to do is create a new scoreboard, and for an example let's just call it Admin...
/scoreboard objectives add Admin dummy

then create whatever value you want the Admin score to be... and then in a new command block, just have it test for anyone not with that Admin number and in gamemode 1 if it finds someone, have that player be changed to gamemode 2 or whatever...
testfor @a[score_Admin=(Number 1 less than Admin number),score_Admin_min=(Number 1 more than Admin Number),m=1]

gamemode 2 @a[score_Admin=(Number 1 less than Admin number),score_Admin_min=(Number 1 more than Admin Number),m=1]

so for example, lets say the Admin number is 2026
testfor @a[score_Admin=2025,score_Admin_min=2027,m=1]

gamemode 2 @a[score_Admin=2025,score_Admin_min=2027,m=1]

and you can even add a message to tell those players...
/tellraw @a[score_Admin=2025,score_Admin_min=2027,m=1] {"text":"","extra":[{"text":"Creative is not allowed","color":"white","italic":"true"}]}

Hope this info helps. Play around with it. Also, this way, you can give out Admin number to whomever the admins are, and the admin number can be changed, but make sure to turn off whatever clock you have running (or in 1.9 take off the always active part) before changing numbers in the command blocks and the admins must change to the new number.
Let me know if this helps and if you need help in anything else.

A: If there is a certain part of game you don't want them to turn creative, you can somehow (Secretly) power a repeat command block that sets the gamemode to survival or adventure. That way if a noob player decides to turn creative, the game will turn back the mode before the noob player can do something. This will ruin the upper left corner of the screen, saying "set game mode to survival" a bunch of times, But its better than a big command. And search the command I forgot it.


text:
Q: not able to get new session java web project I am using NetBeans to create a java web application. I have used only jsp to create the project.
I want to provide login functionality. So, I need to work with Session.
I have tried to get session info on the very next page after the login page.
Meaning that login.jsp is the page where I ask user to give login details. And the next page is verifyCredentials.jsp where I am verifying credentials and checking for new session.
But every time I am getting old session only. So I am not able to get new session for the first login also.
I have tried sample code from Check session to check the functionality of session but it is also taking old session every time.
Getting same problem with every browser.
NetBeans version is 7.2.1 and JDK is 1.7


text:
Q: How to set variables with ./configure I am trying to compile and install a new PHP version next to my existing with pthreads.
Running ./configure, the process is using my default system PHP variables,
not the ones I am in:

checking target system type... x86_64-unknown-linux-gnu
checking for PHP prefix... /usr
checking for PHP includes... -I/usr/include/php5 -I/usr/include/php5/main -I/usr/include/php5/TSRM -I/usr/include/php5/Zend -I/usr/include/php5/ext -I/usr/include/php5/ext/date/lib
checking for PHP extension directory... /usr/lib/php5/20100525
checking for PHP installed headers prefix... /usr/include/php5
checking if debug is enabled... no
checking if zts is enabled... no

How can I change it to use /usr/local/src/php-5.6.5/ext instead?

A: This gets the job done:
./configure --prefix=/usr/local/src/php-5.6.5


text:
Q: JSF ClassNotFoundException in EJB module on JBoss EAP 6.1 I'm in the middle of porting a JSF 2.1 application to Jboss EAP 6.1 (JBoss AS 7.2). The application runs smoothly on Glassfish 3.1, and Weblogic 12c. Moreover a slightly similar application was ported successfully.
The problem occurs in a specific EJB singleton. In this, I have a method with @PostConstruct annotation, which runs at startup and fills a List with SelectItems. During deploy, a java.lang.ClassNotFoundException exception is thrown, which says JBoss can't find the javax.faces.model.SelectItem class.
If I comment out the method, everything is fine. The SelectItem class is used in some other beans in the web module without any problem.
My question is: Is there any known reason for this behaviour? Do I need some special configuration to use classes from the javax.faces package in an EJB module, running on JBoss?
JSF is not packaged with the EAR, so the application uses the server's implementation.
Thank you!

A: You've there a design mistake. The business service (EJB) tier is not supposed to have any web (JSF) tier related dependencies. Having javax.faces.* imports in an EJB class is in first place already wrong. It makes the business service unreusable across different web tiers such as JAX-RS, Wicket, Struts, plain servlets, etc. In well designed application servers the unability to reach web tier classes from the EJB tier on is already enforced by (Java EE default) restrictions in classloaders.
Keep the EJB free of JSF dependencies. Perform the desired job in an eagerly initialized application scoped JSF managed bean instead.
@ManagedBean(eager=true)
@ApplicationScoped
public class App {

    private List<SelectItem> someItems;

    @EJB
    private AppService service;

    @PostConstruct
    public void init() {
        // Populate your List<SelectItem> here.
    }

}


text:
Q: Trace of ui-notification after being killed How to remove the trace of ui-notification
These notifications making user to unable to click on buttons
Even notification killed when user geeting to point again its popping ,blocking the user to press button.
[
My controller code
 $scope.loginForm = function(isValid) {
    // $window.location.href = '/home';
    $scope.submitted = true;
    if (isValid) {
        service.login({
            data: {
                user: $scope.login
            }
        }).then(function(response) {
            authService.isLoggedIn = response.status == "success";
            if (response.status == "success") {
                authService.set("userInfo", response.data)
                authService.role = response.data.role;
                authService.name = response.data.name;
                Notification.success({message:'Successfully logged in'});
                // Notification.clearAll("Successfully logged in");
            }
            else{
                Notification.success('Invalid Credentials');
            }
            // console.log(response.data.redirect)
            $location.path(response.data.redirect);
        });
    } else {
        Notification.error('Error Login');
    }
};

A: option 1: App Config
app.config(["NotificationProvider", function (notificationProvider) {
    notificationProvider.setOptions({
            delay: 1000,
            startTop: 20,
            startRight: 10,
            verticalSpacing: 20,
            horizontalSpacing: 20,
            positionX: 'left',
            positionY: 'bottom'
        });
    }]);

you can use delay option on app config to hide message faster, if not, go option 2.

option 2: make external service
    app.service("closeNotify", function ($timeout) {
        this.closeNotification = function (time) {
            $timeout(function() {
                $(".message").click();
            }, time);
        }
    });

In this service we use "jQuery" to handle click() function, after popup the message we set our service to hide message after specific time, go to how use it

how
    app.controller("ctrl", ["$scope", "Notification", "closeNotify",
    function (scope, notification, closeNotify) {

        notification.primary('Primary notification');
        closeNotify(1000);
    }]);


text:
Q: If conditional in batch (inside a for, inside an if) I have an application that reads through all the files in the directory and will rename those files (if necessary) and create log files from the innards of them, however there are a couple of catches....

*

*If the files 15th character is something other than a "." or "_", substring the 14 characters previous plus the 15th and store as variable.

*If the files 15th character is a "." or "_" substring the 14 characters previous and store as variable.

For example, if filename is: DIY_0000000000a.xml the variable would be DIY_0000000000a and if the filename is: DIY_0000000000.xml the variable would be DIY_0000000000
There is a catch to all of this...
If the user picks Option 2, which is to rerun the application, then the application should rename all files in the directory to DIY_xxx_rerun.xml or DIY_xxxa_rerun.xml (should now explain the "_" in the aforementioned options.
The problem I have and what I need assistance with is that I can't seem to get the conditional logic correct. The application works, but if I have a mix of files in the directory (ie: DIY_0000000000a.xml, DIY_0000000000.xml & DIY_0000000000_rerun.xml, DIY_0000000000a_rerun.xml) it may work on one kind but not the other. Help is much appreciated.
Below is a snippet of my current code:
SETLOCAL EnableDelayedExpansion

    :EXECUTE
    ::IF AN XML FILE EXISTS ADD IT TO A LOG FILE, PROMPT USER IF THEY WANT TO VIEW IT
    ECHO.
    ECHO =============================================
    ECHO **SELECT YOUR OPTION BY USING YOUR KEYBOARD**
    ECHO =============================================
    ECHO.
    ECHO 1  - Generate DIY Log Files for normal orders
    ECHO 2  - Generate DIY Log Files for _rerun orders
    ECHO 3  - EXIT

    ECHO.
    ECHO.
    SET /P CHOICE=Type your option, then press ENTER:
    IF %CHOICE%==1 (
        SET RERUN=
        GOTO PROCESS
    )
    IF %CHOICE%==2 (
        SET RERUN=_rerun
        GOTO PROCESS
    )
    IF %CHOICE%==3 EXIT
    IF NOT '%CHOICE%'== SET CHOICE=%CHOICE:~0,1%
    ECHO.
    ECHO "%CHOICE%" is not a valid option.
    PAUSE
    GOTO EXECUTE

    :PROCESS
    IF EXIST DIY*.xml (
        SET /a FILECOUNTER=0
        ECHO.
        ECHO Processing...
        FOR /f "delims=" %%a IN ('DIR /b /a-d /on DIY*.xml') DO (
            SET /a LOGCOUNTER=!FILECOUNTER!/1+1
            SET ORDERNUMBER=%%a
            IF "!ORDERNUMBER:~14,1!" NEQ "." (
                IF "!ORDERNUMBER:~14,1!" NEQ "_" (
                SET ORDERNUMBSTR=!ORDERNUMBER:~0,15!
                )   ELSE (
                        SET ORDERNUMBSTR=!ORDERNUMBER:~0,14!
                )
            )
            SET ORDERNUMBSTR=!ORDERNUMBER:~0,14!
            IF "%RERUN%"=="_rerun" (
                REN !ORDERNUMBSTR!.xml !ORDERNUMBSTR!%RERUN%.xml >NUL 2>&1
            )   ELSE (
                REN *!ORDERNUMBSTR!*.xml !ORDERNUMBSTR!.xml >NUL 2>&1
            )
            FOR /f "tokens=4 delims=<>" %%i IN ('TYPE !ORDERNUMBSTR!%RERUN%.xml ^|find "DIY_LOG_ID"') DO (
                SET DIYLOGID=%%i
            )
            FOR /f "tokens=7 delims=<>" %%j IN ('TYPE !ORDERNUMBSTR!%RERUN%.xml ^|find "ACCOUNT_KEY"') DO (
                SET ACCOUNTKEY=%%j
                FOR /f "tokens=1-3 delims=-" %%x IN ("!ACCOUNTKEY!") DO (
                    SET CONTRACTNR=%%x
                    SET PLANSEQ=%%y
                    SET SUBSEQ=%%z
                )
            )
...

ENDLOCAL

A: Just needed a day to think about it...
Was able to get what I wanted by using the following FOR loop instead of IFs
FOR /f "delims=" %%a IN ('DIR /b /a-d /on DTL*.XML') DO (
        SET /a LOGCOUNTER=!FILECOUNTER!/1+1
        SET ORDERNUMBER=%%a
        **FOR /f "tokens=1,2 delims=_." %%p IN ("!ORDERNUMBER!") DO (
            SET ORDERNUMBSTR=%%p_%%q**
        )
        IF "%RERUN%"=="_rerun" (
            REN !ORDERNUMBSTR!.XML !ORDERNUMBSTR!%RERUN%.XML >NUL 2>&1
        )   ELSE (
            REN *!ORDERNUMBSTR!*.XML !ORDERNUMBSTR!.XML >NUL 2>&1
        )
        ...


text:
Q: Rigid Body Equations in terms of Body Coordinates by Hamilton's Principle I sought-for the equations of motion of an unrestrained rigid body. The equations of motion are readily available in the literature, but my concern is to derive them by Hamilton's principle.
Expressing the position of an infinitesimal particle within the body as:
$$ \vec{R} = \vec{R}_0 + \vec{r} $$
where $\vec{R}_0$ and $\vec{r}$ are expressed in terms of body coordinates, origin of which is located at the center of mass. Additionally, $\vec{R}_0$ is the position of the center of mass measured from inertial frame, $\vec{r}$ is the position of the point measured from body frame.
The velocity of this point with respect to the inertial frame can be found as:
$$ \vec{V} = \dot{\vec{R}}_0 + \vec{\omega} \times (\vec{R}_0+\vec{r}) $$
where $ (\dot{}) $ represents the time derivative with respect to the body frame. To find the acceleration, differentiate with respect to inertial frame once more yields:
$$ \vec{a} = \ddot{\vec{R}}_0 + \dot{\vec{\omega}}\times(\vec{R}_0+\vec{r}) + \vec{\omega} \times \dot{\vec{R}}_0 + \vec{\omega} \times \vec{V} $$
One can find the variation of velocity by replacing the time derivatives by variational $\delta$ operator and using $\vec{\delta\theta}$ infinitesimal rotation vector:
$$ \delta \vec{V} = \delta \dot{\vec{R}}_0 + \delta \vec{\omega} \times(\vec{R}_0+\vec{r}) + \vec{\omega} \times \delta \vec{R}_0 + \vec{\delta\theta} \times \vec{V}  $$
Now, I can use variation of kinetic energy. For the simplicity, I do not consider potential energy and work done by external forces:
$$ \int_{t_1}^{t_2} \delta T dt = 0 $$
where
$$ \delta T = \int_D \rho \vec{V} \cdot \delta\vec{V} dD $$
By first, calculating the $ \delta \vec{R}_0 $ , I obtain the following:
$$ \int_{t_1}^{t_2} \int_D \rho \left[ \left( \dot{\vec{R}}_0 + \vec{\omega} \times (\vec{R}_0+\vec{r}) \right) \cdot \delta \dot{\vec{R}}_0 + \left( \dot{\vec{R}}_0 + \vec{\omega} \times (\vec{R}_0+\vec{r}) \right) \cdot \left( \vec{\omega} \times \delta \vec{R}_0 \right) \right] dD dt $$
The first part of this integral can be integrated by parts, and hence one can obtain the translational equation of motion.
The rotational equations of motion can be obtained from the second part:
$$ \int_{t_1}^{t_2} \int_D \rho \left[ \left( \dot{\vec{R}}_0 + \vec{\omega} \times (\vec{R}_0+\vec{r}) \right) \cdot \left( \delta \vec{\omega} \times(\vec{R}_0+\vec{r}) \right) + \left( \dot{\vec{R}}_0 + \vec{\omega} \times (\vec{R}_0+\vec{r}) \right) \cdot \left( \vec{\delta\theta} \times \vec{V}  \right) \right] dD dt $$
The second part of the integral is zero, hence we end up with the following form:
$$ \int_{t_1}^{t_2} \int_D \rho \left[ \left( \vec{R}_0+\vec{r} \right) \times \left( \dot{\vec{R}}_0 + \vec{\omega} \times (\vec{R}_0+\vec{r}) \right) \right] \cdot \delta \vec{\omega}  dD dt $$
My question is here. Since angular velocity is non-holonomic, it cannot be expressed as a derivative of a vector, i.e., one cannot obtain an expression for rotation. I need to evaluate this integral by parts to obtain the rotational equations of motion.
In other words, how can I find the relation between $ \delta \vec{\omega} $ and $ \vec{\delta \theta} $?
Please note that the usage of the following expresion does not yield the correct result:
$$ \delta \vec{\omega} = \frac{d (\vec{\delta \theta}) }{dt} $$


text:
Q: Max supported speed for RAM for toshiba satellite a665-s6070? I cant find a reliable source that explains what is the maximum:

*

*Ram size

*Ram speed

That my toshiba satellite a665-s6070 supports.
Currently I put 1 8 GB 1600 mhz + 4 GB 1600mhz and it starts but the computer is shuting down automatically sometimes.
I tried with ubuntu memtest86 and it shutdowns there too, I tried removing each one and the same happen for both of the rams I have.
I also tried with 1 2GB 1600 Mhz and got same result.
Any recomendation?
What happens if I put a more faster RAM than the supported velocity for the computer?

A: According to the page
Crucial Toshiba Satellite A665-S6070 compatible upgrades,
the maximum possible for your computer is 8 GB in two sticks of 4 GB:

Please note all the characteristics of the proposed memory, since you will need
to duplicate them almost exactly.
Crucial itself apparently does not sell this memory any more.
Note also that the
manual
for your computer specifies that when only one stick is installed,
it should be placed in the bottom slot A, as follows:


text:
Q: "cut" and "paste" functionality when using multiple terminals instead of "mv" If I have two terminals in different working directories, and I want to move a file from the PWD of one terminal to PWD of the other without using mv (because mv requires me to type out at least one of the directories)
We can implement a very simple "cut" and "paste" functionality by implementing them as a bash script:
# cut (pseudocode)
fname=<target>
mv <target> /tmp/the-cut-file

# paste
mv /tmp/the-cut-file ./$fname

I wanted to know if standard tools exist which handle this functionality, so I don't have to roll out my own (and take care of edge cases, maintain it, not get command line auto complete... etc)

A: I don't know of a tool that does exactly what you want. That doesn't mean it doesn't exist, but it does mean that it isn't something you can expect to find on a typical Linux desktop.
Copy-pasting a single file with ordinary household tools
If you're willing to change the requirements slightly, so that it isn't exactly the copy-cut-paste model, things can be simpler. One thing the copy-cut-paste model does which complicates the implementation, and is usually counter-intuitive for files anyway, is to take the cut-vs-copy decision at the point of origin. For files, it usually makes more sense to select at the point of origin, and copy or move at the point of destination. If you take this approach, the point of origin only needs to copy a list of file names, and not the decision to move or copy.
Copying a file name to the clipboard is fairly easy with common tools: xsel or xclip on X11, pbcopy and pbpaste on macOS. See Copy the contents of a file into the clipboard without displaying its contents and How to read over 4k input without new lines on a terminal?. xsel and xclip are usually not installed by default, but they're usually available as packages. I'll use xsel in my examples because it's shorter to type, the other tools are similar. xsel is actually buggy with large inputs, but this is not a problem with typical file names.
The following code examples assume that file names don't end in newline characters.
With zsh and xsel, here's a copy-paste example for a single file or directory:
/some/where% xsel <<<$PWD/myfile
/else/where% cp `xsel` .

With bash or ksh you need a few double quotes.
/some/where$ xsel <<<"$PWD/myfile"
/else/where$ cp -p "`xsel`" .

Note that pasting directly into a command line does not work if the file name contains shell special characters.
Dealing with multiple files
The easiest way to deal with multiple files is not to deal with multiple files. If you want to copy multiple files, copy the (name of the) destination directory from the destination terminal, and paste it into the source terminal.
/else/where$ xsel <<<"$PWD"
/some/where$ cp -Rp file1 file2 *.more.files "`xsel`"

I have a script called cfn (copy file name) which essentially copies its argument with $PWD/ prepended to the clipboard, but adds a bit of robustness: it supports multiple arguments, it copies to both the X selection and the clipboard, it works with both absolute and relative file names, it has options to support Windows paths. It could be improved to use null separators, and then it would support newlines in file names.
#! /bin/sh
# Copy file name

if [ "$#" -eq 0 ] || [ "$1" = "--help" ]; then
  cat <<EOF
Usage: $0 [OPTION]... FILENAME [...]
Copy FILENAME to both the X clipboard and the primary selection.
If FILENAME is relative, prepent \$PWD.
Multiple FILENAMEs are separated by newlines, but no newline is added at the
end.

  -F            Do not add a newline after the last file name (default)
  -f            Do add a newline after the last file name
  -p PREFIX     Prefix to use instead of \$PWD
  -r ROOT       Prefix to use before ROOT
  -s STRING     Separator to use instead of a newline
  -u            Use slash as the path separator (default)
  -w            Use backslash instead of slash as the path separator
EOF
  exit
fi

set -e -f

append=
cwd="$PWD/"
explicit_cwd=
names=
nl='
'
root=
sep='/'

change_separator () {
  if [ -z "$1" ]; then
    eval "$var="
    return
  fi
  IFS=/
  var=$1
  eval "set \$$var; $var=\$1"
  shift
  if [ "$1" != "" ]; then
    set "$@" ""
  fi
  while [ "$#" -ne 0 ]; do
    eval "$var=\$$var\$sep\$1"
    shift
  done
}

while getopts Ffuwp:r:s: OPTLET; do
  case "$OPTLET" in
    F) append=;;
    f) append=1;;
    p) cwd="$OPTARG"; explicit_cwd=1;;
    r) root="$OPTARG";;
    s) nl="$OPTARG";;
    u) sep="/";;
    w) sep="\\";;
    *) echo 1>&2 "$0: unknown option: -$OPTLET"; exit 3;;
  esac
done
shift "$((OPTIND-1))"
if [ -z "$explicit_cwd" ] && [ "$sep" != "/" ]; then
  change_separator cwd
fi

for x do
  case $x in
    .) x=${cwd%"$sep"};;
    [!/]*)
      if [ "$sep" != "/" ]; then
        change_separator x
      fi
      x="$cwd$x";;
    *)
      if [ "$sep" != "/" ]; then
        change_separator x
      fi;;
  esac
  names="$names$root$x$nl"
done
if [ -z "$append" ]; then
  names=${names%"$nl"}
fi
printf %s "$names" | xsel
printf %s "$names" | xsel -b

I don't have a corresponding paste script; here's how to paste multiple files (with newline-separated names) in zsh.
/else/where% cp -p ${(f)$(xsel)} .

In bash:
/else/where$ readarray -t a < <(xsel) && cp -p "${a[@]}" .


text:
Q: Why doesn't browser load webp images? (gatsby site, page generated from mdx) I'm wondering if anyone can please help me determine why webp images are not rendered when viewing my gatsby site in the browser?
i'm using gatsby-plugin-mdx and gatsby-remark-images with option withWebp: true
With this setup, the resulting output source that is sent to the browser looks (roughly) like this...
<picture>
  <source srcset-"/static/11aaa2b.../a12bc/example-image-1.webp ... etc... snipped
  <source srcset-"/static/33ccc4d.../a12bc/example-image-1.jpg ... etc... snipped
  <img src="/static/33ccc4d.../a12bc/example-image-1.jpg ... etc... snipped
</picture>

However, the browser is only rendering the <img> version, i.e. the jpg.
I can see that the webp file is there.
I have also confirmed that the webp version is accessible (i.e. I can navigate specifically to the webp file...
Why isn't the browser rendering the webp version?
Thanks in advance for your time/thoughts on this to help me understand it.
I have searched for, but haven't yet found, an answer using the following:

*

*Checked here on StackOverflow using this search query.

*Looked for something in a few varieties of Google search, for example

*Re-checked the relevant usage doco, to ensure I was configuring things correctly

A: Answered by @ksav in comments above.
Turns out, the browser actually is serving the webp version of the image.
By using this method to inspect the element properties and looking at the currentSrc property, I can confirm that webp is actively used.
The issue was with how I was previously inspecting.
I was relying on what Chrome Developer Tools was highlighting in the Elements window. In that highlighted area, it looked like it was the <img> tag that was being rendered.
But now, on closer inspection of the properties (now that I'm aware of how to use it properly) I can see that all is ok.
Thank you @ksav for the suggestion. This answers the question.


text:
Q: incremental/ decremental for-loops for removing elements from an array using splice I'm trying to remove falsy elements from an array. When I run an incremental for loop like the one shown here, it only removes one falsy value at index 2 and not the one at index 3, yet when I run a decremental for loop, like the one shown below, it removes both (all) falsy values from the array. Why? It would seem to me that i should iterate through the array either way. What am I missing?
function bouncer(arr) {
    for(var i=0;i<arr.length;i++){
        if(Boolean(arr[i]) === false){
           arr.splice(i,1);
        }
  }
console.log(arr);
}

bouncer([7, "ate", "", false, 9]);

function bouncer(arr) {
    for(var i=arr.length-1;i>=0;i--){
        if(Boolean(arr[i]) === false){
           arr.splice(i,1);
        }
  }
console.log(arr);
}

bouncer([7, "ate", "", false, 9]);

A: Since your removing the element with Splice your skipping to the element ahead.
Try subtracting the variable by 1 everytime you remove an element.
 function bouncer(arr) {
    for(var i=0;i<arr.length;i++){
        if(Boolean(arr[i]) === false){
           arr.splice(i,1);
           i--;
        }
  }
console.log(arr);
}

bouncer([7, "ate", "", false, 9]);


text:
Q: Copy a bulk of sub nodes to existing node I'm trying to:

*

*run over a column holding XML [MY_XML_COLUMN in MY_TABLE]

*for each XML:

*

*take all nodes of a certain type ([@type="myType"])

*for each "myType" node:

*

*check  if it holds a sub node "myEvent" (note - if exists - there will b only one)

*if so:

*

*copy (update) all the values from this node to another node "myNewEvent" which has the same sub
nodes like "myEvent"

*delete "myEvent" nodes from all "myType" nodes regardless

examples:
<hubs>
  <hubOne type="myType">   (myNewEvent should b updated as its of "myType" hub and has "myEvent" node)
     <myEvent>
       <subNodeOne> x <subNodeOne>
       <subNodeTwo> y <subNodeTwo>
       <subNodeThree> z <subNodeThree>
     </myEvent>
     <myNewEvent>
       <subNodeOne> a <subNodeOne>
       <subNodeTwo> b <subNodeTwo>
       <subNodeThree> c <subNodeThree>
     </myNewEvent>
  </hubOne>
  <hubTwo type="NOTmyType"> (myNewEvent should NOT b updated as its NOT of "myType" hub)
     <myEvent>
       <subNodeOne> x <subNodeOne>
       <subNodeTwo> y <subNodeTwo>
       <subNodeThree> z <subNodeThree>
     </myEvent>
     <myNewEvent>
       <subNodeOne> a <subNodeOne>
       <subNodeTwo> b <subNodeTwo>
       <subNodeThree> c <subNodeThree>
     </myNewEvent>
  </hubTwo>
  <hubThree type="myType"> (myNewEvent should NOT b updated as its of "myType" but no subnode "myEvent")
     <myNewEvent>
       <subNodeOne> x <subNodeOne>
       <subNodeTwo> y <subNodeTwo>
       <subNodeThree> z <subNodeThree>
     </myNewEvent>
  </hubThree>
  <hubFour type="myType"> (myNewEvent should b updated as its of "myType" hub and has "myEvent" node)
     <myEvent>
       <subNodeOne> q <subNodeOne>
       <subNodeTwo> w <subNodeTwo>
       <subNodeThree> e <subNodeThree>
     </myEvent>
     <myNewEvent>
       <subNodeOne> a <subNodeOne>
       <subNodeTwo> b <subNodeTwo>
       <subNodeThree> c <subNodeThree>
     </myNewEvent>
  </hubFour>
</hubs>

The wanted outcome:
<hubs>
  <hubOne type="myType"> (myNewEvent updated and myEvent deleted)
     <myNewEvent>
       <subNodeOne> x <subNodeOne>
       <subNodeTwo> y <subNodeTwo>
       <subNodeThree> z <subNodeThree>
     </myNewEvent>
  </hubOne>
  <hubTwo type="NOTmyType"> (myNewEvent NOT updated and myEvent deleted)
     <myNewEvent>
       <subNodeOne> a <subNodeOne>
       <subNodeTwo> b <subNodeTwo>
       <subNodeThree> c <subNodeThree>
     </myNewEvent>
  </hubTwo>
  <hubThree type="myType"> (myNewEvent NOT updated)
     <myNewEvent>
       <subNodeOne> x <subNodeOne>
       <subNodeTwo> y <subNodeTwo>
       <subNodeThree> z <subNodeThree>
     </myNewEvent>
  </hubThree>
  <hubFour type="myType"> (myNewEvent updated and myEvent deleted)
     <myNewEvent>
       <subNodeOne> q <subNodeOne>
       <subNodeTwo> w <subNodeTwo>
       <subNodeThree> e <subNodeThree>
     </myNewEvent>
  </hubFour>
</hubs>

What I tried so far with no success:

*

*google + older stack overflow solutions

*code example:
DECLARE @ID INT;
DECLARE @HUB_ID UNIQUEIDENTIFIER;
DECLARE @NAME VARCHAR(MAX);

DECLARE PROFILES_CURSOR CURSOR
FOR
SELECT P.[ID] FROM [MY_TABLE] P WHERE P.DELETED=0;
OPEN SOME_CURSOR
FETCH NEXT FROM SOME_CURSOR INTO @ID
WHILE @@FETCH_STATUS = 0
BEGIN

DECLARE HUBS_CURSOR CURSOR
FOR
SELECT H.hub.value('(@name)', 'varchar(1024)') AS [NAME]
FROM MY_TABLE
CROSS APPLY MY_XML_COLUMN.nodes('/integration/hub[@type="myType"]') as H(hub)
WHERE PROFILE_ID=@ID
OPEN HUBS_CURSOR
FETCH NEXT FROM HUBS_CURSOR INTO @NAME
WHILE @@FETCH_STATUS = 0
BEGIN

UPDATE [MY_TABLE]
SET [INTEGRATION_XML].modify(some xquery code to deal all nodes at once?)
WHERE ANOTHER_COLUMN = @ID
AND (
SELECT [SOME_IDENTIFYING_COLUMN]
FROM MY_TABLE PS
WHERE PS.MY_XML_COLUMN.exist('/integration/hub[@name=sql:variable("@NAME" and @type="myType")]/events') = 1
AND PS.INTEGRATION_XML.exist('/integration/hub[@name=sql:variable("@NAME" and @type="myType")]/events/myEvent') = 1
AND PROFILE_ID=@ID
) IS NOT NULL
FETCH NEXT FROM HUBS_CURSOR INTO @NAME
END

CLOSE HUBS_CURSOR
DEALLOCATE HUBS_CURSOR
FETCH NEXT FROM PROFILES_CURSOR INTO @ID
END

CLOSE PROFILES_CURSOR
DEALLOCATE PROFILES_CURSOR

A: ...destruction?
(create newEventNode at the end of the hub and then delete myEvent& all newEventNodes except the last one)
declare @x xml = N'<hubs>
  <hubOne type="myType">   (myNewEvent should b updated as its of "myType" hub and has "myEvent" node)
     <myEvent>
       <subNodeOne> hubone-upd1 </subNodeOne>
       <subNodeTwo> hubone-upd2 </subNodeTwo>
       <subNodeThree> hubone-upd3</subNodeThree>
     </myEvent>
     <myNewEvent>
       <subNodeOne> a </subNodeOne>
       <subNodeTwo> b </subNodeTwo>
       <subNodeThree> c </subNodeThree>
     </myNewEvent>
  </hubOne>
  <hubTwo type="NOTmyType"> (myNewEvent should NOT b updated as its NOT of "myType" hub)
     <myEvent>
       <subNodeOne> x </subNodeOne>
       <subNodeTwo> y </subNodeTwo>
       <subNodeThree> z </subNodeThree>
     </myEvent>
     <myNewEvent>
       <subNodeOne> a </subNodeOne>
       <subNodeTwo> b </subNodeTwo>
       <subNodeThree> c </subNodeThree>
     </myNewEvent>
  </hubTwo>
  <hubThree type="myType"> (myNewEvent should NOT b updated as its of "myType" but no subnode "myEvent")
     <myNewEvent>
       <subNodeOne> x </subNodeOne>
       <subNodeTwo> y </subNodeTwo>
       <subNodeThree> z </subNodeThree>
     </myNewEvent>
  </hubThree>
  <hubFour type="myType"> (myNewEvent should b updated as its of "myType" hub and has "myEvent" node)
     <myEvent>
       <subNodeOne> q </subNodeOne>
       <subNodeTwo> hubfour-w </subNodeTwo>
       <subNodeThree> e </subNodeThree>
     </myEvent>
     <myNewEvent>
       <subNodeOne> 1 </subNodeOne>
       <subNodeTwo> 2 </subNodeTwo>
       <subNodeThree> 3 </subNodeThree>
     </myNewEvent>
  </hubFour>

  <hubFive type="myType"> (myEvent but there is not myNewEvent....it will be created ??)
     <myEvent>
       <subNodeOne> myNewEvent did not exist </subNodeOne>
       <subNodeTwo> but it was created... </subNodeTwo>
       <subNodeThree> ....?? </subNodeThree>
     </myEvent>
  </hubFive>
</hubs>';

declare @t table(id int identity, thexml xml);
insert into @t(thexml)
select top (10) @x
from sys.all_objects;

declare @snet smallint = 20 /*max(xquery(count()path to be updated)) from @t*/;
while exists
(
select *
from @t
where thexml.exist('/hubs/*[@type="myType"][./myEvent][count(./myNewEvent) <= 1]') = 1
)
and @snet >= 0
begin
    update @t
    set thexml.modify
    (
    '
    (: add myEvent as last myNewEvent into the parent:)
    insert <myNewEvent>{/hubs/*[@type="myType"][./myEvent][count(./myNewEvent) <= 1][1]/myEvent[1]/*}</myNewEvent>
    as last
    into (/hubs/*[@type="myType"][./myEvent][count(./myNewEvent) <= 1])[1]
    '
    )
    where thexml.exist('/hubs/*[@type="myType"][./myEvent][count(./myNewEvent) <= 1]') = 1

    set @snet = @snet - 1;
end

update @t
set thexml.modify('
(: delete myEvent&myNewEvent nodes except the last one, which was added earlier :)
delete /hubs/*[@type="myType"][./myEvent][count(./myNewEvent) > 1]/*[local-name(.) = ("myEvent", "myNewEvent")][position() < last()]
')

select *
from @t;


text:
Q: how to display data from user panel using cmb2 metabox?

** This is my code **

        <?php echo get_avatar( get_the_ID() ); ?>
        <a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>">

<?php echo get_the_author_meta('display_name', $author_id); ?>

            <?php the_author_description(); ?>

        <img src="<?php echo get_post_meta( get_the_ID(), 'author_sign', true) ?>" alt="">

<?php echo get_post_meta( get_the_ID(), 'author_text', true ) ?>

** This is my cmb2 code **
    $author_data = new_cmb2_box( array(
    'id'      => 'author_metabox',
    'title'   => __( 'Custom Author Information', 'bounty' ),
    'object_types'  => array( 'user' ),
  ) );

  $author_data->add_field( array(
    'id'      => 'author_sign',
    'type'    => 'file',
    'name'    => __( 'Upload Author Sign: ', 'bounty' ),
    'options' => array(
      'url' => false
    )
  ) );

A: According to CMB2 documentation, instead of
<img src="<?php echo get_post_meta( get_the_ID(), 'author_sign', true) ?>" alt="">

you should use something like
<?php echo wp_get_attachment_image( get_post_meta( get_the_ID(), 'author_sign', true ), 'medium' ); ?>

or
<img src="<?php echo wp_get_attachment_image_url( get_post_meta( get_the_ID(), 'author_sign', true ), 'medium' ); ?>" alt="">


text:
Q: Passing Member Function Pointer into a Template First of all sorry for the title being confusing. Here's my OOP setup. I have base class Base, and two pure virtual functions add and multi. Then I have derived classes D1 and D2 and I implement the add and multi functions. I want to have a template function, that can have the flexibility that can switch between D1 D2 and calling add or multi functions. I googled around and someone people saying I should use function pointers but some others say it does not work with pure virtual functions.
class Base
{ double data; //data member
  Base(double d):data(d){};
  virtual double add() = 0;
  virtual double multi() = 0;
}
class D1::public Base
{ D1(double d): Base(d) {}; //calling base class constructor
  double add() {return data+1;} ;
  double multi() {return data*2;} ;
}
class D2::public Base
{ D2(double d): Base(d) {}; //calling base class constructor
  double add() {return data+3;} ;
  double multi() {return data*4;} ;
}
//now I want to have a template function that give me flexibility to construct D1 or D2 and calling add or multi.
template <typename T, typename F>
void testFun(double num)
{ T tmp(num); //create object either D1 or D2;
  cout << T->F() << endl; //calling either add or multi;
}
int main()
{ testFun<D1, D1.add()>(double x = 5);
//i know passing in D1.add() is wrong i don't know how to fix, hopefully you know what I am trying to achieve
  return 0;}

Any help will be appreciated. Thank you guys.

A: There's nothing about virtual member functions that makes pointers to member functions not work.  You can invoke a pointer to a pure virtual function if the object being invoked on is a pointer/reference to an object that has an actual implementation.
It looks like you're getting tripped up on the syntax of exactly how to pass a pointer-to-member-function in the first place.
Also note that virtual dispatch wouldn't even be used here since the type of object being used is known at compile time.
template <typename T>
void testFun(double num, double (T::*fn)())
{
    T tmp(num);
    std::cout << (tmp.*fn)() << std::endl;
}

Here, fn is a pointer to a member function of T that accepts no arguments and returns a double value.  You can invoke it like so:
testFun<D1>(5, &D1::add);

Note some other errors with the example code you've given:

*

*You specify base types with :: when you should use :. For example: class D1 : public Base.

*You use class but never specify an access modifier, which means all members are implicitly private.  For the purposes of the demo, changing them to struct (which defaults to public access) fixes this.

*You need a semicolon after a class/struct definition.

Here is a demo of the working code.

Just for the sake of completeness, here is a demo showing that you can use a pointer to a pure-virtual member function to invoke on a reference/pointer to a derived type.  The code has to be adjusted to use a D1 or D2 object through a reference of Base for the dispatch to be dynamic.  This example looks like:
template <typename T>
void testFun(double num, double (Base::*fn)())
{
    T tmpConcrete(num);
    Base & tmp = tmpConcrete;
    std::cout << (tmp.*fn)() << std::endl;
}

int main() {
    testFun<D1>(5, &Base::add);
}

(Of course, here it's a bit silly to use a pointer to a Base member when the generic code knows what T is, but it proves the point that it's possible.)


text:
Q: Example of objects and morphisms in h-TOP I've started studying algebraic topology and I've come up with my first example of real category: the h-TOP category.
In order to understand it better, I've thought about an example, and I'd like to know whether it's correct or not.
I start considering the objects $\mathbb{R}_*$ (which represents $\mathbb{R} \setminus \{0\}$) and $X = D^2 \sqcup D^2$ (the disjoint union of two unit disks, which I represent as a subspace of the real space: $(\{0\} \times D^2) \cup (\{1\} \times D^2) = \{ \vec{x}\ |\ x_1^2 + x_2^2 + x_3^2 \leq 1,\ x_1 = 0, 1 \}$).
On the one hand, the set of morphisms from $\mathbb{R}_*$ to $X$ is precisely the one containing only $[a]$, $[b]$, $[c]$ and $[d]$, where
\begin{equation}
a(x) = \left\{ \begin{array}{ll} (0, 0, 0) && x < 0 \\ (1, 0, 0) && x > 0 \end{array} \right.
\textrm{,}
\end{equation}
\begin{equation}
b(x) = \left\{ \begin{array}{ll} (1, 0, 0) && x < 0 \\ (0, 0, 0) && x > 0 \end{array} \right.
\textrm{,}
\end{equation}
\begin{equation}
c(x) = (0, 0, 0)
\textrm{,}
\end{equation}
\begin{equation}
d(x) = (1, 0, 0)
\textrm{.}
\end{equation}
On the other hand, the set of morphisms from $X$ to $\mathbb{R}_*$ is precisely the one containing only $[e]$, $[f]$, $[g]$ and $[h]$, where
\begin{equation}
e(\vec{x}) = \left\{ \begin{array}{ll} -1 && x_1 = 0 \\ 1 && x_1 = 1 \end{array} \right.
\textrm{,}
\end{equation}
\begin{equation}
f(\vec{x}) = \left\{ \begin{array}{ll} 1 && x_1 = 0 \\ -1 && x_1 = 1 \end{array} \right.
\textrm{,}
\end{equation}
\begin{equation}
g(\vec{x}) = -1
\textrm{,}
\end{equation}
\begin{equation}
h(\vec{x}) = 1
\textrm{.}
\end{equation}
Notice that $[e] \circ [a] = \textrm{Id}_{\mathbb{R}_*}$, because
\begin{equation}
e \circ a = e\left( \left\{ \begin{array}{ll} (0, 0, 0) && x < 0 \\ (1, 0, 0) && x > 0 \end{array} \right. \right) = \left\{ \begin{array}{ll} -1 && x < 0 \\ 1 && x > 0 \end{array} \right.
\end{equation}
is homotopic to $\textrm{Id}_{\mathbb{R}_*}$.
Also, $[a] \circ [e] = \textrm{Id}_X$, because
\begin{equation}
a \circ e = a\left( \left\{ \begin{array}{ll} -1 && x_1 = 0 \\ 1 && x_1 = 1 \end{array} \right. \right) = \left\{ \begin{array}{ll} (0, 0, 0) && x_1 = 0 \\ (1, 0, 0) && x_1 = 1 \end{array} \right.
\end{equation}
is homotopic to $\textrm{Id}_X$.
From these last observations follows the fact that $[a]$ is an isomorphism between $\mathbb{R}_*$ and $X$ and hence that $\mathbb{R}_*$ and $X$ are homotopically equivalent.
Please, point out EVERY mistake, and suggest other examples that allow me to understand the category h-TOP better.


text:
Q: TPS61025DRCR regulator input voltage drops to below 3V when powered - trouble shooting techniques? I'm currently using Texas Instruments TPS61025DRCR voltage regulator in a project (digikey link. When attempted to be powered with a 3V input, the regulator input voltage drops down to ~1.4V. When I unplug the 3V power source and measure its voltage, I again receive 3V. Thus, the issue has something to do with interfacing with the regulator.
My regulator circuit is illustrated below.

Note that this circuit was influenced by the TPS61025DRCR manual here.
Here is what I have done to troubleshoot the issue so far:

*

*Because VIN_RAW (per my diagram) is dropping to 1.4V, I first checked to make sure that there was no short circuit from VIN_RAW to GND. I was able to verify that VIN_RAW is not short circuited anywhere.

*I next verified that none of the solder on the pins had bridged.

*I then verified that the VCC (voltage regulator output) was not short circuited (or had low resistance to ground).

I'm looking for a little feedback on other potential errors. Things I can think of:

*

*I used too much hot air when soldering and just broke the chip.

*There is something wrong with how I designed my circuit.

Any ideas?

A: After a little more debugging, I was able to find the issue with the circuit. The following were my debugging steps:

*

*As Peter Bennett suggested, a source voltage that 'sags' (i.e. 3V -> 1.4V) when loaded suggests that the load has high current draw, such that the source can't source enough current. The measured current was found to be 400mA - way too high.

*The next step was determining what was drawing so much current. Although I had measured and determined there were no short circuits, I did not account for active components that could become shorts under the right conditions. After analyzing the circuit, there had been a single TVS diode that had been damaged which would clamp when 3V was applied. Essentially, the short circuit only existed when adding power.

Key takeaway: if there appears to be a short in your circuit but you measure none, always keep in mind that an active component (such as a TVS diode) could be the culprit.


text:
Q: Annotation to serialize Jackson field as a JSON string (instead of object) I'm working with Amazon SNS push notifications and they require me to send a payload like:
{
  "default": "This is the default message which must be present when publishing a message to a topic. The default message will only be used if a message is not present for
one of the notification platforms.",
  "APNS": "{\"aps\":{\"alert\": \"Check out these awesome deals!\",\"url\":\"www.amazon.com\"} }",
  "GCM": "{\"data\":{\"message\":\"Check out these awesome deals!\",\"url\":\"www.amazon.com\"}}",
  "ADM": "{\"data\":{\"message\":\"Check out these awesome deals!\",\"url\":\"www.amazon.com\"}}"
}

I have some classes that look like:
record APS(String alert) {}
record APNS(APS aps) {}
record SNSNotification(
  @JsonProperty("default") String defaultMessage,
  @JsonProperty("APNS") APNS apns
) {}

But when I serialize them I get non-insane JSON:
{
  "default": "...",
  "APNS": { "alert": "..." }
}

I looked into using @JsonSerialize(as =  String.class, using = SomeSerializer.class) but I'm not sure what class to plug in there? BeanSerializer didn't like that I'm using a record and nothing else really made sense.
Is there a simple way to do this without pre-serializing the fields?

A:
I looked into using @JsonSerialize(as =  String.class, using = SomeSerializer.class)

One of the options is to create a custom serializer by extending JsonSerializer and override it's serialize() method.
One of the arguments of serialize() is a JsonGenerator, which as it's name suggests allow to generate JSON. You can with go with JsonGenerator on pretty low level by specifying manually start/end of a JSON-object (JSON-array), writing field-names, etc., or you can feed a nested object into the JsonGenerator as is, depending on whether its default shape satisfies your needs or not.
That's how it might look like (I wasn't touching "GCM" and "ADM" properties from your JSON because it's unclear where they should come from).
@JsonSerialize(using = SNSNotificationSerializer.class)
record SNSNotification(
    @JsonProperty("default") String defaultMessage,
    @JsonProperty("APNS") APNS apns
) {}

public class SNSNotificationSerializer extends JsonSerializer<SNSNotification> {
    @Override
    public void serialize(SNSNotification value,
                          JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {

        gen.writeStartObject();     // {
        gen.writeStringField("default", value.defaultMessage()); // "default": " ",
        gen.writeFieldName("APNS"); // "APNS" :
        gen.writeStartObject();     // {
        gen.writeFieldName("aps");  // "aps" :
        gen.writeStartObject();     // {
        gen.writeStringField("alert", value.apns().aps().alert()); // "alert" : " ",
        gen.writeStringField("url", "www.amazon.com");             // "url":"www.amazon.com"
        gen.writeEndObject();       // }
        gen.writeEndObject();       // }
        gen.writeEndObject();       // }
    }
}

Usage example:
SNSNotification snsNotification = new SNSNotification(
    "This is the default message which must be present when publishing a message to a topic. The default message will only be used if a message is not present for one of the notification platforms.",
    new APNS(new APS("Check out these awesome deals!"))
);

ObjectMapper mapper = new ObjectMapper();

String json = mapper
    .writerWithDefaultPrettyPrinter()
    .writeValueAsString(snsNotification);

System.out.println(json);

Output:
{
  "default" : "This is the default message which must be present when publishing a message to a topic. The default message will only be used if a message is not present for one of the notification platforms.",
  "APNS" : {
    "aps" : {
      "alert" : "Check out these awesome deals!",
      "url" : "www.amazon.com"
    }
  }
}


text:
Q: making a link to another tab with href title and target im new to coding and i got an assignment that I didn't understand the outcome of.
heres a link to the solution: https://gyazo.com/061d8e2e23070bf5c13d737518175362
 i dont understand why the marked ">" is required. my solution to the issue before was : https://gyazo.com/63563dceafa3c14852a78095b24bd786
can someone explain to me the difference between the two

A: Bocman in your first solution you missed to close the tag. You are using anchor tag and its syntax is this
<a> </a>
and you are making href you have to closed it at the end. That was only the syntax that you was not following.


text:
Q: How to read ConnectionString from web.config in Asp.net MVC3 web Application? I am working in Asp.net Razor MVC3. I have created a App_Code folder and make a class in which I want read connection string from web.config and working with database by using this class. I am writing System.Configuration in this app_code class but it didn't shows me ConfigurationManager of Configuration class.
It shows like this

Rather than if I am write the same line in any controller then it will show System.Configuration.ConfigurationManager and in controller I can read connection string from web.config but in app_code I can't.
Please give me the solution how to read connection string in app_code class?

A: Include a reference to System.Web.Configuration:
using System.Web.Configuration;

Then, in your code, access it like this:
WebConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;

Example Class:
using System.Web.Configuration;

namespace MyWebApp.App_Code
{
    public class TestClass
    {
        public void TestMethod()
        {
            var connStr = WebConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
        }
    }
}

A: If you receive an error regarding "the ConfigurationManager does not exist in the current context", you will need to install the dll assembly besides for having the using System.Configuration statement in your controller.
You can find that in the Nuget gallery here https://www.nuget.org/packages/System.Configuration.ConfigurationManager/ or by added an assembly reference inside Visual Studio.
After that, you can write string MyString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString; (notice the singular form at the end of that piece of code).
Or if you haven't written the using statement for System.Configuration you will write the same thing but preface it with string MyString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;


text:
Q: How to limit the value of the textbox in vb 6.0 I am doing a marks updating database system. I need to limit each of my textbox to be in the value of less than 100, when its over than 100 or when its not number, a message box will pop up and the data won't be save until the user change the mistake. How can I do it?

A: I agree with Hiren Pandya, but I thought I would add my own take as well.
Be aware that converting a string to a numerical value is not trivial, but the Val, CInt, CDBl etc. functions in VB6 can all give you behavior that close to what you want. (some of those links are for VB.Net, but can still be valuable).  You want to make sure you are thinking about digit grouping, positive/negative, decimal separators, etc. when you are validating user input on your own.  Most of the time, the built-in functions are good enough.
Private Sub Text1_Change()
    On Error GoTo Err_Handler
    Dim text As String
    text = Text1.text
    If IsNumeric(text) = True Then

        'If you only want integers...
        Dim value As Integer
        value = Val(text)
            If value <= 100 And value > 0 Then
            'The value is good so whatever stuff you need to do
            'And then leave the procedure
            Exit Sub
        End If
    End If

    'Let everything else fall through here...
Err_Handler:
    MsgBox "Invalid input."
    'Other stuff to prevent saving
End Sub

A: In the properties of the text box, set MaxLength to 2.
If you want a message, in the text box Change event, you could do...
If Len(txtBox.Text)>2 then msgbox...

then add your message in the messagebox.
I could go into more detail if you need it. Some thing like below...
Private Sub Text1_Change()
If Len(Text1) > 6 Then
    Text1 = " "
    MsgBox "Not more than six"
    Text1.SetFocus
End If
End Sub


text:
Q: Creating Insert with Mysql Trigger I am trying to create a simple insert trigger from Products table to ProductPrice table, the sql fails with no error message:
CREATE TRIGGER productTrigger AFTER INSERT ON Products
    FOR EACH ROW
BEGIN
    INSERT INTO ProductPriceHistory (CURRENT_DATE(), CURRENT_USER(), productCode, productName, productLine, productVendor, quantityInStock, buyPrice)
    VALUES (productCode, productName, productLine, productVendor, quantityInStock, buyPrice);
END

A: To reference values from the newly inserted line, use the NEW keyword, and use the function calls as values, not as column names;
CREATE TRIGGER productTrigger AFTER INSERT ON Products
    FOR EACH ROW
BEGIN
    INSERT INTO ProductPriceHistory (log_date, log_user, productCode,
        productName, productLine, productVendor, quantityInStock, buyPrice)
    VALUES (CURRENT_DATE(), CURRENT_USER(), NEW.productCode, NEW.productName,
        NEW.productLine, NEW.productVendor, NEW.quantityInStock, NEW.buyPrice);
END

A: Try moving your function calls into the VALUES:
INSERT INTO ProductPriceHistory (date_column_name, user_column_name, productCode, productName, productLine, productVendor, quantityInStock, buyPrice)
VALUES (current_date(), current_user(), new.productCode, new.productName, new.productLine, new.productVendor, new.quantityInStock, new.buyPrice);

I made up the date_column_name and user_column_name names, you'll have to supply the real ones. The parenthesized list the follows the table name should contain column names, not column values. And you might need to prefix the column names in VALUES with new. to tell MySQL to extract those from the newly inserted row (which is called new in a trigger).


text:
Q: How to make code modular? I have some Java programs, now I want to find out whether it is modular or not, if it is modular then up to what extent, because modularity can never be binary term i.e. 0 or 1.
How do I decide that particular code is modular upto this much extent. I want to know how to make code much more modular?

A: Some Benchmarks for modularity:

*

*How many times are you rewriting similar code for doing a particular task?

*How much do you have to refactor your code when you change some part of your program?

*Are the files small and easy to navigate through?

*Are the application modules performing adequately and independently as and when required?

*Is your code minimally disastrous? Does all hell break lose when you delete just one function or variable? Do you get 20-odd errors upon re-naming a class? (To examine this, you can implement a stacking mechanism to keep trace of all the hops in your application)

*How near is the code to natural language usage? (i.e. modules and their subcomponents represent more real world objects without giving much concern to net source file size).

For more ideas check out this blurb about modularity and this one on software quality
As for your concern on making your code more modular first you should ask yourself the above questions, obtain specific answers for them and then have a look at this.
The basic philosophy is to break down your application into as small of code fragments as possible, arranged neatly across a multitude of easily understandable and accessible directory layouts.
Each method in your application must do no more than the minimum quanta of processing needed. Combining these methods into more and more macro level methods should lead you back to your application.

A: To answer your specific question of how to make the code more modular, a couple of approaches are:

*

*One of best tool for modularization is spotting code re-use. If you find that your code does the same exact (or very similar) thing in more than once place, it's a good candidate for modularizing away.

*Determine which pieces of logic can be made independent, in a sense that other logic would use them without needing to know how they are built. This is somewhat similar to what you to in OO design, although module/component does not necessarily need to correspond to a modeled object as in OO.

A: Key points are

*

*Separation of concerns

*Cohesion

*Encapsulation (communicates via interface)

*Substitutability

*Reusability

A good example of such module system is standard car parts like disk brakes and car stereo.
You don't want to build car stereo from scratch when you are building cars. You'd rather buy it and plug it in. You also don't want the braking system affecting the car stereo — or worse car stereo affecting the brake system.
To answer your question, "How do I decide that particular code is modular up to this much extent," we can form questions to test the modularity. Can you easily substitute your modules with something else without affecting other parts of your application?
XML parsers could be another example. Once you obtain the DOM interface, you really don't care which implementation of XML parser is used underneath (e.g. Apache Xerces or JAXP).
In Java, another question may be: Are all functionality accessible via interfaces? Interface pretty much takes care of the low coupling.
Also, can you describe each module in your system with one sentence? For example, a car stereo plays music and radio. Disk brakes decelerate the vehicle safely.

(Here's what I wrote to What is component driven development?)
According to Wikipedia, Component-Based Development is an alias for Component-based software engineering (CBSE).

[It] is a branch of software
engineering, the priority of which is
the separation of concerns in respect
of the wide-ranging functionality
available throughout a given software
system.

This is somewhat vague, so let's look at more details.

An individual component is a software
package, or a module, that
encapsulates a set of related
functions (or data).
All system processes are placed into
separate components so that all of the
data and functions inside each
component are semantically related
(just as with the contents of
classes). Because of this principle,
it is often said that components are
modular and cohesive.

So, according to this definition, a component can be anything as long as it does one thing really well and only one thing.

With regards to system-wide
co-ordination, components communicate
with each other via interfaces. [...]
This principle results in components referred to as encapsulated.

So this is sounding more and more like what we think of good API or SOA should look like.
The provided interfaces are represented by a lollipop and required interfaces are represented by an open socket symbol attached to the outer edge of the component in UML.

Another important attribute of
components is that they are
substitutable, so that a component
could be replaced by another (at
design time or run-time), if the
requirements of the initial component
(expressed via the interfaces) are met
by the successor component.
Reusability is an important
characteristic of a high quality
software component. A software
component should be designed and
implemented so that it can be reused
in many different programs.

Substitutability and reusability is what makes a component a component.
So what's the difference between this and Object-Oriented Programming?

The idea in object-oriented
programming (OOP) is that software
should be written according to a
mental model of the actual or imagined
objects it represents. [...]
Component-based software engineering,
by contrast, makes no such
assumptions, and instead states that
software should be developed by gluing
prefabricated components together much
like in the field of electronics or
mechanics.

A: Hej,
See, "How to encapsulate software (Part 1)," here:
http://www.edmundkirwan.com/encap/overview/paper7.html
Regards,
Ed.

A: Since this has been tagged with 'osgi', I can throw in an OSGi-related perspective.
The short answer is that it is possible to go from completely spaghetti code to modular in small steps; it doesn't have to be a big bang. For example, even spaghetti code depends on some kind of bolognaise logging library, so in some sense, it's already modular, just with One Very Big Metball (sorry, module) in it.
The trick is to break the big meatball into one smaller chunk and then a slightly less big meatball and then recurse. It doesn't all have to be done in one go either; simply chip off a bit more each time until there is nothing left to remove.
As for OSGi, it's still possible to put an uber-jar into a bundle. In fact, you can do this without changing the bits; either by modifying the Manifest.MF in place, or by wrapping that in another JAR and specify Bundle-ClassPath: metaball.jar in the manifest.
Failing that, tools like BND can help generate the right data you'd need, and then it can be dropped in an OSGi runtime easily enough. But beware of overly coupled code, and stuff that mucks around with classloaders - those will trip you up.

A: Assuming I understand your question, that you want to know what it is that makes code modular, since code modules will obviously need some dependency between each other to work at all. This is my answer:
If you can break your system down into modules, and you can test those modules in isolation, that is a good indication that a system is modular.

A: As you say modularity is not a binary thing so it depends on your relative definition.
I would say: Can you use a given method in any program where you need to perform that function?  Is it the "black box" where you wouldn't need to know what it were doing under the hood?  If the answer is no, i.e. the method would only work properly in that program then it is not truely modular.

A: Modularity is relative to who ever is developing the code. But I think the general consensus is that modular code is code that has portions that can easily be swapped out without changing most of the original code.
IMHO, If you have 3 modules A B and C and you want to change or replace module C completely, if it is a SIMPLE task to do so then you have modular code.

A: You can use a code analysis tool such as CAP to analyse the dependencies between types and packages. They'll help you find and remove any cyclic dependencies, which are often a problem when trying to develop modular code.
If there are no cyclic dependencies, you can start separating your code into discrete jars.
In general it is good practice to code to interfaces if you can, this generally means your code can more easily be refactored and/or used in different contexts.
Dependency injection frameworks such as Spring can also help with the modularity of your design. As types are injected with their dependencies by some external configuration process they don't need a direct dependency on an implementation.

A: The package-by-feature idea helps to make code more modular.
Many examples seen on the web divide applications first into layers, not features

*

*models

*data access

*user interface

It seems better, however, to divide applications up using top-level packages that align with features, not layers.
Here is an example of a web app that uses package-by-feature. Note the names of the top-level packages, which read as a list of actual features in the application. Note as well how each package contains all items related to a feature - the items aren't spread out all over the place; most of the time, they are all in a single package/directory.
Usually, deletion of a feature in such an app can be implemented in a single operation - deletion of a single directory.


text:
Q: KeyCloak bearer-only client shouldn't be able to invoke a secured endpoint when its credentials are wrong, but he can, why? I have a Spring Boot application with this configuration:
server:
  port: 9292

keycloak:
  auth-server-url: http://localhost:8180/auth
  realm: SampleRealm
  resource: non-existing
  public-client: false
  principal-attribute: preferred_username
  credentials:
    secret: wrong-secret
  bearer-only: true

I get an access token using another valid client (cli1, secret1):
curl -X POST \
    -H "Authorization: Basic c2ItYXBwOmEyY2ViZmI2LTBjMzgtNDNiNS1hMDAwLThhYmUzYjU5YjJiMQ==" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d 'username=someuser&password=somepassword&grant_type=password' \
    "http://localhost:8180/auth/realms/SampleRealm/protocol/openid-connect/token"

Now I use that bearer token to invoke my Spring Boot Service:
curl -X GET \
  http://localhost:9292/me \
  -H 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJPVE5xWF9jYWRXbEc1dGZYRmJVdEJ2V25hb2NTTGhuSm9LWndpOGxkYjZZIn0.eyJqdGkiOiI5ZTdlMjRmZC1lZDZmLTQzZTItYTFjZC1iMjlkMWRkN2I5ZWUiLCJleHAiOjE1MTk2NjQwODMsIm5iZiI6MCwiaWF0IjoxNTE5NjYzNzgzLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgxODAvYXV0aC9yZWFsbXMvU2FtcGxlUmVhbG0iLCJhdWQiOiJzYi1hcHAiLCJzdWIiOiIyNTFlZjNhNS1iNTRkLTQ4MmMtYTAzZS0wN2MzN2M0OGE5ZWIiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJzYi1hcHAiLCJhdXRoX3RpbWUiOjAsInNlc3Npb25fc3RhdGUiOiJlNjdjMDBiYy0zODUxLTQ4ZjYtYTIxZi1hNDVhOGI0NGQyOGMiLCJhY3IiOiIxIiwiYWxsb3dlZC1vcmlnaW5zIjpbXSwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbInVtYV9hdXRob3JpemF0aW9uIiwidXNlciJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sIm5hbWUiOiJKb3NlIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiamFpbmlnbyIsImdpdmVuX25hbWUiOiJKb3NlIiwiZW1haWwiOiJqYWluaWdvQHByb2ZpbGUuZXMifQ.bkMPSEvUHnVr5QoCsldKcFjKw3E_3Rhdu_SJ6LbgUehysAsLuG6pyjAQ4uqShTKphuXjOUf3E1eFMlttKSxZstCqP7iRU-OyHueGZ-_zGNx1ycvDBWSxCSmQufu9cx_dmnYW4NR9u5sSsZ052eDX0T0VgCvxeTtLJCsoH741SmJIVUvzrkPagKF_M_INVBQ3qaOds74o088qJy4GVJ8eZGqgsW9YOW6nNLV6kERwLAD9WZJoEARCdTBuGARTVJZuJ0lYVI0-jI0wN88T1G3vX3DZS0HIAROmgIait89PZ5wyfOu9u6ohTyFsi3uHV6uSJcN7x7t51snnBpr9KSSMMQ' \
  -H 'Cache-Control: no-cache'

The Spring Boot App is correctly invoking the secured endpoint but it shouldn't be allowed to because the resource (non-existing) and secret (wrong-secret) don't actually exist, they haven't even been configured in KeyCloak!!! Why is this working? Shouldn't the client have its client-id client-secret validated?
o.k.a.BearerTokenRequestAuthenticator    : Verifying access_token
o.k.a.BearerTokenRequestAuthenticator    :  access_token: xxxxxxxxxx.signature
 o.k.a.rotation.JWKPublicKeyLocator       : Going to send request to retrieve new set of realm public keys for client non-existing
 o.k.a.rotation.JWKPublicKeyLocator       : Realm public keys successfully retrieved for client non-existing. New kids: [OTNqX_cadWlG5tfXFbUtBvWnaocSLhnJoKZwi8ldb6Y]
 o.k.a.BearerTokenRequestAuthenticator    : successful authorized

Realm public keys successfully retrieved for client non-existing What??? non-existing client doesn't exist!!


text:
Q: CUDA - Understanding parallel execution of threads (warps) and coalesced memory access I just started to code in CUDA and I'm trying to get my head around the concepts of how threads are executed and memory accessed in order to get the most out of the GPU. I read through the CUDA best practice guide, the book CUDA by Example and several posts here. I also found the reduction example by Mark Harris quite interesting and useful, but despite all the information I got rather confused on the details.
Let's assume we have a large 2D array (N*M) on which we do column-wise operations. I split the array into blocks so that each block has a number of threads that is a multiple of 32 (all threads fit into several warps). The first thread in each block allocates additional memory (a copy of the initial array, but only for the size of its own dimension) and shares the pointer using a _shared _ variable so that all threads of the same block can access the same memory. Since the number of threads is a multiple of 32, so should be the memory in order to be accessed in a single read. However, I need to have an extra padding around the memory block, a border, so that the width of my array becomes (32*x)+2 columns. The border comes from decomposing the large array, so that I have an overlapping areas in which a copy of its neighbours is temporarily available.
Coeleased memory access:
Imagine the threads of a block are accessing the local memory block
1  int x = threadIdx.x;
2
3  for (int y = 0; y < height; y++)
4  {
5    double value_centre = array[y*width + x+1]; // remeber we have the border so we need an offset of + 1
6    double value_left   = array[y*width + x  ]; // hence the left element is at x
7    double value_right  = array[y*width + x+2]; // and the right element at x+2
8
9    // .. do something
10 }

Now, my understanding is that since I do have an offset (+1,+2), which is unavoidable, I will have at least two reads per warp and per assignment (except for the left elements), or does it not matter from where I start reading as long as the memory after the 1st thread is perfectly aligned? Note also, if that is not the case then I would have unaligned access to the array for each row after the first one, since the width of my array is (32*x)+2, and hence not 32-byte aligned. A further padding would however solve the problem for each new row.
Question: Is my understanding correct that in the example above only the first row would allow coeleased access and only for the left element in the array, since that is the only one which is accessed without any offset?
Thread executed in a warp:
Threads in a warp are only executed in parallel if and only if all the instructions are the same (according to link). If I do have a conditional statement / diverging execution, then that particular thread will be executed by itself and not within a warp with the others.
For example if I initialise the array I could do something like
1 int x = threadIdx.x;
2
3 array[x+1] = globalArray[blockIdx.x * blockDim.x + x]; // remember the border and therefore use +1
4
5 if (x == 0 || x == blockDim.x-1) // border
6 {
7   array[x] = DBL_MAX;
8 }

Will the warp be of size 32 and executed in parallel until line 3 and then stop for all other threads and only the first and last thread further executed to initialise the border, or will those be separated from all other threads already at the beginning, since there is an if statement that all other threads do not fulfill?
Question: How are threads collected into a single warp? Each thread in a warp needs to share the same instructions. Need this to be valid for the whole function? This is not the case for thread 1 (x=0), since it initialises also the border and therefore is different from others. To my understanding, thread 1 is executed in a single warp, thread (2-33, etc.) in another warp, which then doesn't access the memory in a singe read, due to miss-alignment, and then again the final thread in a single warp due to the other border. Is that correct?
I wonder what the best practice is, to have either memory perfectly aligned for each row (in which case I would run each block with (32*x-2) threads so that the array with border is (32*x-2)+2 a multiple of 32 for each new line) or do it the way I had demonstrated above, with threads a multiple of 32 for each block and just live with the unaligned memory. I am aware that these sort of questions are not always straightforward and often depend on particular cases, but sometimes certain things are a bad practice and should not become habit.
When I experimented a little bit, I didn't really notice a difference in execution time, but maybe my examples were just too simple. I tried to get information from the visual profiler, but I haven't really understood all the information it gives me. I got however a warning that my occupancy level is at 17%, which I think must be really low and therefore there is something I do wrong. I didn't manage to find information on how threads are executed in parallel and how efficient my memory access is.
-Edit-
Added and highlighted 2 questions, one about memory access, the other one about how threads are collected to a single warp.

A:
Now, my understanding is that since I do have an offset (+1,+2), which is unavoidable, I will have at least two reads per warp and per assignment (except for the left elements), or does it not matter from where I start reading as long as the memory after the 1st thread is perfectly aligned?

Yes, it does matter "from where you start reading" if you are trying to achieve perfect coalescing.  Perfect coalescing means the read activity for a given warp and a given instruction all comes from the same 128-byte aligned cacheline.

Question: Is my understanding correct that in the example above only the first row would allow coeleased access and only for the left element in the array, since that is the only one which is accessed without any offset?

Yes.  For cc2.0 and higher devices, the cache(s) may mitigate some of the drawbacks of unaligned access.

Question: How are threads collected into a single warp? Each thread in a warp needs to share the same instructions. Need this to be valid for the whole function? This is not the case for thread 1 (x=0), since it initialises also the border and therefore is different from others. To my understanding, thread 1 is executed in a single warp, thread (2-33, etc.) in another warp, which then doesn't access the memory in a singe read, due to miss-alignment, and then again the final thread in a single warp due to the other border. Is that correct?

The grouping of threads into warps always follows the same rules, and will not vary based on the specifics of the code you write, but is only affected by your launch configuration.  When you write code that not all the threads will participate in (such as in your if statement), then the warp still proceeds in lockstep, but the threads that do not participate are idle.  When you are filling in borders like this, it's rarely possible to get perfectly aligned or coalesced reads, so don't worry about it.  The machine gives you that flexibility.


text:
Q: Proof of Baer's criterion: what set to apply Zorn on? I'm reading the proof of Baer's criterion here:
https://ncatlab.org/nlab/show/Baer%27s+criterion
and I'm a little confused. Is it possible that they identify $M$ with its image in $N$?
I think if we are really formal, we should define a function $\tilde{f}: i(N) \to I: i(n) \mapsto f(n)$ and define the poset as
$$\{(M',f')\mid i(N) \leq M' \leq M, f': M' \to Q \quad morphism, f'\vert_{i(N)} = \tilde{f}\}$$
Applying Zorn's lemma yields a maximal element $(M',f')$ and it can then be shown that $M'=M$. Then for $n \in N$ we have
$$f'\circ i(n) = f'(i(n)) = \tilde{f}(i(n)) = f(n) $$
and thus $f' \circ i = f$, thus $f'$ is the extension of $f$ we are looking for.
Is the above correct? Did I unravel the identifications correctly?

A: Yes, you're right, you understood the matter of notation and the set to apply Zorn on is the right one. But observe that even if you did this proof by just considering an actual inclusion $N \subseteq M$ instead of a generic monomorphism $ i \colon N \rightarrowtail M$ then nothing would change.
Indeed, after having proved that, if $N \subseteq M$, then every arrow $N \to Q$ extends to an arrow $M \to Q$, consider an injection $N \xrightarrow{i} M$ and an arrow $N \xrightarrow{f} Q$. Then $(N \xrightarrow{i} M)=(N \xrightarrow{j} i(N) \subseteq M)$ and $j$ is an isomorphism. Hence the arrow $fj^{-1} \colon i(N) \to Q$ extends to an arrow $g \colon M \to Q$ along the inclusion $i(N) \subseteq M$, by what we proved before. But then the arrow $f \colon N \to Q$ extends to the arrow $g\colon M \to Q$ along the whole $i \colon N \to M$.
Hence you see that, if you prove the statement just for the actual inclusions, then the statement for every monomorphism follows for free.


text:
Q: Inner Product $p\neq 2$ I am liking know if exist a any generalization for inner product in the set $L^p(\mathbb{R}^2)$ , for any $p\geq 1$.

A: On any real Banach space $X$ one can define semi-inner products
$$\begin{split}
\langle x,y\rangle_+ &= \sup \{f(x):f\in X^*, \|f\|=1, f(y)=\|y\|\} \\
\langle x,y\rangle_- &= \inf\{f(x):f\in X^*, \|f\|=1, f(y)=\|y\|\}
\end{split}
\tag1$$
There is an equivalent definition in terms of directional derivative of the norm.
The semi-inner products  are not linear in $y$ unless we are in a Hilbert space. In general, they are not linear in $x$ either: $\langle x,y\rangle_+$ is convex and $\langle x,y\rangle_-$ is concave. But on smooth Banach spaces, such as $L^p$ for $1<p<\infty$, the set of functionals $f$ in (1) consists of just one element. This implies $\langle x,y\rangle_+ = \langle x,y\rangle_-$ and subsequently, the semi-inner product $\langle x,y\rangle$ becomes linear in $x$.
The Cauchy-Schwarz inequality holds in this form:
$$-\|x\|\,\|y\|\le \langle x,y\rangle_- \le \langle x,y\rangle_+ \le \|x\|\,\|y\| \tag2$$
Reference: Nonlinear Functional Analysis by Deimling.


text:
Q: RestAssured: how to iterate through JSON object and validate each value of key fields {
  "body": {
    "format": "json",
    "query": {
      "attributes": [
        {
          "field": "name",
          "order": "none",
          "hidden": false,
          "label": "Computer"
        }
      ],
      "types": [],
      "detail": true,
      "filter": {},
      "size": 5,
      "types_group": "test",
      "context": "newtest"
    },
    "bookmark": {
      "guid": null,
      "processed_time": 1570570800000
    }
  },
  "description": "test new",
  "display_name": "test1",
  "type": "profile",
  "read": "all",
  "write": "all"
}

how can I iterate through this JSON Object and validate each value of the key in RestAssured framework.
I want to compare something like this for each key in this JSON:
AssertTrue(get("display_name").matches("test1"))

A: As this will be really useful for other so though of Answering it.
However before Answering, there is a Question- How you gonna supply your expected Data set to be compared with Actual response? as you want to validate entire response body so its very important.
I'll explain controlling data from Cucumber Data table; as now a days Rest assured mostly being used with Cucumber(BDD), and so I. (one can use TestNG Data provider also as an efficient way of Test Data m/m, I can explain that too if needed..plz let me know)
Anyways to Answer below is the approach 1:
Sample Feature file:

 When User calls API- "yourAPI" with "Get/Post" method
    Then Server should return response code as "200"
    And Verify Response body contents matched with expected values
      | key     | value                            |
      | status  | 200                              |
      | message | Success                          |
      | result  | Batch got generated successfully |

Step Def for above response validation step:
@Then("^Verify Response body contents matched with expected values$")
    public void validateEntireJsonRespBody(DataTable table) throws Throwable {
        List<List<String>> data = table.raw();
        var resBody = response.getBody(); // capture the response in var as per your FW or methods being used
        for(int i = 1; i < data.size(); i++) {
            System.out.println(" Actual Response Value: "+resBody.jsonPath().get(data.get(i).get(0)).toString()+" To be Matched with Expected Data Table value: "+data.get(i).get(1));
                            assertEquals(data.get(i).get(1),resBody.jsonPath().get(data.get(i).get(0)).toString());
      // Or
        assertThat(resBody.jsonPath().get(data.get(i).get(0)).toString(), equalToCompressingWhiteSpace(data.get(i).get(1)));

        }

Or same can be done in this way too- ex2: if you are using cucumber.io instead of info.cukes.

And response includes the following
      | key                              | value              |
      | id                               | 100000002          |
      | batchCode                        | USFP               |
      | batchName                        | US Faster Paym     |

Step Def for this one-

    @And("response includes the following$")
    public void response_equals(Map<String,String> responseFields){
        json=response.then();
        System.out.println("JsonBody: "+json.extract().body().asString());

        for (Map.Entry<String, String> field : responseFields.entrySet()) {
            if(StringUtils.isNumeric(field.getValue())){
                json.body(field.getKey(), equalTo(Integer.parseInt(field.getValue())));
            }
            else{
                json.body(field.getKey(), equalTo(field.getValue()));
            }
        }
    }

here var json was declared as of type- ValidatableResponse


text:
Q: MySQL search with multiple category id I got a talbe like this
category_table

cat_id   |   cat_name
---------+--------------
1        |  cat 1'
---------+--------------
2        |  cat 2
---------+--------------
3        |  cat 3
---------+--------------
4        |  cat 4
---------+--------------
5        |  cat 5

Another table called item table as follows
item_table

item_id   |   item_name    |  cat_id
----------+----------------+-----------
1         |  name of item  |  2
2         |  name of item  |  1
3         |  name of item  |  2
4         |  name of item  |  3
5         |  name of item  |  2
6         |  name of item  |  4

I have got the following query for select in item_table
SELECT * FROM item_table WHERE cat_id=2

I got a category id array like this
$cats=array("2","3","3");

My question is how to perform a "multiple category" search using the above mentioned array ? Means I want select all items with category id 2,3,4.

A: Use In Operator of MYSQL:
SELECT * FROM item_table WHERE cat_id IN(2,3,4)

If you want to get result with join of tables then you can use:
SELECT t1.item_id, t1.item_name, t1.cat_id, t2.cat_name
FROM item_table t1
INNER JOIN category_table t2 ON t1.cat_id = t2.cat_id
WHERE t1.cat_id IN(2,3,4)


text:
Q: how to convert date string to time interval in PHP how can I convert a preset date string to a time interval? The date string is in the format of d/m/Y g:i:s A?
I tried the following, but it returns nothing:
$date = ... time format set above ....;
echo strtotime($date); //returns nothing.

Sample date - 24/08/2011 11:47:09 PM

A: If you're on PHP 5.3 or newer you can use DateTime::createFromFormat
For PHP 5.2 you could reformat it to something strtotime() can deal with like this:
$date = '24/08/2011 11:47:09 PM';
$d = substr($date,6,4).substr($date,3,2).substr($date,0,2).substr($date,10);
$ts = strtotime($d); //1314229629

A: strtotime will not get you the desired result because it assumes m/d/Y for the date, see Date Formats.
You could try to replace the /'s in the date with -'s, that would lead to an accepted format but it feels wrong / buggy although it should work if your format is fixed:
$new_date = str_replace("/", "-", $string_date);
$timestamp = strtotime($new_date);

A:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

http://php.net/manual/en/function.strtotime.php


text:
Q: What is exactly difference between a 'statement' and a 'function' in oracle sql? While reading upon the difference between decode function and CASE WHEN statement, I got confused while understanding that if both give the same result for a simple equation like the following:
DECODE(col1, 'ABC', 'DEF', 'OTHERS' ) AS COL2

CASE WHEN COL1 = 'ABC' THEN 'DEF'
        ELSE 'OTHERS'
     END AS COL2

Then what is the difference between the functionality of a function and a statement?
p.s. I am aware Case is capable of taking more complex equations... my question here is more about understanding difference between function and statement.

A: In SQL, there is no such thing as a "CASE statement". Your example is a CASE expression. (CASE statements do exist in PL/SQL.)
The documentation states "An expression is a combination of one or more values, operators, and SQL functions that evaluates to a value." So a SQL function is not different from an expression, it is a specific type of expression.
Note that DECODE and CASE behave differently when comparing NULL values: DECODE considers two NULLs to be "the same", which is an exception to the rule that comparing a NULL to anything has an "unknown" result.
with data(a, b) as (
  select 1,1 from dual union all
  select 1,null from dual union all
  select null,1 from dual union all
  select null, null from dual
)
select a, b,
  decode(a,b,'same','different') decode_result,
  case when a = b then 'same' else 'different' end case_result
from data;

A      B      DECODE_RESULT CASE_RESULT
------ ------ ------------- -----------
1      1      same          same
1      (null) different     different
(null) 1      different     different
(null) (null) same          different

A: I'm pretty much sure that CASE didn't exist in pre-9i Oracle database versions so you had to use DECODE.
No difference, they will both do the same job, but CASE is simpler to maintain. DECODE can grow to a real monster when complex things have to be done, with nested DECODEs so you probably know what you're doing while typing that statement, but a month later you're in deep trouble as you don't know what belongs to what, which closing bracket is closing which open bracket, ... real nightmare.
But, for simple things, it is quite OK. Saves some typing.

A: A function is simply some functionality capsuled. With a function you can call a functionality from anywhere without spelling it out explicitely. There are predefined functions like DECODE() or you can define functions yourself.
A statement is something like select 1 from dual and may contain functions (select decode(col1,'1','yes','no') from mytable).
The statement is (as long as you aren't in a block, which itself may contain several statements) an order you send to the DB, a function is kindof an instruction what to do with the given arguments.


text:
Q: Shared Memory Allocation on GPU (Static or Dynamic) I want to know what is the difference between statically allocated shared memory and dynamically allocated shared memory on the GPU? In my device code, I have the following line:
__shared__ int temp[THREADS_PER_BLOCK];

Is this static or dynamic allocation of shared memory?

A: It's dynamically allocated if the shared memory size is specified at run time. It is statically allocated if the size of the shared memory is determined at compile time. Your example is static shared memory allocation.


text:
Q: Error handling in the pipeline This function gets a list of installed software on a remote PC. What is special about this function is the conversion of the date from yyyyMMdd to MM/dd/yyyy. While the function works, it is dropping objects that have no InstallDate. I get this error:

Exception calling "ParseExact" with "3" argument(s).

function Get-Software {
    param ( [string[]]$ComputerName )

    [scriptblock]$code = {
        $keys = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
                'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'

        Get-ItemProperty -Path $keys |
            Where-Object { $_.DisplayName -ne $null } |
            Where-Object { $_.DisplayName -notlike '*update*' } |
            sort DisplayName |
            ForEach-Object {
                [PSCustomObject]@{
                    Display   = $_.DisplayName;
                    Installed = Get-Date ([DateTime]::ParseExact($_.InstallDate, 'yyyyMMdd', $null)) -format d
                }
            }
    }
    Invoke-Command -ScriptBlock $code -ComputerName $ComputerName -ArgumentList * |
        ft Display, Installed -AutoSize |
        Out-File "$Env:USERPROFILE\Desktop\SWinv.txt"
}

Get-Software RemotePC

What can I do to return all objects?

A: You could put a simple if/else check.
Assuming that $_.InstallDate is null when you get the error:
ForEach-Object {
    if ($null -ne $_.InstallDate) {
        [PSCustomObject]@{Display = $_.DisplayName; Installed = Get-Date ([datetime]::ParseExact($_.InstallDate,'yyyyMMdd',$null)) -format d}
    } else {
        [PSCustomObject]@{Display = $_.DisplayName; Installed = "Not Available"}
    }
}

A: Do the date parsing in a try..catch, assign the result to a variable, and use that variable when creating the object:
... | ForEach-Object {
    $date = try {
      [DateTime]::ParseExact($_.InstallDate, 'yyyyMMdd', $null).ToString('d')
    } catch {
      ''  # default value to assign if date is invalid
    }
    [PSCustomObject]@{
        Display   = $_.DisplayName;
        Installed = $date
    }
}

A: Because install date can be null, try this
     function Get-Software {
         param ( [string[]]$ComputerName )

         [scriptblock]$code = {
             $keys = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
                     'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'

             Get-ItemProperty -Path $keys |
                 Where-Object { $_.DisplayName -ne $null -and $_.DisplayName -notlike '*update*' } |
                 sort DisplayName |
                 ForEach-Object {
                     [PSCustomObject]@{
                         Display   = $_.DisplayName;
                         Installed =if ($_.InstallDate -ne $null) { Get-Date ([DateTime]::ParseExact($_.InstallDate, 'yyyyMMdd', $null)) -format d} else {$null}
                     }
                 }
         }
         Invoke-Command -ScriptBlock $code -ComputerName $ComputerName -ArgumentList * |
             ft Display, Installed -AutoSize |
             Out-File "$Env:USERPROFILE\Desktop\SWinv.txt"
     }

     Get-Software RemotePC