text:
Q: Laravel - How to take first name and last name from separate fields and store them in name column in db? So I used php artisan make:auth in my project and I am building on top of that. Problem is it has only "name" field and not "firstName" and "lastName" field. Where do I configure those options? I want to take the input from first name and last name and concatenate them with a space between them, then store them as name in my db. Where is the place to do that? Where do I configure my options like if I want to add an address or phone number for my user? I researched a lot and I am really confused with all those traits so please could someone give me some advice on how to proceed with user authentication?

A: For use name instead of first_name and last_name open database/migration/create_user_table
write
$table->string('name');
instead of
$table->string('first_name');
$table->string('last_name');

After that open app/Http/Controller/Auth/AuthController.php and then put your code like that
protected function create(array $data)
    {
        return User::create([
            'name' => $data['first_name'].' '.$data['last_name'],
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }

if you want to use more fields,write those fields in migration file which is on database/migration and then use those fields in resources/views/auth/register.blade.php that files's html form,and after that change AuthController.php file

A: According to the documentation, you can modify the AuthController class in the create method to set which fields are used to create new users.
However, I'd like to ask you to reconsider requiring both fields. Is it really necessary? Does your design spec require it? W3C recommends a single "name" field for better user experience. I understand that some apps will require both, for things like human resources and accounting purposes, but this is worth considering. General consumer type users desire easier forms, so ask as little as possible of your user.


text:
Q: Grunt Configuration Issue I have a grunt task to concatenate all js files in to one.The configurations is like below.
concat:{
      options: {
        separator: ';'
      },
      dist:{
        src:['src/**/*.js'],
        dest: 'dist/<%= pkg.name %>.js'
      }
    }

The problem is that it is concatenating the test files also which is not required. The test files are having names like "*Spec.js". For example I am having a js file like test.js, then its test file will be like testSpec.js. How Can i exclude them while concatenating the js files?

A: Since all your test files have prefix "test", you can ignore files using ! (negate):
// All files except for bar.js, in alpha order:
{src: ['foo/*.js', '!foo/bar.js'], dest: ...}

So your code should be like:
   concat:{
      options: {
        separator: ';'
      },
      dist:{
        src:['src/**/*.js', '!src/**/test*.js'],
        dest: 'dist/<%= pkg.name %>.js'
      }
    }

This will ignore all the files which has a prefix "test".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using VBA with the "selection" of non-active worksheets Sorry for a potential "bad" title, I wasn't sure how to phrase it. Feel free to edit if you have a better wording.
This is a follow-up on a previous question. As far as I researched there is no solution but maybe I overlooked something.
In a workbook with more then worksheet if I change the selection of the active worksheet (manually or via VBA) the selected range of the non-active sheets won't be affected, so the value must be stored somehow.
Using "the regular commands" (set range = selection, range.select, etc.) requires the cosponsoring sheets to be active. This makes sense since the selection, select etc. applies to the "currently active selection".
But still, the "selection" of non active sheet must be stored somewhere. Is there a way to get those values or even manipulate them?
Appendix1: I thought this was implied: I don't want to change the active sheet (otherwise I could just use the regular select commands).
Appendix2:  It's not just about what you see on the screen. I want to avoid activating a different sheet so I don't have to have to handle the activation of the initially activated sheet altogether - this is my current solution (instead I want sort of a "true" separation of view and controller). I don't think the "regular" API will provide this, but I though there might be some other work around. But thanks for your suggestion anyway.

A:
But still, the "selection" of non active sheet must be stored somewhere. Is there a way to get those values or even manipulate them?

@Pᴇʜ already has given you 1 way. Here are two ways I can think of.

*

*Way 1: Loop through the sheets, activate them and then get the Selection.Address. I have not done error handling so you will have to use If TypeName(Selection) <> "Range" Then to handle situations if say a shape is selected.

*Way 2: Create a copy of the current excel file in user temp directory. Rename it to .Zip. Unzip the zip file. Next go to xl\worksheets folder in the zip file and loop through each Sheets.xml file. Extract the relevant detail from there.

Easy Way (Way 1)
Option Explicit

Sub WayOne()
    Dim ws As Worksheet
    Dim msg As String

    For Each ws In ThisWorkbook.Worksheets
        If ws.Visible = xlSheetVisible Then
            ws.Activate

            msg = msg & vbNewLine & ws.Name & " -- " & Selection.Address
        End If
    Next ws

    Msgbox Mid(msg, 2)
End Sub

Alternative Way (Way 2) Not completely tested
Option Explicit

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long

Private Const MAX_PATH As Long = 260

Sub Way2()
    Dim thisFileName As String
    Dim FileNameFolder As String
    Dim oldFileName As String
    Dim newFileName As Variant
    Dim UnzipFolder As String
    Dim tmpName As String

    '~~> Get a unique mame for the temp folder and zip file
    tmpName = Format(Now, "ddmmyyyyhhmmss")

    '~~> Get this workbooks name
    thisFileName = ThisWorkbook.Name

    '~~> Temp folder
    FileNameFolder = TempPath & tmpName

    '~~> Make the folder
    MkDir FileNameFolder
    DoEvents

    '~~> Folder to unzip files in the above folder
    UnzipFolder = FileNameFolder & "\UnzipFolder"

    '~~> Make the folder
    MkDir UnzipFolder
    DoEvents

    '~~> Name of file with which the current file will saved
    oldFileName = FileNameFolder & "\" & thisFileName
    '~~> Name of the zip file
    newFileName = FileNameFolder & "\" & tmpName & ".zip"

    '~~> Save a copy of this folder
    ThisWorkbook.SaveCopyAs (oldFileName)
    DoEvents

    '~~> Rename the file
    Name oldFileName As newFileName

    '~~> Unzip the files
    Dim oApp As Object
    Set oApp = CreateObject("Shell.Application")
    oApp.Namespace(UnzipFolder & "\").CopyHere oApp.Namespace(newFileName).items

    '~~> Identify our working folder
    Dim Workingfolder As String
    Workingfolder = UnzipFolder & "\xl\worksheets\"

    Dim StrFile As String
    StrFile = Dir(Workingfolder & "\*.xml")

    Dim MyData As String
    Dim SheetName As String
    Dim rngaddr As String

    '~~> Loop through the xml files to extract relevant details
    Do While Len(StrFile) > 0
        Open Workingfolder & StrFile For Binary As #1
        MyData = Space$(LOF(1))
        Get #1, , MyData
        Close #1

        '~~> Get Sheet name
        SheetName = GetValue(MyData, "N")
        '~~> Get Range address
        rngaddr = GetValue(MyData, "R")

        Debug.Print SheetName & " - " & rngaddr
        StrFile = Dir
    Loop

    '~~> Cleanup. Delete the temp folder
    Dim FSO As Object
    Set FSO = CreateObject("scripting.filesystemobject")
    FSO.deletefolder FileNameFolder
End Sub

Private Function GetValue(dat As String, opt As String) As String
    Dim Delim As String
    Dim tmpValue As String

    If opt = "N" Then
        '~~> For sheet name
        Delim = "<sheetPr codeName="""
    Else
        '~~> For multiple cell address
        Delim = "<selection sqref="""
        If InStr(1, dat, Delim) = 0 Then
            '~~> For Single cell address
            Delim = "<selection activeCell="""
        End If
    End If

    If InStr(1, dat, Delim) Then
        tmpValue = Split(dat, Delim)(1)
        tmpValue = Split(tmpValue, Chr(34))(0)
    Else
        tmpValue = "A1"
    End If

    GetValue = tmpValue
End Function

'~~> Get user temp path
Function TempPath() As String
    TempPath = String$(MAX_PATH, Chr$(0))
    GetTempPath MAX_PATH, TempPath
    TempPath = Replace(TempPath, Chr$(0), "")
End Function

In Action

A: I guess this is only possible with a workaround, because per definition Selection only exists once in Excel, because it is Application.Selection and we have no access to the hidden value were Excel remembers this for each worksheet.
Write into ThisWorkbook scope:
Option Explicit

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
    SaveAddress Selection
End Sub

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    SaveAddress Target
End Sub

Write into a module:
Option Explicit

Public SelectionAddresses As Object

Public Sub SaveAddress(ByVal Target As Range)
    On Error GoTo CREATE_DICTIONARY

    If SelectionAddresses.Exists(Target.Parent.Name) Then
        SelectionAddresses(Target.Parent.Name) = Target.Address
    Else
        SelectionAddresses.Add Target.Parent.Name, Target.Address
    End If

    Exit Sub
CREATE_DICTIONARY:
    If Err.Number = 91 Then
        Set SelectionAddresses = CreateObject("Scripting.Dictionary")
        InitializeAddresses
        Resume
    Else
        Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
    End If
End Sub

Public Sub ListAddresses()
    Dim Key As Variant
    For Each Key In SelectionAddresses
        Debug.Print Key, SelectionAddresses(Key)
    Next Key
End Sub

Public Sub InitializeAddresses()
    Dim ActWs As Worksheet
    Set ActWs = ActiveSheet
    Application.ScreenUpdating = False
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        ws.Activate
    Next ws

    ActWs.Activate
    Application.ScreenUpdating = True
End Sub

Public Function GetSelectionAddressOfSheet(ByVal SheetName As String) As String
    On Error GoTo NOT_FOUND
    If SelectionAddresses.Exists(SheetName) Then
        GetSelectionAddressOfSheet = SelectionAddresses(SheetName)
    Else
        GoTo NOT_FOUND
    End If

    Exit Function
NOT_FOUND:
    GetSelectionAddressOfSheet = "not found" 'or vbNullString
    On Error GoTo 0
End Function

This will save the selection address of every sheet into a dictionary SelectionAddresses where you can then read it from. Eg with
Debug.Print GetSelectionAddressOfSheet("Sheet2")

You might want to use an additional
Private Sub Workbook_Open()
    InitializeAddresses
End Sub

So the dictionary gets initialized immediately after opening the workbook.


text:
Q: How to send Email through a C++  program? How can I send an email from C++? Is there a good cross-platform (MS Windows, Linux etc) library that I can use? I'm using GCC (cygwin on MS Windows).

A: Check out C-Client

*

*Apache license

*Very established library ( makers of Pine email reader, UW-IMAP Server, etc. )

*Supports IMAP, POP, SMTP, and NNTP

*Unix and Windows

A: Look at VMime.

VMime is an all-in-one Internet mail library. This well designed, powerful C++ class library allows you to parse/build/modify MIME messages. With the messaging module, you can connect to POP3/IMAP/SMTP/Maildir very easily, and with the same code!

A: Check out jwSMTP - a cross-platform SMTP class.
http://johnwiggins.net/jwsmtp/


text:
Q: How to target only the index page with jQuery/javascript? What I did is actually I added some fade in effects for several divs with css3. At first it looks nice, but when you start browsing through the site it becomes annoying to see this effect so I decided not to get rid of the animations, but to leave it only for the main page. So, actually I have this jQuery code:
if (it is www.mydomain.com, but not www.mydomain.com/aaaa (or anything) ) {
$("#header").addClass("class1 class2 class3");

} else {
$("#header").removeClass("class1 class2 class3");
}

How to check if there is anything after mydomain.com/... or you can come up with a better solution?
I cant do this with css as I will be adding content to header.php file which is necessery for all of the pages.

A: Assuming you're index page has a pathname of /, and that other pages have a pathname that is longer than one letter, you could do:
if (document.location.pathname.length > 1) {
     //do something
}

Or if your index page has a certain element that the other pages does not have, you can do:
if ($("#elementID").length) {
     //do something
}

or if you do :
<body class="index">

in your html, you can do:
if ($('body').is('.index'))  {
     //do something
}

A: You could check for URI
or
Make an index specific include for that javascript.
Second option way cleaner IMO.


text:
Q: Change url in address bar via htaccess I want to change my URLs in my website. I have tried some stuff after going through articles but no help.
What I want is displayed below:
Original Url: abc.com/en/test/index/abc
User written Url: abc.com/en/abc
Thanks in advance.

A: Are you using Codeigniter ,Just use the URI Routing
$route['blog/joe'] = "blogs/users/34";

A URL containing the word "journals" in the first segment will be remapped to the "blogs" class
Just place the bellow line in to your application\config\routes.php file end of the line
$route['en/abc'] = "en/test/index/abc";

It can be work fine :) :) :) :) :) :)
More details visits   https://ellislab.com/codeigniter/user-guide/general/routing.html


text:
Q: Are there magic commit words in Launchpad Code? I know in a lot of source control tracking systems (Redmine, Trac, Jira) you can add magic words like resolves #1234 in your commit message to have the bug updated to a certain status. Is there a feature like this with Launchpad - if so where, or what, is the list of magic keywords?
An example can be seen on Redmine's issue tracker page.
http://www.redmine.org/issues/6987 has two "Associated Revisions"
They're associated because the commit message has Fixed: Wiki#find_page should not be case sensitive because page title uniqueness is not (#6987). The combination of Fixed as a keyword and #6987, bug's unique ID, automatically updated the associated ticked to fixed.

A: From http://doc.bazaar.canonical.com/development/en/user-reference/bugs-help.html:

When making a commit, metadata about bugs fixed by that change can be recorded by using the --fixes option. For each bug marked as fixed, an entry is included in the 'bugs' revision property stating '<url> <status>'. (The only status value currently supported is fixed.)
The --fixes option allows you to specify a bug tracker and a bug identifier rather than a full URL. This looks like:
bzr commit --fixes <tracker>:<id>

For example,
bzr commit --fixes lp:1234 -m "Fixes bug #1234 will mark Launchpad bug #1234 as fixed. The "Fixes bug #1234" message does not mark the bug as fixed but it will link to the bug report when browsing the commit history in Launchpad.


text:
Q: adobe native extension for android, app crashes on back button when trying to come back from Browser I have created a native extension (Android) for 3rd party advertiser (TrialPay), in which it requires to load webview and further opens the url in native browser. After that it asks to tap back button so that user can come back to app from native browser but at that moment app crashes...
here is my Activity in native extension code :
public class TrialPayOfferWallActivity extends Activity{

Button doneButton = null;
WebView offerWallWebView = null;
public static FREContext freContext;
@SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    //Remove title bar
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    //Remove notification bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    Log.i(this.getClass().getSimpleName(), "Inside TrialPayOfferWallActivity OnCreate function");

    this.setContentView(freContext.getResourceId("layout.trialpayofferwallactivity"));

    Log.i(this.getClass().getSimpleName(), "1");
    Bundle extraBundleObj = this.getIntent().getExtras();
    Log.i(this.getClass().getSimpleName(), "2");
    String urlString = extraBundleObj.getString("urlString");
    Log.i(this.getClass().getSimpleName(), "3-"+urlString);

    doneButton = (Button) this.findViewById(freContext.getResourceId("id.btnDone"));
    Log.i(this.getClass().getSimpleName(), "4");
    offerWallWebView = (WebView) this.findViewById(freContext.getResourceId("id.offerwallwebview"));
    Log.i(this.getClass().getSimpleName(), "5");
    doneButton.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              setResult(RESULT_OK);
              finish();
          }
        });
    Log.i(this.getClass().getSimpleName(), "6");
    offerWallWebView.getSettings().setJavaScriptEnabled(true);
    offerWallWebView.getSettings().setUseWideViewPort(true);
    offerWallWebView.getSettings().setLoadWithOverviewMode(true);
    offerWallWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

    Log.i(this.getClass().getSimpleName(), "7");
    this.loadWebViewWithURL(urlString);
}

public void loadWebViewWithURL(String url2)
{
    offerWallWebView.loadUrl(url2);
    offerWallWebView.setWebViewClient(new WebViewClient() {
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("http:") || url.startsWith("https:")) {
            view.loadUrl(url);
        } else {
            if (url.startsWith("tpbow")) {
                url = url.substring(5);
            }
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity( intent );
        }
        return true;
    }

    });
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
 if (keyCode == KeyEvent.KEYCODE_BACK && (offerWallWebView.getVisibility() == WebView.VISIBLE)) {
    this.goBack(keyCode, event);
    return true;
 } else {
    return super.onKeyDown(keyCode, event);
 }
}

private void goBack(int keyCode, KeyEvent event) {
 if (offerWallWebView.canGoBack()) {
    offerWallWebView.goBack();
 } else {
    super.onKeyDown(keyCode, event);
 }
}
protected void onPause()
{
    super.onPause();
    //sendErrorBack("Cancelled");
    Log.i(this.getClass().getSimpleName(), "onPause");
}

protected void onStop()
{
    super.onStop();
    //sendErrorBack("Cancelled");
    Log.i(this.getClass().getSimpleName(), "onStop");
}

protected void onResume()
{
    super.onResume();
    Log.i(this.getClass().getSimpleName(), "onResume");
}

protected void onStart()
{
    super.onStart();
    Log.i(this.getClass().getSimpleName(), "onStart");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.i(this.getClass().getSimpleName(), "Inside OnActivityResult function");
    if (resultCode == RESULT_OK) {
        Log.i(this.getClass().getSimpleName(), "Inside OnActivityResult function->result ok");
    }

}

}
Am I missing something ?


text:
Q: Can we prevent shared mutable state if we only allow local variables to be mutable? In a non-OOP programming language, like C, If we only allow local variables to be mutated in every possible way (change internal fields, re-assigning, ...) but disallow mutation of function arguments, will it help us prevent shared mutable state?
Note that in this case, function main can start 10 threads (functions) and each of those 10 threads will receive an immutable reference to the same variable (defined in main). But the main function can still change the value of that shared variable. So can this cause problem in a concurrent/parallel software?
I hope the question is clear, but let me know if it's not.
P.S. Can "software transactional memory (STM)" solve the potential problems? Like what Clojure offers?

A: Yes and no... this depends on the platform, the CPU, the size of the shared variable and the compiler.
On an NVIDIA forum, in relation to GPU operations, a similar question was very neatly answered:

When multiple threads are writing or reading to/from a naturally aligned location in global memory, and the datatype being read or written is the same by all threads, and the datatype corresponds to one of the supported types for single-instruction thread access ...

(Many GPU single-instruction can handle 16 Byte words (128bit) when it's known in advance, but most CPUs use single-instruction 32bits or 64bit limits)
I'm leaving aside the chance that threads might read from the CPU registers instead of the actual memory (ignoring updates to the data), these are mostly solvable using the volatile keyword in C.
However, conflicts and memory corruption can still happen.
Some memory storage operations are handled internally (by the CPU) or by your compiler (the machine code) using a number of storage calls.
In these cases, mostly on multi-core machines (but not only), there's the risk that the "reader" will receive information that was partially updated and has no meaning whatsoever (i.e., half of a pointer is valid and the other isn't).
Variables larger than 32 bits or 64 bits, will usually get updated a CPU "word" (not an OS word) at a time (32bits or 64 bits).
Byte sized variables are super safe, That's why they are are often used as flags... but they should probably be handled using the atomic_* store/write operations provided by the OS or the compiler.


text:
Q: OpenTK - Useability of Accumulation Buffer I'm trying to use accumulation buffer in OpenTK project to no avail.
I learned that in newer version of OpenGL it was removed so I was wondering if its usable in OpenTK and if yes then is it dependent on:

*

*Libary im using - im currently using OpenTK.Graphics.OpenGL.

*The version of OpenGL set in shaders for example:

#version 330

in vec3 vPosition;
in  vec3 vColor;
out vec4 color;
uniform mat4 modelview;

void
main()
{
    gl_Position = modelview * vec4(vPosition, 1.0);

    color = vec4( vColor, 1.0);
}

If any of this is at fault of not letting me use accum buffer then it will probably solve this question of mine too
OpenTK - How to achive antialiasing using accumulation buffer

A: If deprecated functionality is still available, depends on the OpenGL Context type.
If you use a compatibility profile OpenGL Context, then all the deprecated functionality, as a accumulation buffer, is still available, even in the most resent OpenGL version 4.6.
In a core profile OpenGL context, the deprecated functionality is removed.
By default OpenTK creates a compatibility profile OpenGL context.


text:
Q: is relativity an illusion , a measuring error? In the proof of relativity through lorenz transformation it looks like the relativity is essentially a mis of accuracy to measure the time and lengths. Am I true?

A: No. It is not about any measurement error or the wrong measurements being carried out by some observer or something. Relativity is about the actual changes that come when you change the frame of reference. It is the heart of relativity that all the observers are equivalent and thus surely it doesn't suggest that the 'moving' observers carry out 'wrong' experiments.
The basis of relativity theory comes from 3 things:
2 postulates of Einstein (1. All inertial frames are equivalent 2. The speed of light is same in all inertial frames.) and the definition of simultaneity.
Definition of simultaneity essentially determines what you call a tick of your clock and length of your meter stick and using that definition one can derive the Lorentz Transformations.
Definition of simultaneity clearly states that chronological order of events may be different for different observers and thus simultaneity is relative - and of course, each one's simultaneity is as valid as the other one's. And thus the measurements of the time interval and length also differs in different frames and all of them are equally justified and all the difference that comes is very fundamental- namely a consequence of the most intuitive definition of simultaneity. It is not about experimental errors.
Rather what relativity suggests is that the reality is not 3 dimensional as our intuition suggests, but it is 4 dimensional. The distance between 2 points (i.e. events) in this 4-dimensional reality is to be measured by $c^2t^2 - x^2 - y^2 - z^2$, which essentially comes out same in all the inertial frames. But the individual of these terms: $t, x, y,$ or $z$ can be different for different observers. And all of them are equally justified.


text:
Q: How to create SQL database connectivity in cocoa I am creating a Preference Pane (for System Preferences). I want to fetch data from an SQL database. How do i do that? Please tell me about the code for basic SQL database connectivity in Cocoa.

A: If you really want to fetch from a SQL database, there are a number of wrapper libraries you could use.

*

*FMDB (SQLite only)

*FDO  (SQLite only)

*CocoaMySQL (MySQL only)

Depending on your data needs, I might actually leverage a scripting language and call that (somehow) from your PrefPane. For example, create a bundle using PyObjC or MacRuby and use SQLAlchemy or ActiveRecord as appropriate.


text:
Q: Modify arraystretch for a single row in table I need to display fractions within a table and it requires to set
\renewcommand{\arraystretch}{2.3}

The problem is that not all rows contain fractions, and in this cases the white space below and above is too big. I can tweak it manually with something like \\[-2ex]. This works for the middle cases, though its a little inconvenient, but I have no idea how to reduce the absolute top space.
Something like
\vspace{-2ex}

has no effect.
The best would be to be able to change the arraystretch for a single table row, but the command has no effect after \begin{tabular}. How can I solve this issue?

MWE
\documentclass{article}

\usepackage{amsmath}
\usepackage{booktabs}

\begin{document}

\begin{table}
    \renewcommand{\arraystretch}{2.3}

    \begin{tabular}{@{}c|l@{}}
            \bfseries $R_x$ & Symbol\\
            \hline\hline
            $\dfrac{a}{b}$ & $ \dfrac{A}{B} $\\
            $\dfrac{a}{b}$ & $ \dfrac{A}{B} $\\
            $\dfrac{a}{b}$ & $ \dfrac{A}{B} $\\
            \hline
    \end{tabular}
\end{table}

\end{document}

MWE with siunitx
\documentclass{article}

\usepackage{amsmath}
\usepackage{booktabs}
%\usepackage{siunitx}
\usepackage{wrapfig}

\usepackage{cellspace}
\setlength\cellspacetoplimit{4pt}
\setlength\cellspacebottomlimit{4pt}

\begin{document}

\begin{wrapfigure}[14]{R}{8.5cm}
    \renewcommand{\arraystretch}{2.3}

    \begin{tabular}{@{}Sc|Sl@{}}
            \bfseries $R_x$ & Symbol\\
            \hline\hline
            $\dfrac{a}{b}$ & $ \dfrac{A}{B} $\\
            some text & some other text \\
            $\dfrac{a}{b}$ & $ \dfrac{A}{B} $\\
            $\dfrac{a}{b}$ & $ \dfrac{A}{B} $\\
            \hline
    \end{tabular}
\end{wrapfigure}

\end{document}

A: Similar result as with cellspace package, as propose Bernard, you can obtain with makecell package:

\documentclass{article}
\usepackage{amsmath}
\usepackage{booktabs}
\usepackage{siunitx}
\usepackage{wrapfig}

\usepackage{makecell}% <-- for gaped cells

\begin{document}

\begin{wrapfigure}[14]{R}{8.5cm}
\setcellgapes{3pt}
\makegapedcells
    \begin{tabular}{@{}>{$\displaystyle}c<{$}|>{$\displaystyle}l<{$}@{}}
R_x                 &   \text{Symbol}           \\
    \hline\hline
\frac{a}{b}         &   \frac{A}{B}             \\
    \hline
\text{some text}    &   \text{some other text}  \\
    \hline
\frac{a}{b}         &   \frac{A}{B}             \\
    \hline
\frac{a}{b}         &   \frac{A}{B}             \\
    \hline
    \end{tabular}
\end{wrapfigure}
\end{document}

Note:
Also \makegapedcells doesn't work in all circumstances. For example, it prevent coloring rows/columns with use \colortbl or [table]{xcolor} packages.

A: The best solution is to use the cellspace package: it defines an adjustable minimal vertical padding around a cell. For this, you have to prefix the column specifier with the letter S (or C if you load siunitx).
With \arraystretch, there are two drawbacks: first the cell contents is no more vertically centred, and second, you have to determine, by trial and error, the stretch value – any modification of the contents may result in a new value, as is demonstrated in the following, where I modified one fraction, keeping the value you gave:
\documentclass{article}

\usepackage{amsmath}
\usepackage{booktabs, cellspace, hhline}
\setlength\cellspacetoplimit{4pt}
\setlength\cellspacebottomlimit{4pt}

\begin{document}

\begin{table}
  \renewcommand{\arraystretch}{2.3}
  \begin{tabular}{@{}c|l@{}}
    \bfseries $R_x$ & Symbol \\
    \hline\hline
    $\dfrac{a}{b}$ & $ \dfrac{A}{B} $ \\
    \hline
    $\dfrac{a}{b}$ & $ \dfrac{A}{B + \cfrac{C}{D}} $ \\
    \hline
    $\dfrac{a}{b}$ & $ \dfrac{A}{B} $ \\
    \hline
  \end{tabular}
\hskip2cm
  \begin{tabular}{@{}Sc|Sl@{}}
    \bfseries $R_x$ & Symbol \\
    \hline\hline
    $\dfrac{a}{b}$ & $ \dfrac{A}{B} $ \\
    \hline
    $\dfrac{a}{b}$ & $ \dfrac{A}{B + \cfrac{C}{D}} $ \\
    \hline
    $\dfrac{a}{b}$ & $ \dfrac{A}{B} $ \\
    \hline
  \end{tabular}
\end{table}
\end{document}


text:
Q: Why did the initial victim change so slowly? At the beginning of the series, we saw that

Monsignor Pruitt walked around

during the day without any trouble.
It was days, at the very least, if not weeks, before Pruitt's condition progressed to the point that he could no longer tolerate sunlight, and he did not exhibit as much loss of control as most of the others.
However, Riley exhibited extreme sensitivity to sunlight mere hours after drinking the blood of the winged vampire. Similarly, the townsfolk who were transformed in the final episode turned to ash upon daybreak.
As such, why did Pruitt change so slowly?

A: Drinking small amounts of the vampire's blood only rejuvenated and reversed bodily damage/diseases.  For the full transformation to occur, the victim needs to die first which we later see when the priest falls off dead with obvious signs of ingesting poison and then coming back to life. It's only after this point he develops his photosensitivity.


text:
Q: HTTP-запрос DELETE из AngularJS в Django REST - как передать JSON параметр? Удаление по pk, запрос вида DELETE /myapi/pk/, где pk - это число:
def delete(self, request, pk, format=None):
        print(pk);
        item = self.model.objects.get(item_id=pk)
        item.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

В AngularJS:
$http.delete('/myapp/' + pk + '/');

где pk - также число.
Все работает. print(pk) - выводит искомое число.
Мне же нужно удалять не только по pk, а и при необходимости - по другому полю, который имеет текстовый формат.
Чтобы удалить только по текстовому полю, назовем его item_name, я пытаюсь использовать следующую функцию:
def delete(self, request, pk, format=None):
        print(request.GET['item_name']);
        item = self.model.objects.get(item_name=request.GET['item_name'])
        item.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

В AngularJS:
$http.delete('/myapp/' + pk + '/', {'item_name': item.name});

где pk - также число, item.name - текст.
Пояснение: pk все равно использую, т.к. DELETE-запрос требует формата /url/pk/
print(request.GET['item_name']) - ничего не выводит, ошибка 500. Т.е. item_name не передается в запросе.
Чтобы проверить, делаю то же самое с pk:
def delete(self, request, pk, format=None):
        print(request.GET['id']);
        item = self.model.objects.get(item_name=request.GET['id'])
        item.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

В AngularJS:
$http.delete('/myapp/' + pk + '/', {'id': pk});

где pk - то же число.
Снова print(request.GET['id']) ничего не выводит, ошибка 500.
Если я правильно понимаю, в запросе DELETE отбрасываются JSON-данные, т.е. request.data? Как тогда передать параметр?

A: Вы пытаетесь передавать данные в теле запроса DELETE.Это противоречит спецификации.
У вас два варианта. Использовать DELETE и передавать идентификатор в параметре запроса, либо использовать POST запрос с указанием действия.(по хорошему противоречит REST)
Для ознакомления прочитайте статью с хабра.
Спецификация HTTP/1.1, part 2: Message Semantics

Bodies on DELETE requests have no defined semantics.  Note that
sending a body on a DELETE request might cause some existing
implementations to reject the request.

RFC2616

The DELETE method requests that the origin server delete the resource
identified by the Request-URI.

p.s. Формулируйте суть вопроса, а не вываливайте всю портянку с кодом. Суть вашего вопроса - почему не передаются данные при использовании DELETE метода :) Если бы спросили именно так - ответ получили бы в разы быстрее.


text:
Q: Asymptote - Using the olympiad package I've been trying to use the Olympiad package for Asymptote on my Mac to use in TexShop (I'm working with pdfTeX). I just tried to put import olympiad; in front of my code, but it gives an error:
Processing file
error: could not load module 'olympiad'

On the following link's post, it says I have to install the olympiad package somehow? I'm fairly new to Asymptote in TeXShop, so I don't know how I should install/download/set up the package.
Installing the olympiad package on Mac
How do I use the package? All I want to do is use the add(pathticks()); method, although I suppose if I can't figure it out I can try doing it by hand.
Thanks in advance! Any help would be greatly appreciated.


text:
Q: Separate a string by a wildcard in python I have a file that looks like
 12 MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
 16 S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
  8 O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01

and I want to separate out the numbers from the front of the line, with an output of
MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01

I have this
for line in file:
    head, sep, tail = line.partition('wildcard')
    print tail

What should I put in for the wildcard?

A: Your format looks like a fixed-column format, where each column is of a fixed width.
If so, use slicing instead:
for line in file:
    print line[4:]

to slice off the first 4 characters.
Alternatively, split on whitespace once, with the None argument to str.split():
for line in file:
    tail = line.split(None, 1)[-1]
    print tail

str.split(None) skips whitespace at the start of the string and splits on the first sequence of whitespace characters after the first column. [-1] takes the last element; even if there is no more than one column on the line you'll get a result.
Demo:
>>> line = ' 16 S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01\n'
>>> line.split(None, 1)
['16', 'S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01\n']

A: You can use,
head, sep, tail = line.strip().partition(" ")

The whole program becomes like this
with open("Input.txt") as inFile:
    for line in inFile:
        print line.strip().partition(" ")[2]

Output
MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01

A: text = '''12 MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
 16 S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
  8 O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01'''

for line in text.splitlines():
    print line.split(None,1)[1]

result
MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01

A: Instead of doing it yourself, you could also use a library: NumPy's I/O routines (loadtxt) are very useful for parsing such files.
In your case, you'd have to specifiy a record data type (dtype parameter, see numpy.loadtxt).


text:
Q: MySQL Server 5.6 won't start on Windows I'm having an issue getting MySQL Server 5.6 (community edition) running. It was working just fine until I restarted my server. Now it won't start at all.
After doing a bit of research, I discovered there is a log file that it writes to, which has helped a little, but I'm not entirely sure how to fix the issue it's reporting.
After doing more research I discovered trying to start mysqld manually using the options "--standalone" and "--debug" might help, but they don't seem to make a difference, and I've looked everywhere for the mysterious debug log, but was unable to find it. I checked in the C drive root, and in MySQL server folders, but nothing. Here is the most recent .err file report:

2014-09-18 18:47:29 2240 [Note] Plugin 'FEDERATED' is disabled.
2014-09-18 18:47:29 2240 [Note] InnoDB: Using atomics to ref count buffer pool pages
2014-09-18 18:47:29 2240 [Note] InnoDB: The InnoDB memory heap is disabled
2014-09-18 18:47:29 2240 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2014-09-18 18:47:29 2240 [Note] InnoDB: Memory barrier is not used
2014-09-18 18:47:29 2240 [Note] InnoDB: Compressed tables use zlib 1.2.3
2014-09-18 18:47:29 2240 [Note] InnoDB: Not using CPU crc32 instructions
2014-09-18 18:47:29 2240 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2014-09-18 18:47:29 2240 [Note] InnoDB: Completed initialization of buffer pool
2014-09-18 18:47:33 2240 [Note] InnoDB: Highest supported file format is Barracuda.
2014-09-18 18:47:33 2240 [Note] InnoDB: The log sequence numbers 1625977 and 1625977 in ibdata
  files do not match the log sequence number 28347554 in the ib_logfiles!
2014-09-18 18:47:33 2240 [Note] InnoDB: Database was not shutdown normally!
2014-09-18 18:47:33 2240 [Note] InnoDB: Starting crash recovery.
2014-09-18 18:47:33 2240 [Note] InnoDB: Reading tablespace information from the .ibd files...
2014-09-18 18:47:34 2240 [ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous
  tablespace osticket/ost_ticket__cdata uses space ID: 54 at filepath: .\osticket\ost_ticket__cdata.ibd. Cannot open tablespace osticket_2/ost_api_key which uses space ID: 54 at filepath: .\osticket_2\ost_api_key.ibd
InnoDB: Error: could not open single-table tablespace file .\osticket_2\ost_api_key.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.

Any clue as to what might fix this problem? I'd prefer a solution that doesn't involve losing my MySQL database files/entries, as I've already had to redo over half of my SQL-connected web services, and would prefer not to have to do it again.

A: [closed] Reinstalled MySQL, removed old DB's. starting over. [closed]


text:
Q: Question: Unity3D 3d models non-uniform scaling I have to rotate a 3d model (by LookAt) in unity but it has non-uniform scale
So the question is: Can I convert non-uniform scale to 1,1,1 or I need another 3d model?
Image


text:
Q: How can i add cloudfront behavior path pattern which matched by querystring I want to add cloudfront behavior pattern like below (jpg can replaced various image type eg, gif, png ...)
/original/a/b/c/d/a.jpg?p1=1&p2=2 : match
/original/a/b/c/d/a.jpg : not match
i tried below but not working
"original/*?*"
"original/*\?*"

how can i do this??
please help me
cloudfront

A: Path patterns don't support regex or globbing. Also, it doesn't support query.

The path you specify applies to requests for all files in the specified directory and in subdirectories below the specified directory. CloudFront does not consider query strings or cookies when evaluating the path pattern. For example, if an images directory contains product1 and product2 subdirectories, the path pattern images/*.jpg applies to requests for any .jpg file in the images, images/product1, and images/product2 directories. If you want to apply a different cache behavior to the files in the images/product1 directory than the files in the images and images/product2 directories, create a separate cache behavior for images/product1 and move that cache behavior to a position above (before) the cache behavior for the images directory.

Source: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html?icmpid=docs_cf_help_panel#DownloadDistValuesCacheBehavior

A: From your samples, I think that you want a regex like this:
original\/(?:\w\/)*\w+.\w+\?.*

EDIT
Since you require a globbing pattern try this:
/original/**/*.*\?*

You can find more about the globing patterns here: https://globster.xyz/


text:
Q: Motion (Apple FCP animation software) change project frame size resolution height and width? My Final Cut Pro movie is 2048x1556, 60 fps.

When I import it into Motion it's cropped. It looks like Motion is set for 1080 resolution. How do I change the resolution of Motion to fit the FCP movie? According to Apple's documentation, you use the Width and Height parameters in the Properties Inspector. Are they talking about Inspector > Properties? I don't see any width or height parameters.

Is there a way to start a project with a Final Cut Pro movie and have the Motion project automatically configure itself to the FCP movie?
I'm using Motion 5.4.6 and FCP 10.4.9.

A: The Edit project properties in Motion documentation shows how to change frame size. You click Inspector > Properties and Layers > Project. Now Width and Height appear under Properties and you can change these.


text:
Q: @Mockbean call real method without using thenCallRealMethod() I tried to mock the external packages bean by @MockBean at JPA unit test and successed to mock it. However, the mocking bean calls real method even though it does not call thenCallRealMethod(). I knew that @MockBean register spring application context and always return null value when calling methods. Are there any missing points?
Here are the codes.

*

*MyServiceImplTest.kt
@ExperimentalCoroutinesApi
@DataJpaTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@ContextConfiguration(classes = [TestApplication::class])
@Import(MyServiceImpl::class)
@ExtendWith(SpringExtension::class)
internal class InventoryAdminApiServiceImplTest {
    @MockBean
    private lateinit var myTopicService: TopicV2Service<CustomMessage>

    @Suppress("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private lateinit var myService: MyServiceImpl

    @Test
    fun `test foo`() = runTest {
        runBlocking {
            myService.foo(cancelRequest {
                id = 1
                message = "Canceled"
            })
        }
    }
}

*

*MyServiceImpl
@GrpcService
class MyServiceImpl @Autowired constructor(
    private val myTopicService: TopicV2Service<CustomMessage>,
) : MyServiceGrpcKt.MyServiceCoroutineImplBase() {
    override suspend fun foo(request: CancelRequest): Empty {
        ....
        runBlocking {
            myTopicService.publish(customMessage())
        }
    }
}

*

*TopicV2Service
open class TopicV2Service<M : Message>(private val topic: TopicV2<M>) {
    @Autowired
    private lateinit var queuesProperties: QueuesProperties

    private val client = SnsAsyncClient.create()
    private val protobufPrinter = JsonFormat.printer()

    private val topicArn by lazy {
        client.createTopic { it.name("${queuesProperties.snsPrefix}${topic.name}") }
            .join()
            .topicArn()
    }

    suspend fun publish(message: M) {
        val wrappedMessage = WrappedMessage(topic.name, protobufPrinter.print(message)).let { Json.encodeToString(it) }
        client.publish { it.topicArn(topicArn).message(wrappedMessage) }.await()
    }
}

*

*Error message

java.lang.NullPointerException: Cannot invoke "miniproj.toy1.queues.TopicV2.getName()" because "this.topic" is null
    at miniproj.toy1.queues.TopicV2Service.publish(TopicV2Service.kt:29)
    at miniproj.toy1.inv_service.services.MyServiceImpl$foo$3$1$1.invokeSuspend(MyServiceImpl.kt:485)


text:
Q: How to pass a chart from MPAndroidChart from one activity to another? The charts that I create using the MPAndroidChart library are populated using data that comes from a web service which takes a little time. Hence in this time I wish to show a Splashscreen so the network calls can be made in the back ground, a chart will be formed and then passed to the MainActivity where it is to be shown.
For this I wish to pass two BarChart and a RadarChart object from the Splachscreen activity to the MainActivity.
So how can I accomplish that?

A: Pass the data not the graph. You can pass the data as so:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);

and get it it new activity this way:
Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("new_variable_name");
}

You might have to pass the data as parcelable or serializable depending on what kind of data you have.
Then you can draw the graph on the new activity with the data you passed.

A: In my opinion your overall design approach needs a little refinement.
First, I recommend you avoid using a splash Activity to 'contain' the network operations. From a user experience perspective this could be poor, because the splash screen could be in view for an indeterminate amount of time from one use to the next. If the splash screen stays for more than, say, two seconds, then the application might appear to have become unresponsive. If you insist on doing it this way, I recommend that the splash screen at least contains dynamic status information to inform the user what's going on.
Next, be sure to perform your networking operation on a dedicated Thread, not on the main UI thread.
For the MainActivity to reference the fetched data, I suggest you look at the singleton pattern to hold it in memory. That is, either use a dedicated singleton object, or hold it in a subclass of Application. This way, the networking operation sets the data in that singleton, and the MainActivity obtains it from the singleton. Optionally, when you create the Intent for the MainActivity, the Bundle could perhaps contain a String which acts as a key to obtain the data. The reason I'm suggesting this strategy is because I am assuming that there might be a large amount of data involved. If on the other hand it's a very small amount of data, perhaps you might be able to get away with putting the data itself into the Bundle, perhaps as JSON in a String, or something.
Do keep in mind that if the application goes to the background and is then later resumed, you might be in a situation where your Activity stack is resumed, but all of your application's 'global' state is gone. This means that your MainActivity would be resumed, but the data you expected to be in your singleton class isn't there any more. Your MainActivity should have the means to cope with this, perhaps by setting off a fresh network request.


text:
Q: How far towards my ideal site can I get using available modules. And what would I need to code myself? I've installed the minimal configuration of Drupal 7 with sqlite3 as its database. Now I am wondering how far I can get towards my "ideal site" with already made modules. I'm a programmer and willing to contribute to the community and create modules for what I need, but if there are already nice ones out there I'd like to use those and not re-invent the wheel. What I want is:

*

*A multi-lingual site with two languages, English and Swedish. For this I need:

*

*A way to publish a single post in English and/or Swedish. And being able to set the nice URL for the versions to what I want (like a.com/hej and a.com/hello for the same post in its Swedish and English version).

*If the users browser is set to Swedish and he visits the English version of an article available in Swedish; then a small red box is visible at the top of the article alerting the user that there is a version of this article in his preferred language.

*Two language versions of the navigation where:

*

*Swedish (version of) posts and English only posts are shown in the Swedish version (since most people in Swedish are able to read English anyway).

*English (version of) posts and English only posts are shown in the English version.

*A way to publish three RSS or Atom-feeds:

*

*One per language version of the navigation (see above).

*One additional with Swedish only posts.

*An edited post can be marked to occur on the front page again. I will mark it if I add a tip to my "Linux tips" post for example.

*People can authenticate themselfs when commenting using:

*

*OpenID

*Facebook

*I can write my posts using Markdown.

*My code examples gets syntax highlighted.

*The site validates as XHTML 1.0 Strict and CSS 2.1.

What can I use that is already available?
And what do I need to contribute myself?
Are there any relevant modules I should look at extending for what I contribute?


text:
Q: Android::MediaPalyer.seekTo() method not working I have a problem with seeking with Android MediaPlayer class. I am playing a local video file, drawing it on a surfaceView. It plays ok, but when I call seekTo(msec) it does not seek. Furhermore, I added a listener (OnSeekComplete) and added callback.
It never gets to the onSeekComplete method. Does anyone know why is that, any  good reason, any good workarond ?

A: I seems to be a bug in Android platform -- http://code.google.com/p/android/issues/detail?id=9135. No reaction on that from Android platform developers though.


text:
Q: Why does dropwhile and takewhile skip the last a? Why does dropwhile and takewhile skip the last a in the following exmaple?
>>> import itertools
>>> s = "Aardvark"
>>> def vowel(c):
...     return c.lower() in "aeiou"
...
>>> list(itertools.dropwhile(vowel, s))
['r', 'd', 'v', 'a', 'r', 'k']
>>> list(itertools.takewhile(vowel, s))
['A', 'a']

Before test in console, I think the result should be ['r', 'd', 'v', 'r', 'k'] and ['A', 'a', 'a'].
The documentation said the roughly implementation of dropwhile and takewhile as follows:
def dropwhile(predicate, iterable):
# dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
iterable = iter(iterable)
for x in iterable:
    if not predicate(x):
        yield x
        break
for x in iterable:
    yield x

def takewhile(predicate, iterable):
    # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
    for x in iterable:
        if predicate(x):
            yield x
        else:
            break

A: You are not filtering the string, you are dropping or taking as a certain condition is maintained.
The drop-while would stop dropping when reaching "r" which is not a vowel, and take the rest, and the take-while would stop taking when reaching "r" which is not a vowel, and drop the rest.
The behavior you are describing as desired can be gained with filter:
>>> list(filter(lambda x: x.lower() in 'aeoui', "Aardvark"))
['A', 'a', 'a']
>>> list(filter(lambda x: x.lower() not in 'aeoui', "Aardvark"))
['r', 'd', 'v', 'r', 'k']

A: Starting at the beginning, it takes items While they match a condition, and stops when they don't. You're looking for filter (and itertools.filterfalse):
list(filter(vowel, s))

or a list comprehension:
[c for c in s if vowel(c)]


text:
Q: Need MYSQL uquery solution I have the folowing tree tables one is the stock_items with all the items in it. The stock_in has the stock movements in to the stock and stock_out has the out movements:

and I want to get such a query result:

could some one help me to make this query?

A: You want to select the stock items and join the in totals and out totals. Aggregate to get the totals. Outer join to get items with and without transactions. Use COALESCE to replace nulls with zeros.
select
  s.barcode, s.item_name,
  coalesce(si.total, 0) as amount_in,
  coalesce(so.total, 0) as amount_out,
  coalesce(si.total, 0) - coalesce(so.total, 0) as balance,
  s.unit
from stock_items s
left join
(
  select barcode, sum(amount) as total
  from stock_in
  group by barcode
) si on si.barcode = s.barcode
left join
(
  select barcode, sum(amount) as total
  from stock_out
  group by barcode
) so on so.barcode = s.barcode
order by s.barcode;

A: You can join tables using the barcode column?
select * from stock_items
join stock_in on stock_items.barcode = stock_in.barcode
join stock_out on stock_items.barcode = stock_out.barcode

Just replace the * with a list of desired column names

A: Unleash the power of subqueries and then use subtraction to compute the total stock level.
Basically the strategy here is to:

*

*Run one query to sum up the total stock in

*Run another query to sum up the total stock out

*Run a final query subtracting the summed values.

select *, (stock_in - stock_out) as total from (select
    product_id pid,
    product_name,
    product_unit,
    (select sum(stock_in) from stock_in where product_id=pid) as stock_in,
    (select sum(stock_out) from stock_out where product_id=pid) as stock_out
from products) summed

SQL fiddle here: https://www.db-fiddle.com/f/v95qsALSfnm66HoQb6PqJ6/0


text:
Q: Increment negative value of property based on window size I don't know if this question has an easy or hard answer.
The situation is that I have an element on the page with negative margin:
.element {
margin-left: -195px;
}

It works well with a screen size 1440x532 (check with Chrome's inspector element).
What I want is kind of simple to explain.
I want an increase of 1 pixel (for instance) in the margin-left of the element anytime the window is larger by one pixel:
So, if window size is 1441, the margin-left of the element be -194px. If the window size is 1451, the margin-left of the element be -184px.
In the same way, I want this to work from 1440px upwards.
IMPORTANT NOTE: What I want is a dynamic value for the margin-left that increases based on screen size and not a kind of media query which would make the value always remain the same between an interval of screen sizes. What I want would force me to add a massive number of media queries.
Is this possible with javaScript or jQuery? (or even CSS?)

A: This is not possible with CSS since there is no property or method to capture the window size. If there would be, this could be done using calc().
However, this is possible with JavaScript.
function resizeScreen() {
    var windowWidth = $(window).width();
    var $element = $('.element');

    if (windowWidth > 1440) {
        // Calculate the new (negative) margin by subtracting the windows width by 1440 (e.g. 1500-1440 = 60). The new margin would be: -195 + 60 = -135.
        var newMargin = $element.css('margin-left') + (windowWidth - 1440);

        $('.element').css('margin-left', newMargin)
    }
}

$(window).resize('resizeScreen');

A: The Jquery solutions that other users gave you works perfectly for this use, but if you prefere you can also use a CSS-only alternative (it works even if the user has disabled scripts!).
It has got also a good support among browsers
You can implement your CSS in this way:
    #element{
        margin-left: -195px;
    }
    @media screen and (min-width: 1440px){
        #element{
            margin-left: calc(-195px + 100vw - 1440px); //100vw is the width of the screen

        }
    }

It adds a pixel for each pixel above 1440
Tell me if this is what you mean

A: Yes is it possible with Jquery with resize()
$(window).resize(function() {
  if (($(window).width() <= 1441)) {
     $('.element').css('margin-left', "-194px")
  }else if($(window).width() <= 1451){
     $('.element').css('margin-left', "-184px")
  }

});

But i suggest to you to use media queries with css:
@media screen and (max-width: 1441px) {
  .element {
    margin-left: -194px;
  }
}

@media screen and (max-width: 1451px) {
  .element {
    margin-left: -184px;
  }
}


text:
Q: The entry (Database) has already been added I have two applications that are sharing the same database that is an API and an MVC5 app. Both run well on localhost but on deployment to my Azure account i get this error
 Configuration Error

Description: An error occurred during the processing of a configuration
             file required to service this request. Please review the
             specific error details below and modify your configuration file appropriately.

Parser Error Message: The entry 'XlabDatabase' has already been added.

Source Error:

 An application error occurred on the server. The current custom error settings
 for this application prevent the details of the application error from being viewed remotely (for security reasons)

I have taken steps to even rename the database but on deployment i use the same remote string
here is my MVC app connectionstring
<connectionStrings>
   <add name="XlabDatabase_acc" providerName="System.Data.SQLClient" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;MultipleActiveResultSets=true;App=EntityFramework" />
</connectionStrings>

Here's my MVC Context
    public virtual DbSet<Account> Accounts { get; set; }
    public virtual DbSet<AnnualReport> AnnualReports { get; set; }
    public virtual DbSet<MonthlyReport> MonthlyReports { get; set; }
    public virtual DbSet<WeekReport> WeekReports { get; set; }

    protected override void OnModelCreating(DbModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<AnnualReport>().HasKey<int>(x => x.AnnualReportID);
        builder.Entity<MonthlyReport>().HasKey<int>(x => x.MonthlyReportID);
        builder.Entity<WeekReport>().HasKey<int>(x => x.ReportID);

    }

Here's my API connection string
  <connectionStrings>
     <add name="XlabDatabase" providerName="System.Data.SQLClient" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;MultipleActiveResultSets=true;" />
  </connectionStrings>

Here's my API context
 public virtual DbSet<Customers> Customers { get; set; }
    public virtual DbSet<Salesman> Salesman { get; set; }
    public virtual DbSet<Route> Route { get; set; }
    public virtual DbSet<Purchase> Purchase { get; set; }
    public virtual DbSet<Products> Products { get; set; }
    public virtual DbSet<Assets> Assets { get; set; }
    public virtual DbSet<WeekReports> WKReports { get; set; }
    public virtual DbSet<MonthlyReports> MONReports { get; set; }
    public virtual DbSet<AnnualReports> ANNReports { get; set; }
    public virtual DbSet<Accounts> Accounts { get; set; }
    public virtual DbSet<LoadingOrder> LoadingOrder { get; set; }

    protected override void OnModelCreating(DbModelBuilder builder)
    {

        base.OnModelCreating(builder);

        builder.Conventions.Remove<PluralizingTableNameConvention>();
        builder.Entity<LoadingOrder>().HasRequired(c => c.Salesman).WithMany().WillCascadeOnDelete(false);
        builder.Entity<IdentityUserClaim>().ToTable("UserClaim").HasKey<Int32>(r => r.Id);
        builder.Entity<IdentityUserLogin>().ToTable("UserLogin").HasKey<string>(l => l.UserId);
        builder.Entity<IdentityRole>().ToTable("Role").HasKey<string>(r => r.Id);
        builder.Entity<User>().ToTable("User").HasKey(r => new{ r.IDNumber, r.UserName});
        builder.Entity<IdentityUser>().ToTable("User").HasKey<string>(r => r.UserName);
        builder.Entity<IdentityUserRole>().ToTable("UserRole").HasKey(r => new { r.RoleId, r.UserId });

    }

I have deployed the two applications into two different Virtual Applications and Directories.
UPDATE
This is how i deploy the two applications they share the same connection string

I have also added the Initial Catalog to the connection strings
XLAB

A: On the connection string, after the <providers> and before the first <add....> node, add a <clear /> node.


text:
Q: AADB2C Exception We are developing a mobile client App that is working with the MSAL library to login through Azure. Today we started getting this exception on the client side for both Android and iOS:

Same thing happens if I try to hit the login url through desktop:

This is from the WebView that the MSAL library uses. Everything was working perfectly a couple of days ago and out of nowhere this exception started popping up.
Another thing is that we can actually login and use the App normally if we tunnel through a VPN and go through a United States/Canadian network. If we do that everything works perfectly. But if we try to connect from outside the US or Canada we get this exception. The people in charge of the Azure account told us that they didn't change anything this last days.
I was hoping that maybe you guys can point us in the right direction to dig the cause of this issue. I'm not looking for a straight answer, I know that this is a kinda tricky issue, but any tip that could lead me to detect the issue It's appreciated.
Thanks, and let me know if I can provide any other information.


text:
Q: stopPropagation: element.addEventListener vs onclick attribute I'm playing with stopPropagation, adapting code from an MDC doc.
Here's the question: Everything works fine if I do what they did and use element.addEVentListener("click", fname).
But, when I try to attach the function with the element's onclick attribute (
 ), propagation does not stop.
And if I use
, fname() isn't called at all (I also tried passing fname(ev) with the same results).
Ideas anyone? Let me know if you need to see the code.

A: Actually, your event acts in the following ways:
Event Fires, Capturing Phase, Bubbling phase, Event has Default Action applied.
Thus, in order to stop propagation you can do the following:
element1.addEventListener('click',fname,true)  // Capturing phase
element1.addEventListener('click',fname,false) // Bubbling phase

fname(event){
  event.stopPropagation();
//event.preventDefault(); is also available here (in both phases I believe)
}

Please note that propagation can only be stopped during the bubbling phase, and only using event handlers in this way allows you to interrupt an event.
As far as I know the tradidtional method of

does not allow this functionality.

A: When you do this:

You're not assigning fname as the event handler, you're calling fname from within your event handler (which is an anonymous function created for you). So your first parameter is whatever you pass into fname, and in your quoted code, you're not passing anything into it.
You'd want:

But even that won't be reliable, because it assumes that either the auto-generated anonymous function accepts the event parameter using the name event or that you're using IE or a browser that does IE-like things and you're looking at IE's global window.event property.
The more reliable thing to do is this:

...and have fname return false if it wants to both stop propagation and prevent the browser's default action.
All of this why I strongly advocate always using DOM2 methods (addEventListener, which is attachEvent — with slightly different arguments — on IE prior to IE9) to hook up handlers if you want to do anything interesting in the event (or, 9 times out of 10, even if you don't).

Off-topic: And this whole area is one of the reasons I recommend using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over browser differences for you so you can concentrate on your own work.


text:
Q: Redux - calling a chain of functions in action or reducer? I have a logical issue, whether i should make a multiple function calls into response of each callback inside an actions:
export const myAction= () => (distaptch, getState) => {
    callFunctionA(function(e){
        if(e){
            dispatch(eventA(e));

            callFunctionB(function(e){

                dispatch(eventB(e));

                callFunctionC(function(e){

                    dispatch(eventC(e));
                });
            });
        }
    });
}

or i might want to move those calls into redux reducers and call every next function from there?
const reducer = (state={}, action) => {
  switch (action.type) {
    case 'EVENT_A':

      callFunctionB(action.e);

      return state;
    case 'EVENT_B':

        callFunctionC(action.e);
        return state;
    default:
      return state
  }
}

Second approach looks to me like anti-pattern which leads to spaghetti code... Maybe i am wrong?

A: You're correct in assuming that dispatching actions in the reducer is an anti-pattern. The reasons are mentioned pretty succinctly in this post.
From the Redux documentation:

Things you should never do inside a reducer:
Mutate its arguments;
Perform side effects like API calls and routing transitions;
(Call non-pure functions, e.g. Date.now() or
  Math.random().
[...] For now, just remember that the reducer must be
  pure. Given the same arguments, it should calculate the next state and
  return it. No surprises. No side effects. No API calls. No mutations.
  Just a calculation.

You can look into Redux-Saga to handle asychronous flow to avoid the callback hell of the actions that you show in your first example.


text:
Q: How do you "inject" '/.well-known/jwks.json' into AddJwtBearer during ASPNET startup/configuration? We are using Auth0 for Authentication using one of their boiler plate configuration setups in the Startup of ASPNET:
        string domain = $"https://{configuration["Auth0:Domain"]}/";
    AuthenticationServiceCollectionExtensions.AddAuthentication(services, (string) JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {

            options.Authority = domain;
            options.Audience = configuration["Auth0:Audience"];
            // If the access token does not have a `sub` claim, `User.Identity.Name` will be `null`. Map it to a different claim by setting the NameClaimType below.
            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = ClaimTypes.NameIdentifier
            };
        });

We have a multi-threaded client that spins up a lot of requests at once.  Because of this we sometimes get an error in Auth0 of 'Rate Limit On API - You passed the limit of allowed calls to '/.well-known/jwks.json'.  The suggested correction for this is to "cache '/.well-known/jwks.json'", but they provide no example on how to do that.
I have tried a few of the tangential samples found on stackoverflow and others in order to override the configuration manager for authentication, but each ends in a different deadend/error I can't figure out.
Does anyone have a working example of how to "inject" a cached version of '/.well-known/jwks.json' into the authentication middleware?
FYI: This is all running on AWS lambda, so the ability for AWS Lambda to spin up at least 20 instances of ASPNET that hits the rate limit exception is not only plausible, but alread occurring in our system testing.  I can't really/don't want to rate limit Lambda because then we'll get gateway timeouts from API Gateway.
FYI2: I have already rate limited the client to 20 executing requests in order to work around it, but would really like to solve this problem at the root cause.
One example I have used gets me a "invalid_issuer" error:
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;

namespace YadaYada.Web;

public static class JwtAuth
{
    public static IServiceCollection AddJwtAuth(this IServiceCollection services, IConfiguration configuration)
    {
        //services.AddSingleton<IConfigurationRetriever<OpenIdConnectConfiguration>, Xyz>();
        //services.AddSingleton<IConfigurationManager<OpenIdConnectConfiguration>, CachingConfigurationManager>(provider => new CachingConfigurationManager("https://tjb.auth0.com/.well-known/jwks.json", provider.GetRequiredService<IConfigurationRetriever<OpenIdConnectConfiguration>>()));

        //https://stackoverflow.com/questions/66865872/ioexception-idx20807-unable-to-retrieve-document-from-system-string-httpre

        string domain = $"https://{configuration["Auth0:Domain"]}";
        AuthenticationServiceCollectionExtensions.AddAuthentication(services, (string) JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority = domain;
                options.Audience = configuration["Auth0:Audience"];
                // If the access token does not have a `sub` claim, `User.Identity.Name` will be `null`. Map it to a different claim by setting the NameClaimType below.
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = ClaimTypes.NameIdentifier,
                    ValidIssuer = domain

                };

                options.SetJwksOptions();

            });
        return services;
    }
}
public static class JwksExtension
{
    public static void SetJwksOptions(this JwtBearerOptions options)
    {
        LambdaLogger.Log(nameof(SetJwksOptions));

        var httpClient = new HttpClient(options.BackchannelHttpHandler ?? new HttpClientHandler())
        {
            Timeout = options.BackchannelTimeout,
            MaxResponseContentBufferSize = 1024 * 1024 * 10 // 10 MB
        };

        options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>("https://tjb.auth0.com/.well-known/jwks.json", new JwksRetrieverNew(), new HttpDocumentRetriever(httpClient) { RequireHttps = options.RequireHttpsMetadata });
    }
}

public class JwksRetrieverNew : IConfigurationRetriever<OpenIdConnectConfiguration>
{
    public Task<OpenIdConnectConfiguration> GetConfigurationAsync(string address, IDocumentRetriever retriever, CancellationToken cancel)
    {
        LambdaLogger.Log(nameof(GetConfigurationAsync));
        return GetAsync(address, retriever, cancel);
    }

    /// <summary>
    /// Retrieves a populated <see cref="OpenIdConnectConfiguration"/> given an address and an <see cref="IDocumentRetriever"/>.
    /// </summary>
    /// <param name="address">address of the jwks uri.</param>
    /// <param name="retriever">the <see cref="IDocumentRetriever"/> to use to read the jwks</param>
    /// <param name="cancel"><see cref="CancellationToken"/>.</param>
    /// <returns>A populated <see cref="OpenIdConnectConfiguration"/> instance.</returns>
    public static async Task<OpenIdConnectConfiguration> GetAsync(string address, IDocumentRetriever retriever, CancellationToken cancel)
    {
        LambdaLogger.Log(nameof(GetAsync));
        if (string.IsNullOrWhiteSpace(address))
            throw LogHelper.LogArgumentNullException(nameof(address));

        if (retriever == null)
            throw LogHelper.LogArgumentNullException(nameof(retriever));

        var doc = await retriever.GetDocumentAsync(address, cancel).ConfigureAwait(false);
        LambdaLogger.Log($"IDX21811: Deserializing the string: '{doc}' obtained from metadata endpoint into openIdConnectConfiguration object.");
        var jwks = new JsonWebKeySet(doc);
        LambdaLogger.Log(jwks.ToString());

        var openIdConnectConfiguration = new OpenIdConnectConfiguration()
        {
            JsonWebKeySet = jwks,
            JwksUri = address,
        };
        foreach (var securityKey in jwks.GetSigningKeys())
        {
            LambdaLogger.Log(securityKey.ToString());

            openIdConnectConfiguration.SigningKeys.Add(securityKey);
        }

        return openIdConnectConfiguration;
    }
}


text:
Q: Unexpected results parsing date strings in JavaScript I'm working on a JavaScript application. I have two different String dates 31/10/2013  and 1/11/2013 and I create an instance of these two dates with new Date(string).getTime();
But it shows this (the same date ) as the result:
console.log(date_s + " after new date " + date );

31/10/2013 after new date Fri Nov 1 00:00:00 UTC 2013

1/11/2013 after new date Fri Nov 1 00:00:00 UTC 2013

A: You haven't a valid string in you new Date(string)
Some example to initialize dates
var my_date=new Date(2013,10,31)

and all the documentation on http://www.w3schools.com/js/js_obj_date.asp

A: 31/10/2013 is not a valid date string unless you've got maybe some localization going on. To the default localization settings for en-US, it should be 10/31/2013. What your string means is "month 31 of 2013" which pushes new Date('31/10/2013') to be some time in 2015 because that's where it resolves the date due to that "month 31."

A: If you want an easy solution, try moment.js - a powerful javascript date parser/formatter/validator/manipulator.
In moment, you can parse date with the syntax like this [doc]:
//this will gives you a correct date object
moment('31/10/2013', 'DD/MM/YYYY').toDate();

Else, you can always welcome to split and rebuild the date object.


text:
Q: Jacobian of Identity?
If one does the substitution as mentioned here, the left side will be Jacobian of an identity map isn't it? How to compute that and how to conclude that the Jacobian here is invertible.


text:
Q: Unable to create a file and assert its existance I am using JAVA to create a log file, but after creating it, when I assert its existence, I get back a java.lang.AssertionError. I must be doing something simply wrong but I do not know what. Here is the code:
File testLogFile = new File("/home/ninad/eclipse-workspace/Log.txt");

testLogFile.createNewFile();

service = builder.withLogFile(testLogFile).build();

service.start

assertTrue(testLogFile.exists());

A: I can think of a few possible explanations:

*

*You are not checking the result of the createNewFile() call.  It returns true if the file did not exist before AND it has been successfully create.
By my reading of the javadoc, the method should throw an IOException if it tries to create the file and fails.  But the flipside is that if you don't test the result of the call, you can't be sure that you got a new file.

*The builder or the service could be removing or renaming the logfile.

*If the code was part of a multi-threaded application, then another thread could have removed / renamed the file.

*The file could (in theory) have been removed / renamed by another application.

*You may have (OS-level) permission to create the file, but not test for its existence.  (It seems a bit far-fetched ... but some OSes have "complicated" permissions systems.)
There could be other things I haven't thought of.  If you provided an MCVE (including the "builder" implementation) we could check.


text:
Q: MeteorJS click event issue when using meta viewport tag on iOS Safari I've stumbled across this strange Meteor JS behaviour when using the following meta tag in the head:
<meta name="viewport" content="width=device-width, initial-scale=1">

When tapping anywhere on the body in iOS Safari some kind of click/touch event is triggered. It's clearly visible because it creates and outline/highlight on the body just like it would for a normal link when it's clicked.
For a demo open this link on your iPhone:
http://metaviewportissue.meteor.com and click anywhere on the body.
Code is here:
https://github.com/st3phan/meteorviewportissue
When I remove the meta viewport tag the click/touch event on the body is gone.
Does someone know what's going on here and maybe how to get rid of this strange behaviour?
Versions:
Meteor 1.0
Safari 8.1


text:
Q: How to use progress bar in wpf without multithreading? Help please.
I want to see the progress bar change with the IsIndeterminate= true property while reading from the database.
I know that I can use Task and BackgroundWorker to create another thread. But for me, it is very important that I do not leave the method in which the long-term operation takes place until it is finished. What can be done in this case?
P.S. Sorry for my English :)

A: You can't. The UI thread needs to run to display the change to the progress bar, at the same time as your method is running.
Run your method in a background thread, but disable everything in the window before you start so the user can't change anything, and set the mouse pointer to an hourglass so they don't try.
Use try/catch/finally to re-enable everything at the end and reset the mouse pointer.

A: After awaiting a Task, execution returns to the method where you started the Task. This is perhaps all you need, as the method isn't actually "left".
Here is a sample Button Click event handler that disables itself before awaiting an awaitable method call (e.g. some long running operation), and that enables itself again when the call has completed:
private async void Button_Click(object sender, RoutedEventArgs e)
{
    var button = (Button)sender;
    button.IsEnabled = false;

    await SomethingAsync();

    button.IsEnabled = true;
}

private Task SomethingAsync()
{
    // ...
}


text:
Q: Spring : Convert Response Entity to JSON From my rest client, i am hitting a web service and getting my response in the form of String {"code":"00000","msg":"Success"> . Now I am converting this in the form of JSONObject which i can then use further. But i am not able to. Below is the code i am using . Please guide.
private ResponseEntity<String> test()
{
    final String uri = "URL";

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
    ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
    System.out.println(result);

    //This part is not working.
    try {
        JSONObject arr = new JSONObject((result));
        for (int i = 0; i < arr.length(); i++) {
          JSONObject abc = arr.getJSONObject(i);
          System.out.println("test1 : " + abc.getString("test1"));
          System.out.println("test2 : " + abc.getString("test2"));
          System.out.println("test3 : " + abc.getString("test3"));
        }
    } catch (Exception e) {
    }

    return result;
}

A: Instead of converting to a generic JSONObject, you should create a class matching your response.
Spring will map the response to your model class using Jackson(behind the scenes).  There is no need for converting it yourself.
So Let's say, you create a class
class Response {
String code;
String message:

//Gettes and Setters
}

Now you can change your code a bit like this
 ResponseEntity<Response> result = restTemplate.exchange(uri, HttpMethod.GET, entity, Response.class);

Now if you useresult.getBody(), this would give your Response object, which you can use

A: One form is using JSONObject

  <dependency>
   <groupId>com.googlecode.json-simple</groupId>
   <artifactId>json-simple</artifactId>
   <version>1.1</version>
   <scope>${scope}</scope>
  </dependency>

import org.json.simple.JSONObject;

JSONObject json = new JSONObject();

json.put("key1", value1);
json.put("key2", value2);


text:
Q: When using a virtual printer how can I check that print is finished? I am using a virtual printer to print a word document into an image file in a C# program. So far everything is going fine except that I don't know when the printing process is finished so I can read the content of the generated image.
Here's my code :
using System;
using Microsoft.Office.Interop.Word;
using Word=Microsoft.Office.Interop.Word;

var app = new ApplicationClass();
object filename = "C:\\ad.doc";
var missing = Type.Missing;
var doc = app.Documents.Open(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
var oldPrinter = app.ActivePrinter;
app.ActivePrinter = "Name of printer";
object outputFileName = "c:\\ad.tif";
object trueValue = true;
object falseValue = false;

doc.PrintOut(ref trueValue, ref falseValue, ref missing, ref outputFileName, ref missing, ref missing,
                             ref missing, ref missing, ref missing, ref missing, ref trueValue, ref missing, ref missing,
                             ref missing, ref missing, ref missing, ref missing, ref missing);

app.ActivePrinter=oldPrinter ;
doc.Close(ref missing, ref missing, ref missing);
app.Quit(ref missing, ref missing, ref missing);

Then how can I be sure that the print processing is finished so I can continue and get the image content?

A: Unfortunately, about the only way I've found to check for printing status in word is one of two things.

*

*Print synchronously. Not great though because it'll can hang you
till the printing is complete.

*Print the doc asynchronously, and then check the
APPLICATION.BACKGROUNDPRINTINGSTATUS property in a loop or on a
background worker thread continuously until it becomes 0 (no longer
printing) or you hit a watchdog timeout

Something like this....
        Do Until _Doc.Application.BackgroundPrintingStatus = 0
            System.Windows.Forms.Application.DoEvents()
            System.Threading.Thread.Sleep(750)
        Loop

Not perfect, but it works.
Note that this will only tell you when its finished spooling from word. If you're talking about knowing when the document is actually completed PRINTING on the printer, that's a whole other issue. You'll need the print jobID and have to query the printer spooler stuff, which I couldn't help you on.


text:
Q: Find the number of possible pairs of the number of days required by Ramu and Krishna respectively to complete the work independently If Ramu and Krishna work on alternate days to complete a work, then the work gets completed in exactly 24 days. If R and K denote the number of days required by Ramu and Krishna respectively to complete the work independently, then how many ordered pairs of integral values of R and K are possible?
If Ramu and Krishna work independently then they are doing work for 12 days. How to find the integral pairs. I am stuck and I think it is a really tricky one

A: In one day, Ramu can do $\large{\frac{1}{R}}$ of the job.

In one day, Krishna can do $\large{\frac{1}{K}}$ of the job.

In $2$ days, working on alternate days, they can do $\large{\frac{1}{R}+\frac{1}{K}}$ of the job.

In $24$ days, working on alternate days, they can do $12\left(\large{\frac{1}{R}+\frac{1}{K}}\right)$ of the job.

Given that it take $24$ days (assumed exact) for them to complete the job,
we get
\begin{align*}
&12\left(\frac{1}{R}+\frac{1}{K}\right)=1\\[4pt]
\implies\;&12(R+K)=RK\\[4pt]
\implies\;&RK-12R-12K=0\\[4pt]
\implies\;&(R-12)(K-12)=12^2\\[4pt]
\end{align*}
So for every pair $(a,b)$ of positive integers such that $ab=12^2$, we get a pair $(R,K)=(12+a,12+b)$.

It remains to count the number of positive integer factors of $12^2$.

Since $12^2 = (2^4)(3^2)$, it follows that $12^2$ has $(4+1)(2+1)=15$ positive integer factors, hence there are $15$ valid $(R,K)$ pairs.


text:
Q: How to setup vscode settings for Python formatter? Somehow my formatter isn't working. I pip installed yapf , but when I do Ctrl+Shift+P -> Format Document or Shift + Alt + F on a selected code, It doesn't change. I heard it auto formats on save, but that didn't work either.
I am trying to follow the guide here.
It mentions I should edit this part in the settings
"python.formatting.yapfArgs": ["--style", "{based_on_style: chromium, indent_width: 20}"],

But when I search this, this is the only thing I see
What I am trying to do at the moment is set the indent to 4 spaces, and also adjust the max line length.
This is what my settings look like for formatting

A: It seems in the preference you have not set the correct "provider" for the formatting

You can also check for the file C:\Users\\AppData\Roaming\Code\User\settings.json (if you want to change globally) or \.vscode\settings.json (if you want to change for the current workspace only).

Hope that helps.


text:
Q: JavaEE/Tomcat 9.0.0/ IntellijIdea 2016.2: java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL 'null' There is a problem with connectors in my project. I have added MySQL connector to Tomcat's lib and also to project's path in IntellijIDEA but problem still exist. Answers from older versions in stackoverlow didnt work in here.
 Here are project classes:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
           version="3.1">

    <resource-ref>
        <description>DB Connection</description>
        <res-ref-name>jdbc/library</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

    <context-param>
        <param-name>javax.faces.CONFIG_FILES</param-name>
        <param-value>/WEB-INF/context.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

</web-app>

context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/myApp" docBase="myApp"
         crossContext="true" reloadable="true" debug="1">
    <Resource name="jdbc/library"
              global="jbc/library"
              auth="Container"
              type="javax.sql.DataSource"
              initialSize="10"
              maxTotal="100"
              maxIdle="30"
              maxWaitMillis="10000"
              username="root"
              password="admin"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/library" />
</Context>

error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Upss</title>

Something is wrong

Try again

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Library Viewer</title>

Biblioteka viewer

<form action="BookServlet" method="post">
  <input placeHolder="ISBN" type="text" name="isbn">

  <input placeHolder="Tytuł" type="text" name="title">

  <input placeHolder="Opis" type="text" name="description">

  Szukaj: <input type="radio" name="option" value="search"> Dodaj: <input type="radio" name="option" value="add">
  Modyfikuj: <input type="radio" name="option" value="update"> Usuń: <input type="radio" name="option" value="delete">

  <input type="submit" value="Wyślij">
</form>

result.jsp
<%@page import="pl.javastart.model.Book"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<% Book book = (Book)request.getAttribute("book"); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>

Wynik zapytania <%= request.getAttribute("option") %>

W wyniku Twojego zapytania otrzymano następujacy wynik:

Title: <%= book.getTitle() %>

    ISBN: <%= book.getIsbn() %>

    Descrition: <%= book.getDescription() %>

Book.java
package pl.javastart.model;

public class Book {
    private String isbn;
    private String title;
    private String description;
    public String getIsbn() {
        return isbn;
    }
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

    public Book(){}
    public Book(String isbn, String title, String desc){
        this.isbn = isbn;
        this.title = title;
        description = desc;
    }
}

BookServlet.java
package pl.javastart.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pl.javastart.dao.BookDAO;
import pl.javastart.model.Book;

@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String isbn = request.getParameter("isbn");
        String title = request.getParameter("title");
        String description = request.getParameter("description");
        String option = request.getParameter("option");
        BookDAO dao = new BookDAO();
        Book book = null;
        String operation = null;
        boolean result = false;
        if("search".equals(option)) {
            book = dao.read(isbn);
            result = book!=null? true:false;
            operation = "search";
        } else if("add".equals(option)) {
            book = new Book(isbn, title, description);
            result = dao.create(book);
            operation = "add";
        } else if("update".equals(option)) {
            book = new Book(isbn, title, description);
            result = dao.update(book);
            operation = "update";
        } else if("delete".equals(option)) {
            book = new Book(isbn, title, description);
            result = dao.delete(book);
            operation = "delete";
        }
        if(book != null && result) {
            request.setAttribute("option", operation);
            request.setAttribute("book", book);
            request.getRequestDispatcher("result.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }

}

BookDAO.java
package pl.javastart.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import pl.javastart.model.Book;
import pl.javastart.util.ConnectionProvider;

public class BookDAO {

    private final static String CREATE = "INSERT INTO book(isbn, title, description) VALUES(?, ?, ?);";
    private final static String READ = "SELECT isbn, title, description FROM book WHERE isbn = ?;";
    private final static String UPDATE = "UPDATE book SET isbn=?, title=?, description=? WHERE isbn = ?;";
    private final static String DELETE = "DELETE FROM book WHERE isbn=?;";

    public boolean create(Book book) {
        Connection conn = null;
        PreparedStatement prepStmt = null;
        boolean result = false;
        try {
            conn = ConnectionProvider.getConnection();
            prepStmt = conn.prepareStatement(CREATE);
            prepStmt.setString(1, book.getIsbn());
            prepStmt.setString(2, book.getTitle());
            prepStmt.setString(3, book.getDescription());
            int rowsAffected = prepStmt.executeUpdate();
            if (rowsAffected > 0) {
                result = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseResources(prepStmt, null, conn);
        }
        return result;
    }

    public Book read(String isbn) {
        Connection conn = null;
        PreparedStatement prepStmt = null;
        ResultSet resultSet = null;
        Book resultBook = null;
        try {
            conn = ConnectionProvider.getConnection();
            prepStmt = conn.prepareStatement(READ);
            prepStmt.setString(1, isbn);
            resultSet = prepStmt.executeQuery();
            if(resultSet.next()) {
                resultBook = new Book();
                resultBook.setIsbn(resultSet.getString("isbn"));
                resultBook.setTitle(resultSet.getString("title"));
                resultBook.setDescription(resultSet.getString("description"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseResources(prepStmt, resultSet, conn);
        }
        return resultBook;
    }

    public boolean update(Book book) {
        Connection conn = null;
        PreparedStatement prepStmt = null;
        boolean result = false;
        try {
            conn = ConnectionProvider.getConnection();
            prepStmt = conn.prepareStatement(UPDATE);
            prepStmt.setString(1, book.getIsbn());
            prepStmt.setString(2, book.getTitle());
            prepStmt.setString(3, book.getDescription());
            prepStmt.setString(4, book.getIsbn());
            int rowsAffected = prepStmt.executeUpdate();
            if (rowsAffected > 0) {
                result = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseResources(prepStmt, null, conn);
        }
        return result;
    }

    public boolean delete(Book book) {
        Connection conn = null;
        PreparedStatement prepStmt = null;
        boolean result = false;
        try {
            conn = ConnectionProvider.getConnection();
            prepStmt = conn.prepareStatement(DELETE);
            prepStmt.setString(1, book.getIsbn());
            int rowsAffected = prepStmt.executeUpdate();
            if (rowsAffected > 0) {
                result = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseResources(prepStmt, null, conn);
        }
        return result;
    }

    private void releaseResources(PreparedStatement prepStmt, ResultSet res,
                                  Connection conn) {
        try {
            if (prepStmt != null && !prepStmt.isClosed()) {
                prepStmt.close();
            }
            if (res != null && !res.isClosed()) {
                res.close();
            }
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}

ConnectionProvider.java
package pl.javastart.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class ConnectionProvider {
    private static DataSource dataSource;

    public static Connection getConnection() throws SQLException {
        return getDSInstance().getConnection();
    }

    private static DataSource getDSInstance() {
        if(dataSource == null) {
            try {
                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup("java:comp/env");
                dataSource = (DataSource) envContext.lookup("jdbc/library");
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
        return dataSource;
    }
}

Dao.iml
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
  <component name="FacetManager">
    <facet type="web" name="Web">
      <configuration>
        <descriptors>
          <deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/web/WEB-INF/web.xml" />
        </descriptors>
        <webroots>
          <root url="file://$MODULE_DIR$/web" relative="/" />
        </webroots>
      </configuration>
    </facet>
  </component>
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
    <orderEntry type="library" scope="PROVIDED" name="Tomcat 9.0.0.M9" level="application_server_libraries" />
    <orderEntry type="library" name="mysql-connector-java-5.1.39-bin" level="project" />
  </component>
</module>

Here is a screen with project structure:
And console:

A: In context.xml
<Resource name="jdbc/library"
          global="jbc/library"
          ...

it looks like the value for the global key might be missing a letter.
On a different note, all the examples of getConnection() I'm finding online have a String parameter for the url, e.g. this Mkyong article, but no where in your code does it appear to be like that. Is ConnectionProvider.getConnection() actually returning anything when you debug through it?

A: Problem solved. I had to add META-INF directory and move there context.xml
Screen attatched