text:
Q: How to integrate BOT framework in a CMS based website for answering FAQ's which questions should be fetched from Backend I am planning to develop a website in Umbraco where FAQ's should be integrated with BOT framework. All the Questions need to be in the backend (MySQL) from there i need to fetch from answering FAQ's. Can anyone please help me out on integrating a BOT framework in a Umbraco based website? Your help in this query is much appreciated

A: the way you build this within Umrbaco is going to be very similar to the way you build a BOT framework in a normal language.  YOu could build a FAQ document-type within Umbraco and put all the questions within the CMS if you anted.  You could then create a JSON API to render that data to be used by the BOT framework:
https://www.jondjones.com/learn-umbraco-cms/umbraco-8-tutorials/umbraco-8-tutorials/how-to-create-a-json-api-within-umbraco-8/
If you do not need the data to be edited within Umbraco then you can jsut follow a normal .NET workflow


text:
Q: How to obtain token from "secondary" app from FirebaseApp.initializeApp() I am trying to initialize two FCM server in a single FCM client app.
First app is initialize with default name which is "[DEFAULT]" and second app is initialize with name "secondary".
Since in FirebaseApp it is compulsory to name one app as "[DEFAULT]".
After initialization I trying to obtain token value from both app but I am only receiving token from the [DEFAULT] app. Secondary app is returning null while querying for the token.
//Default app initialization:
FirebaseOptions.Builder defaultBuilder = new FirebaseOptions.Builder()
            .setApplicationId("[applicationID]")
            .setApiKey("[apikey]")
            .setDatabaseUrl("[url]")
            .setStorageBucket("[storageBucket]");
FirebaseApp defaultapp =FirebaseApp.initializeApp   (this,defaultBuilder.build());

//secondary app initialization:
 FirebaseOptions.Builder defaultBuilder1 = new FirebaseOptions.Builder()
            .setApplicationId("[applicationID]")
            .setApiKey("[apikey]")
            .setDatabaseUrl("[url]")
            .setStorageBucket("[storageBucket]");
 FirebaseApp myapp = FirebaseApp.initializeApp(this,defaultBuilder1.build(),"secondary");

//getting token for default app:
Log.d(TAG, "Default app token: " + FirebaseInstanceId.getInstance
(defaultapp).getToken());

//getting token for secondary app:
Log.d(TAG, "Secondary app token: " + FirebaseInstanceId.getInstance
(myapp).getToken());

'
Here Default app is returning proper token value but Secondary app is returning null, incase if we switch the FirebaseOptions for both app then still I am only able to get token from the server which is initialized as DEFAULT.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MSAL node / Create React App 5 - ClientAuthError: endpoints_resolution_error: Error: could not resolve endpoints I'm getting the following error when using MSAL node in an electron (v20) / create-react-app 5 - App.
ClientAuthError: endpoints_resolution_error: Error: could not resolve endpoints. Please check network and try again. Detail: ClientAuthError: openid_config_error: Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints. Attempted to retrieve endpoints from: https://abc_test.b2clogin.com/abc_test.onmicrosoft.com/b2c_1_abc_signupsignin/v2.0/.well-known/openid-configuration

I'm running this code in the component:
import React, { useEffect, useState } from "react";
import {
  PublicClientApplication,
  LogLevel,
  CryptoProvider,
} from "@azure/msal-node";

const authorizationOptions = {
  clientId: process.env.REACT_APP_B2C_CLIENT_ID,
  authority: process.env.REACT_APP_B2C_AUTHORITY,
  knownAuthorities: [process.env.REACT_APP_B2C_KNOWN_AUTHORITIES],
};

const authCodeUrlParameters = {
  scopes: [],
  redirectUri: process.env.REACT_APP_REDIRECT_URI,
};

const authCodeRequest = {
  redirectUri: process.env.REACT_APP_REDIRECT_URI,
  scopes: [],
};

const MSAL_CONFIG = {
  auth: authorizationOptions,

  system: {
    loggerOptions: {
      loggerCallback(loglevel, message, containsPii) {
        console.log(message);
      },
      logLevel: LogLevel.Verbose,
    },
  },
};

const AuthProvider = () => {

  const [authClient, setAuthClient] = useState()

  const showAuthClient = () => {
    console.log(authClient)
  }

  const getTokenInteractive = async (requestParams) => {

 try {
  // Generate PKCE Challenge and Verifier
  const cryptoProvider = new CryptoProvider();
  const { challenge, verifier } = await cryptoProvider.generatePkceCodes();

  // Add PKCE params to AuthCodeUrl request (passed to getAuthCodeUrl method)
  const authCodeUrlParams = {
    ...requestParams,
    prompt: "login",
    scopes: requestParams.scopes,
    codeChallenge: challenge,
    codeChallengeMethod: "S256",
  };

  const authCodeUrl = await authClient.getAuthCodeUrl(authCodeUrlParams);

  console.log("Done !")
 } catch (error) {console.log(error)}

  }
  useEffect(() => {
    const client = new PublicClientApplication(MSAL_CONFIG);

    setAuthClient(client);
  }, []);

  return (

Test abc

      <button onClick={showAuthClient}>AuthClient</button>
      <button className="border-3-blue" onClick={()=> {getTokenInteractive(authCodeUrlParameters)}}>getToken</button>

  );
};

export default AuthProvider;

Here's my package JSON:
{
  "name": "cra5polyfill",
  "version": "0.1.0",
  "private": true,
  "main": "./public/electron.js",
  "homepage": "./",
  "dependencies": {
    "@azure/msal-node": "^1.12.1",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^13.0.0",
    "@testing-library/user-event": "^13.2.1",
    "assert": "^2.0.0",
    "buffer": "^6.0.3",
    "crypto-browserify": "^3.12.0",
    "https-browserify": "^1.0.0",
    "os-browserify": "^0.3.0",
    "process": "^0.11.10",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "stream-browserify": "^3.0.0",
    "stream-http": "^3.2.0",
    "url": "^0.11.0",
    "util": "^0.12.4",
    "web-vitals": "^2.1.0"
  },
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject",
    "electron:start": "concurrently -k \"cross-env BROWSER=none yarn start\" \"wait-on http://localhost:3000 && electron .\"",
    "build:local:mac": "yarn build && electron-builder -m -c.extraMetadata.main=build/electron.js"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "concurrently": "^7.3.0",
    "cross-env": "^7.0.3",
    "dotenv": "^16.0.1",
    "electron": "^20.1.0",
    "electron-builder": "^23.3.3",
    "electron-notarize": "^1.2.1",
    "react-app-rewired": "^2.2.1",
    "wait-on": "^6.0.1"
  }
}

I needed to polyfill CRA 5 based on this article:
https://www.alchemy.com/blog/how-to-polyfill-node-core-modules-in-webpack-5
I need to request a token afterwards but can't get past this stage.
The endpoint is valid when I enter it in the browser.
The code works perfectly with an older version of the Electron / React App (exactly same endpoints / params).
Here's the package.json for that application:
{
  "name": "desktop-app",
  "displayName": "abc",
  "version": "0.2.1",
  "main": "public/electron.js",
  "homepage": "./",
  "private": true,
  "dependencies": {
    "@azure/msal-node": "^1.3.1",
    "@azure/storage-blob": "^12.8.0",
    "@popperjs/core": "^2.11.5",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^12.1.0",
    "@testing-library/user-event": "^13.2.1",
    "axios": "^0.21.4",
    "caniuse-lite": "^1.0.30001269",
    "cross-env": "^7.0.3",
    "dicom-parser": "^1.8.13",
    "dotenv": "^10.0.0",
    "electron-devtools-installer": "^3.2.0",
    "electron-is-dev": "^2.0.0",
    "electron-squirrel-startup": "^1.0.0",
    "framer-motion": "^4.1.17",
    "hammerjs": "^2.0.8",
    "history": "^4.10.1",
    "jwt-decode": "^3.1.2",
    "lodash": "^4.17.21",
    "react": "^16.14.0",
    "react-cool-onclickoutside": "^1.6.2",
    "react-dom": "^16.14.0",
    "react-hook-form": "^6.15.8",
    "react-redux": "^7.2.5",
    "react-router-dom": "^5.3.0",
    "react-scripts": "4.0.3",
    "redux": "^4.1.1",
    "redux-thunk": "^2.3.0",
    "use-is-in-viewport": "^1.0.9"
  },
  "scripts": {
    "dev": "concurrently \"npm run start\" \"wait-on http://localhost:3000 && electron --trace-warnings .\"",
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "pack": "npm run build && electron-builder --dir",
    "dist": "npm run build && electron-builder"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "concurrently": "^6.2.1",
    "electron": "^14.0.0",
    "electron-builder": "^22.11.7",
    "spectron": "^15.0.0",
    "wait-on": "^6.0.0"
  }

}

I cannot work out exactly why one is working and the other isn't.
Q: How do I debug this error ?
Any help would be much appreciated !


text:
Q: Symfony FOSUserBundle user manager extension I'm working on a RESTful application powered by Symfony 3, using FOSRestBundle, FOSUserBundle and FOSOAuthBundle.
My problem is I want to extend the FOS UserManager class, but this throws a fatal error :

Type error: Argument 1 passed to FOS\UserBundle\Doctrine\UserManager::__construct() must implement interface FOS\UserBundle\Util\PasswordUpdaterInterface, none given, called in /var/www/html/var/cache/dev/appDevDebugProjectContainer.php on line 2538

Here are parts of my application files:
# app/config/config.yml

fos_user:
    # [...]
    service:
        user_manager: foo.user_manager

# src/FooBundle/Resources/config/services.yml

services:
    # [...]
    foo.user_manager:
        class: FooBundle\Service\UserManager

    FooBundle\Service\UserManager:
        arguments:
            $class: '%fos_user.model.user.class%'

<?php

// src/FooBundle/Service/UserManager.php

namespace FooBundle\Service;

use FOS\UserBundle\Doctrine\UserManager as BaseUserManager;

class UserManager extends BaseUserManager implements UserManagerInterface
{
    /**
    * {@inheritDoc}
    * @see \FooBundle\Service\UserManagerInterface::findUsersAtPage()
    */
    public function findUsersAtPage($usersPerPage, $page) {
        $offset = $usersPerPage * $page;
        return $this->getRepository()->findBy(array(), null, $usersPerPage, $offset);
    }
}

<?php

// src/FooBundle/Service/UserManagerInterface.php

namespace FooBundle\Service;

use FOS\UserBundle\Model\UserManagerInterface as BaseUserManagerInterface;

interface UserManagerInterface extends BaseUserManagerInterface
{
    /**
     * Returns a collection with specified number of user instances at specified page.
     * @param int $usersPerPage The number of users per page.
     * @param int $page The page number.
     * @return \Traversable
     */
    public function findUsersAtPage($usersPerPage, $page);
}

The thing I observed is that when I use the default FOS user manager, the appDevDebugProjectContainer.php generates the getter method (with parameters) :
<?php

// var/cache/dev/appDevDebugProjectContainer.php

class appDevDebugProjectContainer extends Container
{
    // [...]

    protected function getFosUser_UserManagerService()
    {
    return $this->services['fos_user.user_manager'] = new \FOS\UserBundle\Doctrine\UserManager(${($_ = isset($this->services['fos_user.util.password_updater']) ? $this->services['fos_user.util.password_updater'] : $this->getFosUser_Util_PasswordUpdaterService()) && false ?: '_'}, ${($_ = isset($this->services['fos_user.util.canonical_fields_updater']) ? $this->services['fos_user.util.canonical_fields_updater'] : $this->getFosUser_Util_CanonicalFieldsUpdaterService()) && false ?: '_'}, ${($_ = isset($this->services['fos_user.object_manager']) ? $this->services['fos_user.object_manager'] : $this->getFosUser_ObjectManagerService()) && false ?: '_'}, 'FooBundle\\Entity\\User');
    }

    // [...]
}

and when I use mine (without parameters) :
<?php

// var/cache/dev/appDevDebugProjectContainer.php

class appDevDebugProjectContainer extends Container
{
    // [...]

    protected function getFosUser_UserManagerService()
    {
        return $this->services['fos_user.user_manager'] = new \FooBundle\Service\UserManager();
    }

    // [...]
}

Please, can someone help me ?

A: Ok guys that's the answer:
The service arguments had to be set in the service definition, not the class service definition. That's not really clear, so better than word, some code :
# src/FooBundle/Resources/config/services.yml

services:
    # [...]
    foo.user_manager:
        class: FooBundle\Service\UserManager
        arguments:
            $class: '%fos_user.model.user.class%'

    FooBundle\Service\UserManager: '@foo.user_manager'

I was thinking I tried it, but I didn't...

A: Just resolved the similar problem. Maybe will be helpful for someone. Check this answer
Or just try this one out
services:
    you_bundle.user_manager:
        class: YourBundle\Services\UserManager
        arguments: ["@fos_user.util.password_updater", "@fos_user.util.canonical_fields_updater", "@doctrine.orm.entity_manager", "%fos_user.model.user.class%"]


text:
Q: Plesk / Pin domain to the same home directory as another domain is it possible to pin domain to another's domain home directory?
Example: I have domain1.com and domain2.com. Now I want domain2.com pin to same home directory as domain1.com to access the same files.
I don't want Alias Domain, because it's just redirecting doman2 to domain1.
Thanks

A: Your goal will result in issues/errors/problems, due to the fact, that each domain will create it's very own domain - specific system-user, who owns files/folders, when you use Plesk. The domain - specific system-user from domain2 will not be able to interact with the content of domain1.


text:
Q: springAOP:AfterReturning Cannot act on a method in an interface Now I want to modify some parameters in the return value of a method. I want to use AOP implementation, but I have encountered a problem
@Pointcut("execution(public * com.hmdp.utils.MzJsonRedisUtil.my(..))")
    public void getSourceData() {

    }
    //    @Pointcut("execution(public * com.hmdp.utils.Ilock.my(..))")
    @Pointcut("execution(public * com.hmdp.utils.lock.SimpleLockImpl.my(..))")
    public void getineterfaceaop() {

    }

    @AfterReturning(returning = "map",pointcut = "getSourceData()")
    public void afterGetSourceData(Map<String, String> map) {
        System.out.println("进入切面修改aop"+map.get("K"));
        map.put("K","aop修改过了");
    }

    @AfterReturning(returning = "map",pointcut = "getineterfaceaop()")
    public void afterinter(Map<String, String> map) {
        System.out.println("进入实现接口的bean切面修改aop"+map.get("K"));
        map.put("K","进入实现接口的bean切面修改aop");
    }

I use the AOP aspect to succeed in a normal bean
However, when the bean is an implementation class, it fails
normal bean
@Component
public class MzJsonRedisUtil {
    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    public HashMap<String, String> my(){
        HashMap<String, String> map = new HashMap<>();
        map.put("K","V");
        System.out.println("进入切面内");
        return map;
    }
}

implementation bean
@Component
public class SimpleLockImpl implements Ilock {
    @Override
    public HashMap<String, String> my(){
        HashMap<String, String> map = new HashMap<>();
        map.put("K","V");
        System.out.println("进入切面内");
        return map;
    }
}


text:
Q: BibLaTeX Citetracker Confusion I have the following requirement: For the first time an author / the authors are mentioned, there has to be a "full" citation, matching the entry of the bibliography. After that, a short form is used, which already works.
Now I found in the BibLaTeX documentation the option citetracker which I set to true. I also found the macros \ifciteseen and \ifentryseen. However, I cannot figure out how to use them in my .cbx file in order to solve the problem. Do I have to rewrite a macro? And how do I get the bibliography string generated with the help of a .bbx file?
If you need more information or find a similar post (in spite of my search), feel free to comment.
Minimal example:
\documentclass{article}
\usepackage{lipsum}
\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
  @book{Knu86,
    author = {Knuth, Donald E.},
    year = {1986},
    title = {The \TeX book},
  }
\end{filecontents}

\begin{filecontents}{cs.cbx}
\RequireCitationStyle{authoryear}
\DeclareFieldFormat{citetitle}{#1\isdot}
\DeclareFieldFormat[article]{citetitle}{#1}
\DeclareNameFormat{labelname}{%
    \ifcase\value{uniquename}%
    \usebibmacro{name:last}{#1}{#3}{#5}{#7}%
    \or
    \ifuseprefix
        {\usebibmacro{name:last}{#1}{#3}{#5}{#8}}
        {\usebibmacro{name:last}{#1}{#4}{#6}{#8}}%
    \or
    \usebibmacro{name:last}{#1}{#3}{#5}{#7}%
    \fi
    \usebibmacro{name:andothers}
}
\end{filecontents}

\usepackage[citestyle = cs, bibstyle = standard, backend=bibtex8, citetracker=true]{biblatex}
\bibliography{\jobname}

\begin{document}
\lipsum[1]\footcite[S.85]{Knu86}
\lipsum[1]\footcite[S.96]{Knu86}
\printbibliography
\end{document}

I want to provide a piece of pseudocode which will hopefully make clear what I mean.

If the current bib entry (e.g. Knu86) was already cited
(true:) use the citation way defined in the cite style
(false:) print the string from the bibliography

A: This type of citation label is already implemented in the verbose style and its variants, but with short author-title instead of author-year labels. In verbose.cbx, use of the \ifciteseen test is demonstrated in the cite bibliography macro, defined by:
\newbibmacro*{cite}{%
  \usebibmacro{cite:citepages}%
  \ifciteseen
    {\iffieldundef{shorthand}
       {\usebibmacro{cite:short}}
       {\usebibmacro{cite:shorthand}}}
    {\usebibmacro{cite:full}}}

To obtain the desired output, we can then edit the cite:short macro to print labelyear in place of labeltitle. Full citations are generated by the cite:full macro via:
\usedriver{\DeclareNameAlias{sortname}{default}}{\thefield{entrytype}}

which gives the almost same output as the entry's bibliography item, except the name list at the beginning of the entry is printed in the default first-last format instead of last-first/first-last. Identical output can be obtained with
\usedriver{}{\thefield{entrytype}}

although the pages field may cause some confusion with page references in postnotes. To address this, the verbose style and its variants offer an additional option called citepages.
\documentclass{article}
\usepackage[german]{babel}
\usepackage{csquotes}
\usepackage[style=verbose,labelyear]{biblatex}

% experiment with these settings
\ExecuteBibliographyOptions{citepages=omit,citetracker=true}

% replace labeltitle with labelyear
\renewbibmacro*{cite:short}{%
  \printnames{labelname}%
  \setunit{\nameyeardelim}%
  \usebibmacro{cite:labelyear+extrayear}}

% full citations same as bibliography
\renewbibmacro*{cite:full}{%
  \usebibmacro{cite:full:citepages}%
  \printtext[bibhypertarget]{%
    \usedriver{}{\thefield{entrytype}}}%
  \usebibmacro{shorthandintro}}

% from authoryear.cbx
\newbibmacro*{cite:labelyear+extrayear}{%
  \iffieldundef{labelyear}{}{%
    \printtext[bibhyperref]{\printfield{labelyear}\printfield{extrayear}}}}

\bibliography{biblatex-examples}

\begin{document}
\null\vfill\noindent
Filler text \autocite{baez/article,baez/online}.
Filler text \autocite[85]{bertram}.
Filler text \autocite[96]{bertram}.
Filler text \parencite{baez/article,baez/online}.
\printbibliography
\end{document}

Note that the extrayear field appended to labelyear for disambiguation is not incorporated in author-title bibliographies. This field could be added, but an author-year bibliography style would be more reader-friendly. You can achieve this by replacing
\usepackage[style=verbose,labelyear]{biblatex}

with
\usepackage[citestyle=verbose,bibstyle=authoryear]{biblatex}


text:
Q: Model-to-Model-Transformation - no meta model for source I have to do a model-to-model transformation but the source model is rather obscure but also quite similar to UML activity diagrams (which are also the target by the way).
I've looked into tutorials for Eclipse Modeling Tools but I struggle a lot with it. Also, because there is no meta model for the source, I'm not sure if EMT is any help. What are my options here? Can I use EMT, should I use another tool in this case or should I write a generator myself?
Greetings


text:
Q: Get the caret position of a Firefox window The code below will correctly get the caret position on screen of a notepad window.  But when run for Firefox it returns all zeros?
I'm I do doing something wrong?   Or does Firefox just self-draw the caret onscreen outside of the Windows OS?  If the later, is there an alternative way to achieve this?
Thanks
    Option Explicit

    Private Declare Function GetForegroundWindow Lib "user32" () As Long
    Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
    Private Declare Function GetGUIThreadInfo Lib "user32" (ByVal dwthreadid As Long, lpguithreadinfo As GUITHREADINFO) As Long

    Private Type RECT
        Left As Long
        Top As Long
        Right As Long
        Bottom As Long
    End Type
    Private Type GUITHREADINFO
        cbSize As Long
        flags As Long
        hwndActive As Long
        hwndFocus As Long
        hwndCapture As Long
        hwndMenuOwner As Long
        hwndMoveSize As Long
        hwndCaret As Long
        rcCaret As RECT
    End Type

    Private Function GetCaretPosition() As GUITHREADINFO
        Dim pThreadId As Long
        Dim guiInfo As GUITHREADINFO
        pThreadId = GetWindowThreadProcessId(GetForegroundWindow(), &H0)
        guiInfo.cbSize = LenB(guiInfo)
        GetGUIThreadInfo pThreadId, guiInfo
        GetCaretPosition = guiInfo
    End Function

    Private Sub Test()

        Dim guiInfo As GUITHREADINFO
        'Works on notepad
        AppActivate "Notepad"
        Application.Wait DateAdd("s", 1, Now)
        guiInfo = GetCaretPosition()
        Debug.Print guiInfo.flags, guiInfo.hwndFocus, guiInfo.hwndCaret, guiInfo.rcCaret.Left, guiInfo.rcCaret.Top, guiInfo.rcCaret.Right, guiInfo.rcCaret.Bottom
        'Returns:  1             5119032       5119032       5             0             6             22

        'Doesn't work on Firefox
        AppActivate "Firefox"
        Application.Wait DateAdd("s", 1, Now)
        guiInfo = GetCaretPosition()
        Debug.Print guiInfo.flags, guiInfo.hwndFocus, guiInfo.hwndCaret, guiInfo.rcCaret.Left, guiInfo.rcCaret.Top, guiInfo.rcCaret.Right, guiInfo.rcCaret.Bottom
        'Returns:   0             5444838       0             0             0             0             0

End Sub

A: Here's my solution... WARNING it is using a intrusive method of SendKeys and clipboard access to test if the caret active is on the window.  I have got it to tidy up as it goes, but still could have undesired affects depending on the context in which it's used.
It doesn't return the caret position; just a true/false indicator whether or not the window as can active caret.
It's usueful if trying to identify when an opened window has keyboard focus and is ready for further SendKeys; just setup to run the check in a loop until true or suitable timeout has passed
Option Explicit

Private Declare Function GetForegroundWindow Lib "user32" () As Long
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long

Private Sub test2()

    AppActivate "Notepad"
    Application.Wait DateAdd("s", 1, Now)
    Debug.Print WindowHasKeyboardFocus(GetForegroundWindow())
    'Returns True

    AppActivate "Firefox"
    Application.Wait DateAdd("s", 1, Now)
    Debug.Print WindowHasKeyboardFocus(GetForegroundWindow())
    'Returns True

End Sub

Private Function WindowHasKeyboardFocus(hwnd As Long) As Boolean

    Dim WSH As Object
    Dim UserClipboard As String

    Set WSH = CreateObject("WScript.Shell")

    'Copy of user's clipboard for later restore
    UserClipboard = GetClipboard()
    SetClipboard ""

    'Send keys to prove it has keyboard focus
    WindowHasKeyboardFocus = False
    If SetForegroundWindow(hwnd) <> 0 Then
        WSH.SendKeys "a+{LEFT}^x" 'Type "a", then select it and cut it to clipboard
        Sleep 200
        WindowHasKeyboardFocus = GetClipboard() = "a"
    End If

    'Restore User's clipboard
    SetClipboard UserClipboard

    Set WSH = Nothing

End Function

Private Sub Sleep(Milliseconds As Long)
    Dim WaitTimer As Double
    WaitTimer = Timer + Milliseconds / 1000
    While Timer < WaitTimer
        DoEvents
    Wend
End Sub

Private Function GetClipboard() As String

    Dim X As Long
    Dim CB As Object
    Set CB = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

    'Get data from Clipboard (sometimes fails so done on loop)
    On Error Resume Next
    For X = 1 To 100
        CB.GetFromClipboard
        GetClipboard = CB.GetText
        Select Case Err.Number
            Case 0: Exit For
            Case -2147221040: Err.Clear 'Try Again (DataObject:GetText OpenClipboard Failed)
            Case Else: Err.Raise Err.Number, Err.Source, Err.Description
        End Select
    Next

    'Pass back any error that occured
    If Err.Number > 0 Then
        Err.Raise Err.Number, Err.Source, Err.Description
    End If

    Set CB = Nothing

End Function

Private Function SetClipboard(Value As String)

    Dim X As Long
    Dim Timeout As Single
    Dim CB As Object
    Set CB = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")

    'Prone to errors
    On Error Resume Next

    'Put data into Clipboard (sometimes fails so done on loop)
    CB.SetText Value
    For X = 1 To 100
        CB.PutInClipboard
        Select Case Err.Number
            Case 0: Exit For
            Case -2147221040: Err.Clear 'Try Again (DataObject:PutInClipboard OpenClipboard Failed)
            Case Else: Err.Raise Err.Number, Err.Source, Err.Description
        End Select
    Next

    'Pass back any error that occured
    If Err.Number > 0 Then
        Err.Raise Err.Number, Err.Source, Err.Description
    End If

    Set CB = Nothing

End Function


text:
Q: App Verification for OAuth 2.0 for Server to Server Applications Is the Google application verification required for Server to Server OAuth 2.0?
We are working on an application that writes to a Google Sensitive scope. We have searched the Google documentation for OAuth 2.0 regarding Server to Server Applications and cannot determine is the application verification is required. The only sort of definitive answer is in this snippet from the Server to Server OAuth docs

Your application calls Google APIs on behalf of the service account,
so users aren't directly involved.

Our application is hosted within a sub-government environment that blocks traffic originating from the outside. We have successfully demonstrated the read and write to the "user public" sensitive scope (because the OAUTH traffic is initiated from the inside) with Google API Client Library for JavaScript.
But, we are not able to verify the application by DNS or other methods using Oauth2 public method. We believe this is because for each verification method, Google servers need access to the internal (government) environment. We are also not allowed to use the internal "private" method.
Below is a simplistic drawing of a user being posed with an application verification dialog when trying to use the sensitive scope. The drawing also shows that the verification for the public method not being successful because it's blocked from the Government firewall(s)

A: Yes, for the OAuth Flow that you have described.
For Google Service to Service authorization, use a Service Account and not a User Account. For internal services use Token Based Authentication (one of many methods).
Google Authentication Overview
Getting Started with Authentication

But, we are not able to verify the application by DNS or other methods
  using Oauth2 public method. We believe this is because for each
  verification method, Google servers need access to the internal
  (government) environment. We are also not allowed to use the internal
  "private" method.

What application are you referring to? Google servers do not access your internal servers. When using the User type of OAuth Flow, Google verifies the callback URL for your service. This means that Google needs to verify that you own/control the domain name. Since this is an internal private domain, this is not possible. However, you are using the wrong type of OAuth Flow so worrying about this is the wrong direction to take.
For an internal server to server authorization, there are many methods. Probably the best and easiest is to emulate how OAuth does it. Create a signed JWT with a certificate private key on one server and verify the signed JWT using the public key on the other service. You have now verified that the request is valid from a known source. Next embed in the JWT the identity, permissions/roles, etc. that you want to implement/control. The other side verifies that the permissions requested have been granted for the identity.
Introduction to JSON Web Tokens
Token Based Authentication Made Easy

A: curl -F 'client_id=CLIENT_ID' \
-F 'client_secret=CLIENT_SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=AUTHORIZATION_REDIRECT_URI' \
-F 'code=CODE' \
https://api.instagram.com/oauth/access_token


text:
Q: json output is not in sorting order I have created web service in JAVA Netbeans and called MySQL data through rest web service.
Edited code:
For loop shows all areas in sorting order then why as json output all data are not displayed in ascending order???
my method is as follows :
    @GET
@Path("/ShowAreasDup")
@Produces(MediaType.APPLICATION_JSON)
public List<EntityAreas> ShowAreasDup(){

    ArrayList<EntityAreas> listSort;

    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn=DriverManager.getConnection(DB_URL,USER,PASSWORD);
        String query = "SELECT * FROM Areas ORDER BY AreaName";
        Statement statement = conn.createStatement();
        ResultSet resultset = statement.executeQuery(query);
    // iterate through the java resultset
    while (resultset.next())
    {
        int id = resultset.getInt("AreaID");
        String restroName = resultset.getString("AreaName");

        EntityAreas anames=new EntityAreas();
        anames.setAreaid(id);
        anames.setAreaname(restroName);
        ShowentityAreas.put(id, anames);
    }
    statement.close();
    }
    catch(HeadlessException | SQLException |ClassNotFoundException ee)
    {
        JOptionPane.showMessageDialog(null, ee);
    }

    listSort=new ArrayList<EntityAreas>(ShowentityAreas.values());
    Collections.sort(listSort,new Comparator<EntityAreas>(){

        @Override
        public int compare(EntityAreas o1, EntityAreas o2) {
            return o1.getAreaname().compareTo(o2.getAreaname());
        }

    });

    for(EntityAreas entityarea:listSort){
        System.out.println(entityarea);
    }

    return listSort;
}

thank you in advance for help
Edit :
Above code is works perfectly for me
thanks to all for giving me a direction to the answser :)

A: Given your code, there could be some hypothesis. The most probable is that ShowAreas stores the information in an non ordered data structure (for example an HashMap).
If you want to maintain your values in order , you have to use some additional data structure. For example, you can use a TreeSet for the values.
Another solution could be to sort the values immediatly before returning them (javadoc),
// Get the elements
List<Areas> areas = new ArrayList<Areas>(ShowAreas.values());
// Sort them
Collections.sort(areas);
// Return them
return areas;

Pay attention: if you want to use this method, the class Areas must implement Comparable.
A last advise: don't put the code that interacts with the database in the class that has the responsibility to receive external REST calls. You violates the single responsibility principle and your application will become unmaintainable very quickly. Try to use a structure Controller - Service - Repository.


text:
Q: Is it practical to build a web site using strict XHTML and relying on CSS 100% for visual style? I tend to take the academic approach all too often and adhere to strict principles in my development when the reality is that I could have finished the project sooner had I been a little less cautious. I'm looking to find the right amount of practicality.
I want to take the "Zen" approach to designing a site which (in my words) says "Use HTML strictly for content structure, and let the CSS magic do the rest". How practical is this in reality? One of the issues I run into is that I want to develop (make functional) the site first, then come back in and design it later. I know structure-wise how I want the site to flow, but I haven't even begun playing with the CSS layout, graphics, or any of the other designy stuff. What is the right approach here?

A: The approach you want to follow is the right one. Just two things:

*

*If you use a validator for css or html, don't pretend that all your html or css pass the test. Obviously the ideal goal is that everything validates, but at a first stage I think is better not spend a lot of time in validation issues. And remember that no one validator is perfect, and the good way to use it at the beginning is to guide you in the right direction and avoid big mistakes (i.e. put the same id twice in one page, or put block elements inside inline ones...). Then, when the application is at a good stage, you can make your css and html perfect and valid.

*Don't design the interface at the end. I think that the interface of the application can give you good directions in how develop your back-end too. So, at your place, I would design the interface first, with html and css, and then I'd start to add functionality to it.

(Sorry for my english, spelling corrections are welcome.)

A: It can be very practical and you will be suprised how clean your HTML looks.  I like using a CSS reset file to help get started, I personally like the YUI reset.  Another Zen item to consider is the use of unobtrusive JavaScript.  This further separates the different layers of your code.  JavaScript libraries, like jquery, prototype and dojo can help with this.

A: It can be done, and I think your site (and your web design skills, not least) will be much better for it. But it also has a certain learning curve. It requires a more thorough understanding of the XHTML/CSS specs than many people have.
Making sure your HTML can be validated is just the beginning.
Oh, and make sure all browsers run in strict mode when rendering the page.
Of course, you will require workarounds for IE support, but that can be done with several methods.
First, IE supports conditional comments, allowing you to include special CSS stylesheets just to fix IE bugs, which should get you most of the way, without affecting your compliant standard-version of the page.
For some things, you may need a bit of javascript as well, but it shouldn't be necessary for most common functionality.

A: There are reasons explained in http://www.webdevout.net/articles/beware-of-xhtml against using XHTML today. To summarize, XHTML is not supported unless you serve it as such and if you target older browsers (any IE version is old considering most of its features are implemented when they were still immature and not changed substantially for a while) you have no choice but serve it as HTML.
Unless you don't require features that being XML provides (like SVG, MathML), stick with HTML. You won't have any serious advantage over HTML, be any more semantic, have better CSS support (even less). But you get wider compatibility and your layout will be more predictable (for example table cells can inherit from first cell in the row in HTML, no such thing in XML, not even sure XHTML has any exceptions somewhere).
Validators won't help writing XHTML any more than HTML. Even annoy, if you use a strict one, leaving you wondering what is all the fuss about / in the br tag if you lie and say it is HTML. (Firefox view source shows it bright red if you serve XHTML as HTML). I am sure you can find more examples.

A: It's absolutely practical, and provides infinite benefit. In fact it's exactly what CSS and the separation of content and layout is designed for.
The right approach given the above, is to let different teams get on with the different tasks at hand. That requires (perhaps) an initial graphic design which can be quite rough, and a documented and collaboratively agreed set of naming conventions for things like "#viewport", ".user" etc..
The markup team will usually be backend driven and will usually lead the design team slightly, but they should and must remain flexible enough to change markup where required, or put that in the control of the designers.
This last is just my $.02, but where one person is both roles, again I think you lead yourself with the markup/backend first and then iteratively go to a design stage, then markup, then design, as required.

A: Sure, you can do that, but be prepared that it WILL NOT render under IE. On a recent web project, the majority of our front-end defects were fixing stuff in IE that already worked fine in Firefox. Maybe this will change in IE8, but I doubt it. In some cases we even had to write some javascript that would be executed on IE only to work around things that couldn't be done with just CSS.

A: while it sounds good in theory you cant create the layout for a site 100% with css. You still need to use some markup so that you have something to apply the css to.  That said, you can come fairly close to ideal using this method.  I'm constantly amazed at how little markup a true css guru actually requires.
closer the "zen" approach that you are really looking for is xslt. it works by your app generating xml data and then the xslt transforms that xml into html/css.  this requires learning xslt and adds another layer of complication to the process of generating a page, but adds the separation you are looking for.  In an ideal world the theory is that a programmer only has to worry about generating xml data and then a designer can generate the visuals using that data, however it rarely works that way as xslt is more technical than most designers can handle. Most of the time the programmer ends up generating the xslt which somewhat defeats the purpose.

A: One approach that works for me is to structure the HTML first, then add some minimal CSS in a  tag in the same file (just enough to create the right layout etc). Then once you're happy with the structure, you can pull the CSS out into separate files and / or completely rework the CSS. This strikes the right balance for me - it's still a lightweight process, but it avoids the potential headache of finding and replacing inline CSS.

A: In theoria yes, in practice, browser differences may force you to add a bit of javascript to deal with the differences.

A: Now... Benefits of something is different from practicality of doing it. Are you guys forgetting IE or even the pain-in-the-whatever client who wants the impossible done?
I am tempted to say you have to make some exception to the strict DTD that you are using to make it work in a reasonable set of browsers and please your stakeholder for the website/web-app.
I am a standards freak and no one would be more happy than me if it was possible to build a website that doesn't violate even 1 DTD rule. But after 4 years, I just haven't been able to do it for practical purposes.
Sure if I am the one coming up with the requirements for the website I am going to develop, it might be possible, but I have to bend the business rules to accommodate that. Believe me, that's the only way it is possible.


text:
Q: Table border affecting cell size Can anyone tell me why when I place border=1 on a table is fixes its layout?
This is the problem: I wrote some JavaScript that makes me an org chart. If I place a border around the tables that make the chart, everything lines up perfectly. If I remove the borders, some of the lines vary wildly (and seemingly randomly) in width. You will notice this in the red lines that connect the org chart.
This is for the inline attribute of "border" (such as <table border="1">).
Here are two demos:
Borders (good, looks all lined up): http://andrewvantran.com/table1.html
No borders (bad, all misaligned): http://andrewvantran.com/table2.html
I would like the have the table laid out the way it does with borders, but I don't want the borders! I can't simulate the layout of the table with borders unless I keep the borders (which I don't want). Any ideas?

A: Did you set the table to border-collapse:collapse;? By nature the default collapse is separate where cells have their own borders. If you set it to collapse they merge and it "looks right"

A: Try to add border-collapse: collapse; to your stylesheet. This seems to fix a lot in your case.
Other than that, I'd suggest you at least use widths for the cells. Different browsers handle cell drawing differently. If you specify a width, you can be more sure the cells align right. When testing your graph, use a inspector tool like Firebug to determine where each cell is located. This will help you a lot.


text:
Q: Jquery Ajax & Google Maps v3 API Markers - a { or ( Hi I have the following function that I am trying to create based on a google example which did not use the ajax method. I'm having a problem with my }'s or )'s I think and I could do with some one just having a look at where I am going wrong as I've been at this for some time now.
The line marked below is been flagged as having a syntax problem although I can not work out what.
Many Thanks all.
Terran
      // http://code.google.com/apis/maps/articles/phpsqlajax_v3.html
      // Change this depending on the name of your PHP file

     function showGetResultkml()
{
     var result = null;
     var scriptUrl = "http://www.kml";
     $.ajax({
        url: scriptUrl,
        type: 'get',
        dataType: 'xml',
        async: false,
        success: function(data) {
            result = data;
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName("marker");

            for (var i = 0; i < markers.length; i++) {
            var name = markers[i].getAttribute("name");
            var address = markers[i].getAttribute("address");
            var type = markers[i].getAttribute("type");
            var point = new google.maps.LatLng(
                parseFloat(markers[i].getAttribute("lat")),
                parseFloat(markers[i].getAttribute("lng")));

            var html = "" + name + "
" + address;
            var icon = customIcons[type] || {};

            var marker = new google.maps.Marker({
                map: map,
                position: point,
                icon: icon.icon,
                shadow: icon.shadow
                                                });

          bindInfoWindow(marker, map, infoWindow, html);
            }
// problem with this bracket
});
// problem with this bracket
}

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }
        }
     });
     return result;
}

A: Fixed:
// http://code.google.com/apis/maps/articles/phpsqlajax_v3.html
// Change this depending on the name of your PHP file

function showGetResultkml()
{
    var result = null;
    var scriptUrl = "http://www.kml";
    $.ajax(
    {
        url: scriptUrl,
        type: 'get',
        dataType: 'xml',
        async: false,
        success: function(data)
        {
            result = data;
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName("marker");

            for (var i = 0; i < markers.length; i++)
            {
                var name = markers[i].getAttribute("name");
                var address = markers[i].getAttribute("address");
                var type = markers[i].getAttribute("type");
                var point = new google.maps.LatLng( parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));

                var html = "" + name + "
" + address;
                var icon = customIcons[type] || {};

                var marker = new google.maps.Marker(
                {
                    map: map,
                    position: point,
                    icon: icon.icon,
                    shadow: icon.shadow
                });

                bindInfoWindow(marker, map, infoWindow, html);
            }
        }
    });

    function bindInfoWindow(marker, map, infoWindow, html)
    {
        google.maps.event.addListener(marker, 'click', function()
        {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);
        });
    }

    return result;
}


text:
Q: PHP SimpleXML has Child How can check if $xml has child "students"?
I'm using SimpleXML to use Xml in php:
$xml = simplexml_load_file('log.xml');

Thanks in advance.

A: You can use a simple isset() call for that
$node = new SimpleXMLElement('<foo><students>test</students></foo>');

var_dump(isset($node->students));

bool(true)

A: if( isset($xml->students) )
   // Do


text:
Q: Why am I getting heap corrpution when I'm not using new or delete? TL;DR: always remember that std::vector needs to move your data around when it grows, which invalidates any pointers you still have floating around.
I've googled around for this problem a bit, and it seems every case I came across was a question of calling delete on the same pointer twice.  I'm writing a small program and I'm getting heap corruption, but the only thing doing heap allocation is the c++ standard library.  I have a hunch I'm leaking a reference to a local variable or done something wrong with polymorphism, but I can't figure it out.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

struct Project;
struct Solution;

struct Line {
    string command;
    vector<string> params;

    void print(ostream &os) {
        os << command << ": ";
        for (string s : params)
            os << s << ' ';
        os << endl;
    }
};

struct Properties {
    vector<string> includes;
    vector<string> libPaths;
    vector<string> libs;
    vector<string> sources;
    vector<string> headers;
    vector<Project *> depends;
    string folder;
    string name;
    string type;
};

struct Project : Properties {
    Project() { built = false; }

    bool built;

    void build() {
        if (built)
            return;
        built = true;

        for (Project *p : depends)
            p->build();

        cout << "Building project: " << name << endl;
    }
};

struct Solution : Properties {
public:
    Project *getProject(const string &name) {
        for (Project &p : projects) {
            if (p.name == name)
                return &p;
        }

        // No project with such a name -- create it
        Project p;
        cout << &p << endl;
        p.name = name;
        projects.push_back(p);
        cout << "Created project: " << name << endl;
        return getProject(name);
    }

private:
    vector<Project> projects;
};

Line parseLine(const string &strline) {
    istringstream stream(strline);
    Line line;

    stream >> line.command;
    while (stream.good()) {
        string tok;
        stream >> tok;
        if (tok.length() > 0)
            line.params.push_back(tok);
    }

    return line;
}

template <typename T>
vector<T> concat(const vector<T> &a, const vector<T> &b) {
    vector<T> vec;
    for (T obj : a)
        vec.push_back(obj);
    for (T obj : b)
        vec.push_back(obj);
    return vec;
}

template <typename T>
void printVector(ostream os, vector<T> v) {
    for (T obj : v)
        os << obj;
    os << endl;
}

int main(int argc, char *argv[]) {
    Solution solution;
    Properties *properties = &solution;
    ifstream stream("testproj.txt");

    Project p[100]; // No error here....

    string linestr;
    for (int lineNum = 1; getline(stream, linestr); lineNum++) {
        Line line = parseLine(linestr);

        if (line.command == "solution") {
            // Make future commands affect the solution
            properties = &solution;
        } else if (line.command == "exe" || line.command == "lib") {
            if (line.params.size() != 1) {
                cerr << "Error at line " << lineNum << endl;
                return 1;
            }

            // Make future commands affect this project
            properties = solution.getProject(line.params[0]);
            properties->type = line.command;
            properties->name = line.params[0];
        } else if (line.command == "includes") {
            properties->includes = concat(properties->includes, line.params);
        } else if (line.command == "libpath") {
            properties->libPaths = concat(properties->libPaths, line.params);
        } else if (line.command == "libs") {
            properties->libs = concat(properties->libs, line.params);
        } else if (line.command == "folder") {
            if (line.params.size() != 1) {
                cerr << "Error at line " << lineNum << endl;
                return 1;
            }

            properties->folder = line.params[0];
        } else if (line.command == "source") {
            properties->sources = concat(properties->sources, line.params);
        } else if (line.command == "header") {
            properties->headers = concat(properties->headers, line.params);
        } else if (line.command == "depends") {
            Project *proj;
            for (string projName : line.params) {
                proj = solution.getProject(projName);
                properties->depends.push_back(proj);
            }
        }
    }
}

The error:
HEAP: Free Heap block 00395B68 modified at 00395BAC after it was freed

Here is my stack trace (sorry no line numbers in the source above):
crashes in malloc & ntdll somewhere up here
libstdc++ ---- incomprehensible name mangling
main.cpp, line 24 (inside Properties::Properties()): (compiler-generated constructor)
main.cpp, line 37 (inside Project::Project()): Project() { built = false; }
main.cpp, line 62 (inside Solution::getProject()): Project p;
main.cpp, line 150 (inside main()): proj = solution.getProject(projName);

It seems to be crashing in the default constructor for Properties?  Perhaps while constructing a vector?
Edit:
The input file, if it would help:
solution
    includes deps/include deps/include/SDL2
    libpath deps/lib
    libs opengl32 glu32 SDL2main SDL2 libpng16 glew

exe game
    folder game
    source main.cpp
    depends render common

lib render
    folder render
    source Shader.cpp
    header TODO
    depends common

lib common
    folder common
    source util.cpp
    header TODO

A: This is a lot of code, but one strong possibility is that you are de-referencing one of the pointers returned by getProject, but this has been invalidated because the vector projects, that holds the objects pointed to, has performed a re-allocation. This invalidates all pointers, references and iterators.
When you do this:
projects.push_back(p);

projects may need to grow, which results in a re-allocation and the invalidation of pointers mentioned above.
Without looking into the code in any depth, it looks like you can implement Solution quite trivially by using an std::map:
struct Solution : Properties
{
public:
    // Check for project with name "name"
    // Add one if it doesn't exist
    // return it
    Project& getProject(const std::string& name)
    {
      if (!projects.count(name))
      {
        projects[name].name = name;
      }
      return projects[name];
    }

    // Return project with name "name" or raise exception
    // if it doesn't exist
    const Project& getProject(const string &name) const
    {
      return projects.at(name);
    }
private:
    std::map<std::string, Project> projects;
};


text:
Q: Could not load JDBC driver class - Spring Batch standalone program I'm working on a Spring Batch program, running it as a command-line app (currently via STS for testing).  When I run it via the Eclipse run/debug configuration via the org.springframework.batch.core.launch.support.CommandLineJobRunner, it cannot load the SQL Server JDBC driver.  I'm certain I have it on the classpath, but evidently it is still having issues.
Here is my exception trace from the console log:
09:11:59.291 [main] ERROR o.s.b.c.l.s.CommandLineJobRunner - Job Terminated in error: Error creating bean with name 'legacyDatasource' defined in class path resource [META-INF/spring/module-context.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.microsoft.jdbc.sqlserver.SQLServerDriver]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'legacyDatasource' defined in class path resource [META-INF/spring/module-context.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.microsoft.jdbc.sqlserver.SQLServerDriver]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1506) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.batch.core.launch.support.CommandLineJobRunner.start(CommandLineJobRunner.java:290) [spring-batch-core-3.0.2.RELEASE.jar:3.0.2.RELEASE]
    at org.springframework.batch.core.launch.support.CommandLineJobRunner.main(CommandLineJobRunner.java:590) [spring-batch-core-3.0.2.RELEASE.jar:3.0.2.RELEASE]
Caused by: org.springframework.beans.PropertyBatchUpdateException: Failed properties: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.microsoft.jdbc.sqlserver.SQLServerDriver]
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:121) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:75) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1502) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
    ... 14 common frames omitted

My datasource config from the spring xml (details changed to protect the innocent of course):
<bean id="legacyDatasource" class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
  <property name="driverClassName" value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />
  <property name="url" value="jdbc:microsoft:sqlserver://server:1433;DatabaseName=database" />
  <property name="username" value="user" />
  <property name="password" value="pw" />
</bean>

Now to the classpath stuff...installed in my local maven repo:

And in my pom:
<dependency>
  <groupId>com.microsoft.sqlserver</groupId>
  <artifactId>sqljdbc41</artifactId>
  <version>4.1</version>
</dependency>

And it's in my project's Maven Dependencies:

In my run config, I've tried adding it directly to the classpath on the classpath tab, and through the VM argument.

I'm pretty sure it's something simple.  Any ideas why the driver cannot be loaded?  To me it's also worth noting that it's not a class not found error (though it may be under the covers and not part of this stack trace).

A: Had jdbc & sqlserver transposed in the package name.
<bean id="legacyDatasource" class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
  <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
  <property name="url" value="jdbc:sqlserver://server:1433;DatabaseName=database" />
  <property name="username" value="user" />
  <property name="password" value="pw" />
</bean>


text:
Q: Changing the font in XScreensaver's dialogs? I decided to build XScreensaver from source recently after realizing my distribution had a slightly outdated build in the repo. Everything is great except for the dialog boxes, which have a humungous, awful, Papyrus like font.
I'm told that I can edit a file titled ".Xdefaults", but that file doesn't exist. Nor does .Xresources, which supposedly does the same thing. Apparently if I don't have one that I need to create it myself. But if one doesn't exist, then where is the program getting this font from? I feel like creating an .Xdefaults file wouldn't solve the problem here. I tried editing the source code to change the font but it seems like the program just ignores any changes I make to the font names and keeps the font.

I'm using Elementary OS. I'm told xscreensaver doesn't work well with eOS, but since the version I downloaded from the package manager has a different font, I beg to differ.

A: X resources come from several places; the first place is the database inside the X server and managed with, e.g., xrdb. Typically ~/.Xresources (if it exists) will be loaded into the X server by your distro's X login scripts — using xrdb. ~/.Xdefaults servers a similar purpose.
The fallback (before compiled-in defaults) is the app defaults files. I'm not entirely sure where they're located on Elementary OS, but on Debian they're in /etc/X11/app-defaults — in particular, take a look at /etc/X11/app-defaults/XScreenSaver. Another possible location is /usr/lib/X11/app-defaults/XScreenSaver.
BTW: XScreenSaver probably uses traditional X font naming, not modern Fontconfig naming. Which also may mean not all fonts are available. xfontsel can be used to get the traditional X font name (and find a font you like).


text:
Q: Angular Uploading a pdf file wih a local path In my code, I want the user to be able to write a PDF path to a text box, for example like "\\Server\\Stability\202606\\file1.pdf" and I also want him to be able to click open button and open the PDF file using this path. Here is my code, I can't figure out the way to do it. What should I do?
<ng-container matColumnDef="FilePath">
                                 File Path

                                    {{row.LabAnalysisFiles.FilePath}}
                                    <mat-form-field floatLabel="never" *ngIf="EditIndex == i" class="w-100-p">
                                        <input matInput name="FilePath" [(ngModel)]="row.LabAnalysisFiles.FilePath" type="text">
                                    </mat-form-field>

                                            <button mat-icon-button matTooltip="Open" [disabled]="!isValid">
                                            <mat-icon>open_in_browser</mat-icon>
                                        </button>


text:
Q: Let $\,u,v,x,y\,$ be real numbers. Prove that $ux+vy\leqslant\sqrt{u^2+v^2}\!\cdot\!\sqrt{x^2+y^2}$ I am unsure how to go about this. This is a question for a mathematical proofs class at my University and the only proofs we have been exposed to so far are direct, contrapositive, and contradictory proofs. I tried squaring both sides but that seemed futile. I also tried proof by contradiction but it didn't seem to work. Any nudge in the right direction would be helpful.

A: $ux\!+\!vy\leqslant\big|ux\!+\!vy\big|=\!\sqrt{\left(ux\!+\!vy\right)^2}\leqslant\!\sqrt{\left(ux\!+\!vy\right)^2\!+\!\left(uy\!-\!vx\right)^2}\!=$
$=\sqrt{u^2x^2+v^2y^2+u^2y^2+v^2x^2}=\sqrt{\left(u^2+v^2\right)\!\!\cdot\!\!\left(x^2+y^2\right)}=$
$=\sqrt{u^2+v^2}\!\cdot\!\sqrt{x^2+y^2}\,.$

A: This is the the Cauchy-schwartz inequality in $\mathbb{R^2}$ with the euclidean product.
In this particular case, there is a geometric proof based on this figure (from Wikipédia) :

Otherwise you can look for any proof of CS inequality on the internet. Consider the polynomial of variable $t$ denoted by $P(t) = (x+tu)^2+(y+tv)^2 = (x^2+y^2)+2t(xu+yv)+t^2(u^2+v^2)$ and show that its discriminant is negative.
There is probably a more elementary approach for this particular case.


text:
Q: Clients Not Working With Offline Ubuntu 16.04 Repository I have followed the instructions to install a local repository for a segregated network.  I apt-mirror to a local drive, rsynce to and external, then 'sneakernet' to the segregated networ.  I can see the files when I go to http://inside-server/ubuntu.  I've also updated two clients to point to the inside-server for the xenial files.  One of these is the actual repo server.
The sources.list has:
deb http://inside-server/ubuntu xenial main restricted multiverse

I tried a few permutations of this line that I have found.  However, I always get this error:
# apt update
Ign:1 http://inside-server/ubuntu xenial InRelease
Err:2 http://inside-server/ubuntu xenial Release
  404  Not Found
Reading package lists... Done
E: The rpository 'http://inside-server/ubuntu xenial Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
#

I've spent three days googling and reading but the 'normal' directions all say my installation should just work.  I looked at creating a key.  That became involved and seemed out of the norm.  My segregated network is trusted, so I looked at allowing an unauthenticated repository on the client.  However, the man page for apt-secure points to apt.conf which is broken out in 16.04.  I haven't yet found a clear example on what to change.
So, I'm punting.  Anyone have any ideas?

A: Well, after taking a very conservative approach, I started hacking on the internal repo.  My problem was I had linked the wrong path to http://inside-server/ubuntu.
The apt-mirror command clones more that what is needed to host a mirror.  The actual path is /mirror/ubuntu.archive.com/ubuntu.


text:
Q: Multiple acf plot in one ggplot. I plot two acf in R with follow code, how can make the same plot in ggplot, I try to use geom_area,but I could not get same one.
data1 <- seq(1, 3000, 3)
data2 <- seq(1, 1000, 0.5)
acf(data2, plot = T, lag.max = 300,col=2,ylim=c(0,1))
par(new=TRUE)
acf(data1, plot = T, lag.max = 300,col=1,ylim=c(0,1))

A: You can try below approach,
library(ggplot2)
library(reshape2)
data1 <- seq(1, 300, 3)
data2 <- seq(1, 100, 0.5)
acf1 <- acf(data1, plot = F, lag.max = 25)
acf2 <- acf(data2, plot = F, lag.max = 25)
df<- data.frame(lag = acf1$lag,acf1=acf1$acf,acf2=acf2$acf)
colnames(df)<-c("lag","data1","data2")
data<-melt(df,id="lag")

GGPLOT with area
ggplot(data=data[data$variable=="data2",], aes(x = lag, y = value,
             fill = variable)) + geom_area(position = "dodge") +
  geom_area(data=data[data$variable=="data1",],
           aes(x = lag, y = value, fill=variable), position = "dodge")

GGPLOT with bar
ggplot(data=data[data$variable=="data2",], aes(x = lag, y = value,
                                               fill = variable)) + geom_col(position = "dodge") +
  geom_col(data=data[data$variable=="data1",],
            aes(x = lag, y = value, fill=variable), position = "dodge")

You have below graphs from both the approaches
:


text:
Q: Why can't gcc reduce the alignment of a struct to be lesser than that of one of its individual fields I have a struct definition employee that instantiates monica. The struct looks like this
struct __attribute__((aligned(2))) employee {
    int salary; // 4 bytes
    int age; // 4 bytes
} monica;

As you can see, I have forced the alignment of the struct to be 2 but gcc does not set the alignment of the struct to 2, nor does it throw an error. I tried to print the alignment of the struct using the alignof macro(include <stdalign.h>) which returns 4 as the alignment of the struct. Why can't gcc set the alignment of a struct to value that is less than the largest alignment of one of its fields.
I tried to reproduce the issue by additionally adding a pointer as a field in the struct. On adding the pointer as a field, I noticed that gcc does not allow me to reduce the alignment below 8 using __attribute__((aligned(x))).
GCC allows me to set the alignment of the struct to 1 by using __attribute__((packed)) but it still does not allow me to set the alignment to 1 by using __attribute__((aligned(1))). Why is this happening?
gcc x86 v7.1.1

A: The GCC documentation says:

… When used on a struct, or struct member, the aligned attribute can only increase the alignment; in order to decrease it, the packed attribute must be specified as well…

That is from the GCC 11.2 documentation. You can check older documentation. There is none for 7.1 at that site; it jumps from 6.5 to 7.5, but I expect it is the same in this regard.


text:
Q: How do I throw an exception if an element is present that shouldn't be I am using XmlReader.  I am basically going through an if statement reading each element if it's present.  If I come across an element that shouldn't be there I want to throw an XmlException.  Then I have an else basically saying if we have already read all of the elements and there aren't any that don't match what we are looking for close the element that all of these other elements are wrapped inside of.  Everthing is working except for the checking for an invalid or unrecognized element.
public void ReadXml(XmlReader reader)
        {
            if (reader.IsStartElement("job"))
            {
                //
                // Get the values of all the <job> attributes
                //
                JobName = reader.GetAttribute("name");
                MethodName = reader.GetAttribute("method");

                //
                // Read past <job>
                //
                reader.Read();

                //
                // We could have (in any order):
                //   <Description></Description>
                //   <Source></Source>
                //   <Properties></Properties>
                //   <Elements></Elements>
                //
                while (true)
                {
                    if (reader.IsStartElement("description"))
                    {
                        Description = reader.ReadElementContentAsString();
                    }
                    else if (reader.IsStartElement("source"))
                    {
                        Source = reader.ReadElementContentAsString();
                    }
                    else if (reader.IsStartElement("properties"))
                    {
                        Properties.ReadXml(reader);
                    }
                    else if ((reader.IsStartElement("elements")) && (!reader.IsEmptyElement))
                    {
                        Elements.ReadXml(reader);
                    }
                    else if ((reader.IsStartElement("parameters")) && (!reader.IsEmptyElement))
                    {
                        Parameters.ReadXml(reader);
                    }
                    else if (((!reader.IsStartElement("description"))
                        && (!reader.IsStartElement("source"))
                        && (!reader.IsStartElement("properties"))
                        && (!reader.IsStartElement("elements"))
                        && (!reader.IsStartElement("parameters"))
                        && (!reader.IsStartElement("job"))))
                    {
                        throw new XmlException("Unexpected element was present");
                    }
                    else
                    {
                        reader.MoveToContent();
                        reader.ReadEndElement();
                        break;
                    }
                }
            }
            else
            {
                throw new XmlException("Expected <job> element was not present");
            }
        }

The part that is breaking is this code below.  It goes inside of this if statement everytime and throws and exception.
else if (((!reader.IsStartElement("description"))
     && (!reader.IsStartElement("source"))
     && (!reader.IsStartElement("properties"))
     && (!reader.IsStartElement("elements"))
     && (!reader.IsStartElement("parameters"))
     && (!readerE("job"))))
{
    throw new XmlException("Unexpected element was present");
}

A: The ideal way of doing this is to validate the XML against an XSD (XML schema) as provided by the System.Xml.Schema namespace. Further info and examples can be found on the applicable MSDN pages Here
Example from MSDN :
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", "CustomersOrders.xsd");

Console.WriteLine("Attempting to validate");
XDocument custOrdDoc = XDocument.Load("CustomersOrders.xml");
bool errors = false;
custOrdDoc.Validate(schemas, (o, e) =>
                 {
                     Console.WriteLine("{0}", e.Message);
                     errors = true;
                 });
Console.WriteLine("custOrdDoc {0}", errors ? "did not validate" : "validated");

A: It is probably worth pointing out that the recommended practice when validating xml is to use a schema.
See the following : XML Schema (XSD) Validation with XmlSchemaSet

A: I found that XmlReader reader contains a method for IsName(string).  It is static.  So since I could add IsEndElement to the condition because XmlReader doesn't contain this method, I was able to add XmlReader.IsName("job") to bypass the ending job element tag.
else if (((!reader.IsStartElement("description"))
                        && (!reader.IsStartElement("source"))
                        && (!reader.IsStartElement("properties"))
                        && (!reader.IsStartElement("elements"))
                        && (!reader.IsStartElement("parameters"))
                        && (!XmlReader.IsName("job"))))
                    {
                        throw new XmlException("Unexpected element was present");
                    }


text:
Q: How to speed up Ubuntu 12.04 I am using Ubuntu 12.04 and my system is too much slow, I want to speed it up. I have tried several apps and methods like jupitar, cleaning tmp file, but still my system is too much slow.
Here is my sys config: 1gb RAM 160gb hdd intel duo core

A: Try using LXDE. It is lighter than Unity (the default DE) and will speed up your computer.
For 12.04 and later versions, you'll need to do this through a terminal.
Open up a terminal (Super, then type Terminal into the dash), then run the following:
sudo apt-get update && sudo apt-get install lubuntu-desktop
Or install via the Software Center:

You will get asked to enter your password, and you will also be asked to choose between LightDM and LXDM - I suggest using LightDM.
Once that is done, log out, and then select Lubuntu as your desktop session:

A: You can speed up your ubuntu system using this 4 triks. It might be useful to you:
4 Tricks to speed Up Ubuntu 14.X - I am Programmer


text:
Q: NIToolBarPhotoViewController to display images from a selected image I am using Nimbus to display photos. I have a tableviewcontroller displaying list of filenames. When the user select particular file (if an image) , it displays all the image files in viewcontroller extended from NIToolBarPhotoViewController starting fromt the first element of my photo source array i.e. photoFiles which is the first element in list.
I am returning the total count for scrollview pages like this:
- (NSInteger)numberOfPagesInPagingScrollView:(NIPhotoAlbumScrollView *)photoScrollView {
    return self.photoFiles.count;
}

However, I am unable to launch the photoview from a particular index as the method:
  - (UIImage *)photoAlbumScrollView: (NIPhotoAlbumScrollView *)photoAlbumScrollView
                     photoAtIndex: (NSInteger)photoIndex
                        photoSize: (NIPhotoScrollViewPhotoSize *)photoSize
                        isLoading: (BOOL *)isLoading
          originalPhotoDimensions: (CGSize *)originalPhotoDimensions

gets called directly as per the example NetworkPhotoAlbumViewController. How can I get it to take the particular index before launch the photoview?

A: in viewDidLoad add this line
[self.photoAlbumView setCenterPageIndex:photoIndex];

to set index of displayed photo


text:
Q: mbed combining two programs I am trying to get my board connected to ethernet to do so I am using the code Nucleo_F746ZG_Ethernet this code uses an outdated version of mbed, but as soon as I update it it stops working.
In my own made code I use the newest version of mbed that I need for a few functions.
My question is, can I combine these two into a new code that performs both tasks on different versions of mbed and how would I do so?

A: I used a different library to assist me in this matter.
https://os.mbed.com/teams/ST/code/mbed-os-tcp-server-example/
This one does work for what i use but i cant set the ip address for my board.
besides this you can create an web interface with it also.


text:
Q: Trying to add polymorphism to template function So yeah, you can't have a template virtual class member function. That makes sense, not trying to figure that part out...and I'm trying like the devil to avoid multiple/virtual inheritance.
I've got a a template class A, and an abstract template class B that inherits from A, and a C that inherits from B.
template <typename T>
class A
{
protected:
   T val;
public:
   A(T a) {val = a;}
   T val() {return val();}

   template <typename J>
   A<J> cast_as() { return A<J>((J)val); }
};

template <typename T>
class B : public A<T>
{
protected:
  int b;
public:
   B(T a) : A(a){b=10*a;}
   virtual foo() = 0;
   //and I'd like, but this can't exist
   //template <typename J>
   //B<J>* BCastAs();

};

template <typename T>
class C : public B<T>
{
protected:
  int c;
public:
  C(T c) : B(c) { c=c+1;}
  virtual foo() override { cout << (a+b+c);}
};

int main() { C<int> c(10); B<double>* b = c.BCastAs<double>();}

And I can't think of any way to do that...It feels like it should be possible, as B* does not need to actually know that it is a C (much like the return of a clone call) but i don't know a way to get the c to move over correctly without having virtual template member functions, which is impossible.

A: The sample code you've posted looks like a having a serious design flaw to me at first glimpse.
Usually it's not necessary to have virtual functions in class templates, because you can use a CRT pattern to avoid them.
You make up the intention that you require inherited classes (this is how you make a template 'abstract'), that implement a defined interface. The interface may or (preferably) not be defined as pure virtual methods (a static interface check would do as well and cause less mysterious compiler error messages in case of missing method implementations).
You can see a sample of such template framework and how to use this technique in my STTCL template library.
In short: Use static polymorphism.
UPDATE:
And yes, I'm also using pure virtual methods in STTCL, but in a completely different manner (just as basic entry points to couple complete sets of inheritance hierarchies).


text:
Q: how to pass Sql parameter This error will come in my code  Procedure or function 'gridalldata' expects parameter '@order_no', which wast not supplied. I am sending parameter to procedure like below
try
{
    con.Open();

    SqlCommand cmd = new SqlCommand("gridalldata", con);
    cmd.Parameters.Add("@order_no", SqlDbType.NVarChar).Value = txt_orderno.Text;

    SqlDataReader dr = cmd.ExecuteReader();

    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        if (dr.HasRows)
        {
            dr.Read();

            dataGridView1.Rows[i].Cells[0].Value = dr[0].ToString();

            dataGridView1.Rows[i].Cells[2].Value = dr[2].ToString();
            dataGridView1.Rows[i].Cells[3].Value = dr[3].ToString();
            dataGridView1.Rows[i].Cells[4].Value = dr[4].ToString();
            dataGridView1.Rows[i].Cells[5].Value = dr[5].ToString();
            dataGridView1.Rows[i].Cells[6].Value = dr[6].ToString();
            dataGridView1.Rows[i].Cells[7].Value = dr[7].ToString();
            dataGridView1.Rows[i].Cells[8].Value = dr[8].ToString();
            dataGridView1.Rows[i].Cells[9].Value = dr[9].ToString();
            dataGridView1.Rows[i].Cells[10].Value = dr[13].ToString();
            dataGridView1.Rows[i].Cells[11].Value = dr[12].ToString();
        }

    }
    dr.Close();
    con.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
finally
{
    con.Close();
}

How To Fix This

A: Use cmd.CommandType = CommandType.StoredProcedure; to execute stored procedure.

A: Try This:
    Try
       {
         con.Open();
            string order= txt_orderno.Text;

            SqlCommand cmd = new SqlCommand("gridalldata", con);
               cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@order_no", SqlDbType.NVarChar).Value=order;

            SqlDataReader dr = cmd.ExecuteReader();
             for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
            if (dr.HasRows)
            {
                dr.Read();

                dataGridView1.Rows[i].Cells[0].Value = dr[0].ToString();

                dataGridView1.Rows[i].Cells[2].Value = dr[2].ToString();
                dataGridView1.Rows[i].Cells[3].Value = dr[3].ToString();
                dataGridView1.Rows[i].Cells[4].Value = dr[4].ToString();
                dataGridView1.Rows[i].Cells[5].Value = dr[5].ToString();
                dataGridView1.Rows[i].Cells[6].Value = dr[6].ToString();
                dataGridView1.Rows[i].Cells[7].Value = dr[7].ToString();
                dataGridView1.Rows[i].Cells[8].Value = dr[8].ToString();
                dataGridView1.Rows[i].Cells[9].Value = dr[9].ToString();
                dataGridView1.Rows[i].Cells[10].Value = dr[13].ToString();
                dataGridView1.Rows[i].Cells[11].Value = dr[12].ToString();
                }

                }
            dr.Close();
            con.Close();

        }

A: using (SqlConnection connection = new SqlConnection(connectionString))
 {
    connection.Open();
    String orderNo=txt_orderno.Text;
    // Am assuming gridalldata is your SP
    SqlCommand cmd= new SqlCommand(gridalldata, connection);
    cmd.CommandType=CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@order_no", orderNo);
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
      // Code
    }
 }

The using statement makes sure the connection is closed after use
Also You should bind Your Datagridview like this
Public DataTable FillDataGrid(string orderID)
{

SqlCommand cmd = new SqlCommand("gridalldata", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@order_no", orderNo);
        SqlDataAdapter dap = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        dap.Fill(ds);
        return ds.Tables[0];

}

Datatable dt=FillDataGrid(txt_orderno.Text);
DataGridVIew1.DataSource=dt;


text:
Q: Microsoft Graph and Partner Center in the same api gran I am looking to create a login that verifies a user account via the graph api and also verifies they are a microsoft partner via the partner api. I can easily get one grant or the other but can't seem to get both to work in one grant. I would rather not force the user to approve two different app approval boxes.
Is this possible:
scope=https%3A%2F%2Fapi.partnercenter.microsoft.com/user_impersonation%20https%3A%2F%2Fgraph.microsoft.com/openid+profile+email

A: as per the limitations of azure ad, I don't believe you can request multiple scopes from different external resources like you're doing there. you will have to do two different requests. the token should stack with the resources, but you cannot call them both in one go. so no, that scope= you provided probably won't work or will only return the first scope.
Similar type question for reference.
https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1390


text:
Q: Another question on changing measure Now asked and bountied at Mathoverflow.

This question is a follow-up to this one, to which hot_queen gave an excellent answer. Briefly, the original question is whether the (outer Lebesgue) measure of a set of reals can change without becoming zero when we pass from one model to a larger one. Hot_queen observed that we can achieve this by killing half of the starting set if it is built appropriately (that is, out of two pieces such that we can make one null while keeping the other non-null).
In some sense, though, this isn't totally satisfying. So the following seems a natural follow-up question:

Can we have a pair of transitive models $M\subseteq N$ of ZFC with some $A\in\mathcal{P}(\mathbb{R})^M$ such that there are no sets $B,C\in M$ with

*

*$A=B\cup C$,

*$\mu^*(B)^N=0$, and

*$\mu^*(C)^N=\mu^*(C)^M$?

A good first step towards a negative answer would be ruling out the following extreme situation: a pair of transitive models $M\subseteq N$ where $(i)$ the outer measure of some set of reals in $M$ changes when we go to $N$ but $(ii)$ every non-$M$-null set is non-$N$-null. That's so ridiculous it has to be impossible ... right?
Meanwhile, on the positive side I'd be excited (if not fully satisfied) by a pair of models of a subtheory of ZFC (although I'd rather not go below ZF).

Incidentally, it's known that even the original situation can't happen for $A$ measurable; see here (it's stated there for forcing extensions specifically but that's not actually used).