text:
Q: Extract numbers between string and second empty line : BASH and python Question is similar to many previous questions on SO. But seems distinct enough.
I have data file which has following output. The numbers are to be extracted. The number of elements in the number block is random and there is one empty line above and below the number block. Aim is to extract the numbers and possibly assign them to python numpy array.
string 1

234034 6361234 45096 12342134 2878814 456456
125294 7341234 17234 23135   768234  54134123
213203 6.25 2.36 1.0 0.0021

string 2

298034 20481234 45096 12502134 2870814 456456
19875294 441284 98234 27897135 251021524  768234  54134123
2.3261

string 3

744034 6644034 75096 5302134 298978814 456456
6767294 70441234 330234 200135   867234  54004123
204203 22015 120158 125 21  625 11 5 2.021

Expected output :
Numbers from all blocks arranged as bash arrays or numpy(python) arrays.
Numeric values shown below are only representative.

*

*Bash array : '744034','6644034','75096', .. .. '21','625','11','5','2.021'

or

*

*Numpy array : [744034,6644034,75....,625,11,5,2.021]
My use case prefers numpy array though.

Taking cue from previous question, tried this sed -n '/^symmetry 1$/,/^symmetry 2$/p' file
 but the output is null possibly due to space in the start and end search terms.

Tried python, since eventually I need the numbers as np array. From the question and help in comments, I get one block using the following code
import sys
import re
F=open(sys.argv[1])
text=F.read()
reg=re.compile(r'string 1(.*?)string 2',re.DOTALL)
for match in reg.finditer(text):
    print (match.groups())

output,
string 1

744034 6644034 75096 5302134 298978814 456456
6767294 70441234 330234 200135   867234  54004123
204203 22015 120158 125 21  625 11 5 2.021

 string 2

Need suggestions.

A: If I understood well, this could help:
>>> [np.array(block.split()).astype(float)  # good blocks get parsed into np arrays
     for block in file_content.split("\n\n")  # split by empty lines
     if not block[0].isalpha()]  # avoid string lines

[array([2.3403400e+05, 6.3612340e+06, 4.5096000e+04, 1.2342134e+07,
        2.8788140e+06, 4.5645600e+05, 1.2529400e+05, 7.3412340e+06,
        1.7234000e+04, 2.3135000e+04, 7.6823400e+05, 5.4134123e+07,
        2.1320300e+05, 6.2500000e+00, 2.3600000e+00, 1.0000000e+00,
        2.1000000e-03]),
 array([2.98034000e+05, 2.04812340e+07, 4.50960000e+04, 1.25021340e+07,
        2.87081400e+06, 4.56456000e+05, 1.98752940e+07, 4.41284000e+05,
        9.82340000e+04, 2.78971350e+07, 2.51021524e+08, 7.68234000e+05,
        5.41341230e+07, 2.32610000e+00]),
 array([7.44034000e+05, 6.64403400e+06, 7.50960000e+04, 5.30213400e+06,
        2.98978814e+08, 4.56456000e+05, 6.76729400e+06, 7.04412340e+07,
        3.30234000e+05, 2.00135000e+05, 8.67234000e+05, 5.40041230e+07,
        2.04203000e+05, 2.20150000e+04, 1.20158000e+05, 1.25000000e+02,
        2.10000000e+01, 6.25000000e+02, 1.10000000e+01, 5.00000000e+00,
        2.02100000e+00])]

A: You don't show your expected output but is this what you''re trying to do?
$ awk -v RS= '!(NR%2)' file
234034 6361234 45096 12342134 2878814 456456
125294 7341234 17234 23135   768234  54134123
213203 6.25 2.36 1.0 0.0021
298034 20481234 45096 12502134 2870814 456456
19875294 441284 98234 27897135 251021524  768234  54134123
2.3261
744034 6644034 75096 5302134 298978814 456456
6767294 70441234 330234 200135   867234  54004123
204203 22015 120158 125 21  625 11 5 2.021

or maybe one of these (or something else - do tell....):
$ awk -v RS= -v ORS='\n\n' '!(NR%2)' file
234034 6361234 45096 12342134 2878814 456456
125294 7341234 17234 23135   768234  54134123
213203 6.25 2.36 1.0 0.0021

298034 20481234 45096 12502134 2870814 456456
19875294 441284 98234 27897135 251021524  768234  54134123
2.3261

744034 6644034 75096 5302134 298978814 456456
6767294 70441234 330234 200135   867234  54004123
204203 22015 120158 125 21  625 11 5 2.021

.
$ awk -v RS= -v OFS='\n' '!(NR%2){$1=$1; print}' file
234034
6361234
45096
12342134
2878814
456456
125294
7341234
17234
23135
768234
54134123
213203
6.25
2.36
1.0
0.0021
298034
20481234
45096
12502134
2870814
456456
19875294
441284
98234
27897135
251021524
768234
54134123
2.3261
744034
6644034
75096
5302134
298978814
456456
6767294
70441234
330234
200135
867234
54004123
204203
22015
120158
125
21
625
11
5
2.021


text:
Q: QGIS Fetch Python Plugins Crash I am using QGIS v1.6 on Ubuntu 10.10.
When I use the Fetch Python Plugins menu item QGIS crashes. If I run from the terminal with sudo I get the following error:
Segmentation Fault
Does anyone know how to fix this? I have this problem on 2 installs of Ubuntu on 2 different computers.

A: The python library is probably out of sync with the python library the QGIS plugin was built on. This has been an ongoing issue and can get me more then a little irritated.
Here is what I finally did:
Use QGIS from experimental. Add the nightly build to your sources in apt usually fixes this issue, but puts you on the bleeding edge, not recommended for production work.
http://www.qgis.org/wiki/Download#Trunk_4 The python version and Qgis version seem to stay in sync this way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I merge two tables in a query? I have two tables in my database, one for leaving planes and one for arriving planes. Each of them includes a column which contains the runway sign. Now I want to make a query where I combine the two tables and count how many planes have arrived at the runway and how many have left.
This is my attempt:
SELECT runway_sign as Landebahn, [Anzahl gelandet], [Anzahl gestartet]  from
    (
        SELECT runway_sign, COUNT(runway_sign) as [Anzahl gelandet], 0 as [Anzahl gestartet] FROM tbl_arriving_planes
            GROUP BY runway_sign
    ) as b
    UNION
    SELECT runway_sign as Landebahn, [Anzahl gelandet] ,[Anzahl gestartet]  from
    (
        SELECT runway_sign, 0 as [Anzahl gelandet], COUNT(runway_sign) as [Anzahl gestartet] FROM tbl_leaving_planes
            GROUP BY runway_sign
    ) as a

Result should look like this:
runway_sign | number of arrived planes | number of leaving planes

A: You can use UNION ALL followed by another aggregation:
SELECT runway_sign as Landebahn,
       SUM([Anzahl gelandet]),
       SUM([Anzahl gestartet])
FROM ((SELECT runway_sign, COUNT(runway_sign) as [Anzahl gelandet], 0 as [Anzahl gestartet]
       FROM tbl_arriving_planes
       GROUP BY runway_sign
      ) UNION ALL
      (SELECT runway_sign as Landebahn, 0 as [Anzahl gelandet], COUNT(runway_sign) as [Anzahl gestartet]
       FROM tbl_leaving_planes
       GROUP BY runway_sign
      )
     ) al
GROUP BY runway_sign;

An alternative method uses FULL JOIN rather than UNION ALL:
SELECT COALESCE(a.runway_sign, l.runway_sign) as Landebahn,
       a.[Anzahl gelandet],
       l.[Anzahl gestartet]
FROM (SELECT runway_sign, COUNT(runway_sign) as [Anzahl gelandet]
      FROM tbl_arriving_planes
      GROUP BY runway_sign
     ) a FULL JOIN
     (SELECT runway_sign as Landebahn, COUNT(runway_sign) as [Anzahl gestartet]
      FROM tbl_leaving_planes
      GROUP BY runway_sign
     ) l
     ON l.runway_sign = a.runway_sign

A: It sounds like you want to group on the result of the UNION
SELECT runway_sign as Landebahn, SUM([Anzahl gelandet]) as [Anzahl gelandet], SUM([Anzahl gestartet]) as [Anzahl gestartet]
FROM (
    SELECT runway_sign, 1 as [Anzahl gelandet], 0 as [Anzahl gestartet] FROM tbl_arriving_planes
    UNION
    SELECT runway_sign, 0 as [Anzahl gelandet], 1 as [Anzahl gestartet] FROM tbl_leaving_planes
) as a
GROUP BY runway_sign


text:
Q: How to convert HLP files into CHM files I need some help, I have some .hlp files and I want to convert it to .chm files, as .hlp files don't run on Windows 10.
How can I do that?

A: I see two or more solutions depending on your requirements:

*

*Converting WinHelp (HLP) to HTMLHelp (CHM) or PDF

*Running WinHelp files on Windows10

Convert WinHelp (HLP) to HTMLHelp (CHM):
A tutorial on my site gives a step-by-step description how to convert WinHelp (HLP) to HTMLHelp (CHM) on a freeware/shareware and "low budget" level. The conversion project example from the download section includes a working structure and example files.
You can of course use a helpauthoring tool (HAT) like Help+Manual, HelpScribble or any other HAT to convert existing WinHelp projects to HTMLHelp.
Run WinHelp on Windows 10:
WinHlp32 for Windows 10 restores the ability to open and view .hlp files on Windows 10.

*

*WinHlp32 for Windows 10 6.3.9600.16411 (MajorGeeks) OR

*see further information and the man's way below.

The WinHelp (.hlp) format has been around since the very early 1990s and is superseded by HTML Help 1.x (.chm). Microsoft strongly advise you move away from WinHelp about ten years ago. But for a test application it's running on my Windows10 machine like a charm.

But some heavy steps to fix the bygone WinHelp Viewer. Please note I don't speak of the HTMLHelp Viewer for *.chm help files here.
Following the solution steps depends on your Windows 10 Version (32 bit or 64 bit). To find out your system type (32 bit or 64 bit), Hold the Windows+R. Type msinfo32 in the Run dialog box that appears and Press Enter.
You know, trying to open a help file (*.hlp) results on a Microsoft Support page.Error opening Help in Windows-based programs: "Feature not included" or "Help not supported".
You'll find a download link for Windows 8.1 but you have to install in a special way for Windows 10 (Windows8.1-KB917607-x64.msu).

*

*Start your command prompt as Administrator (Please NOTE - samples for German here)!

*Extract the downloaded .msu file to a temp directory

md msu-extracted
expand Windows8.1-KB917607-x64.msu /f:* .\msu-extracted

*Extract the contained CAB-File with 279 files in it.

cd msu-extracted
md cab-extracted
expand Windows8.1-KB917607-x64.cab /f:* .\cab-extracted

*Depending on your language settings locate the matching MUI-File e.g. use "cs-", "de-" or "en-". People using the x86 variant need to run "dir x86de-."

cd cab-extracted

*Navigate to the given path for your language "... de-de ..." e.g.:
cd amd64_microsoft-windows-winhstb.resources_31bf3856ad364e35_6.3.9600.20470_de-de_1ab8cd412c1028d0

*Here we'll find "winhlp32.exe.mui". Now we need to replace e.g.
%SystemRoot%\de-de\winhlp32.exe.mui with our new file:
takeown /f "%SystemRoot%\de-de\winhlp32.exe.mui"
icacls "%SystemRoot%\de-de\winhlp32.exe.mui" /grant "%UserName%":f
ren %SystemRoot%\de-de\winhlp32.exe.mui winhlp32.exe.mui.w10
copy winhlp32.exe.mui %SystemRoot%\de-de\winhlp32.exe.mui
takeown /f "%SystemRoot%\winhlp32.exe"
icacls "%SystemRoot%\winhlp32.exe" /grant "%UserName%":f
ren %SystemRoot%\winhlp32.exe winhlp32.exe.w10
cd ..
dir *.exe /s

*Find the right path starting either with amd64 or x86 and navigate
to it:
cd "amd64_microsoft-windows-winhstb_31bf3856ad364e35_6.3.9600.20470_none_1a54d9f2f676f6c2"
copy winhlp32.exe %SystemRoot%\winhlp32.exe

Edit:
You don't need to replace _none_ in the  last cd command step (all single steps tested 2017-09-01 and 2018-08-24 and working on Windows 10).
There is a reset of the workaround described above after a main Microsoft Windows update.
Edit: (copied form comments, thanks to @dxiv)
An alternative to the last couple of steps is to copy the winHlp32 files entirely elsewhere, like C:\etc[\de-de], then re-associate ftype hlpfile=C:\etc\winHlp32 %1 at an elevated command prompt. This avoids clashes with sfc and future windows updates, and HLPs would still work when opened by association (double-click in explorer, or start old.hlp at the cmd prompt).

A: You can convert HLP to HTML, using a Chrome extension:
<< CHM, HLP Viewer and Extractor >>
Proposed by : https://ehubsoft.herokuapp.com/chmviewer

A: Well people, after a long time searching, my conclusion was: .HLP files can't be executed by Windows 8 and 10, just in Windows 7 and lower. .CHM files can be executed by Windows 8 and windows 10. SO, I had to create my new .chm file in Help Development Studio on Windows 10 to be executed by it. My old files .HLP became obsolete. It took so much time to do this but I learned so much about this type of files.
Finally, thank you for your contribution to my question.

A: You are a hero sir! I ended up using HelpScribble and using its Decompiler linked here.
Quoting their website:

If you have an existing WinHelp file without the HPJ and RTF source files, you can download the WinHelp decompiler to recreate the HPJ and RTF sources from the HLP file. Extract the files inside helpdc21.zip into a new folder. Then you can easily decompile any .hlp file from the command prompt, by typing: helpdeco helpfile.hlp where helpfile.hlp is the help file you want to decompile. The decompiler will generate the HPJ and RTF files, along with a series of bitmap files if the help file contains images. Use Project|Import Help Project in HelpScribble to import the help file.

That will extract the source files for the hlp file.
Lastly, simply import the resulting hpj file in HelpScribble. From there you can simply export to a html file with the option Make Flat Manual.
Boom. Done.


text:
Q: celery doesn't run simple print I have a helloworld type function for celery:
from celery import Celery
import time
app = Celery('test_celery',
             broker= 'amqp://celeryuser:pass@ip:5672/celeryvhost',
             )

@app.task
def add(x, y):
    time.sleep(2)
    print('calculating something aaewsome --------------------')
    return x + y

if __name__ == '__main__':
    result = add.delay(4, 4)
    print( result.get() )

I run the command to run the task:
celery -A test_celery worker --loglevel=info

I get the output:
[tasks]
  . test_celery.add
[2018-07-17 00:17:40,668: INFO/MainProcess] Connected to amqp://celeryuser:**@myip:5672/celeryvhost
[2018-07-17 00:17:40,679: INFO/MainProcess] mingle: searching for neighbors
[2018-07-17 00:17:41,705: INFO/MainProcess] mingle: sync with 1 nodes
[2018-07-17 00:17:41,706: INFO/MainProcess] mingle: sync complete
[2018-07-17 00:17:41,725: INFO/MainProcess] celery@www.mysite.com ready.

In the logs it shows:
[2018-07-17 00:17:40,698: INFO/MainProcess] sync with celery@mysite.com

But no output prints.
what am I doing wrong?

A: You are not calling the celery task anywhere, that's why it's not printing.
Step.1 Open your terminal and run the command, celery -A test_celery worker --loglevel=info
Step.2 Open another terminal and import the celery task, then run it with .delay()
Screenshots
1. Celery command running

2. Calling celery task

A: Initialize the app with a result backend passed as an argument. Example
app = Celery('tasks', backend='rpc://', broker='pyamqp://')


text:
Q: not able to download file in asp .net I have uploaded my file and inserted its data into database, now when i click I want to download it.
bytes = (byte[])dsResult.Tables[0].Rows[0]["data"];
contentType.Text = dsResult.Tables[0].Rows[0]["contentType"].ToString();
fileName.Text = dsResult.Tables[0].Rows[0]["name"].ToString();

try
{
   Response.Clear();
   Response.Buffer = true;
   Response.Charset = "";
   Response.Cache.SetCacheability(HttpCacheability.NoCache);
   Response.ContentType = contentType.Text;
   Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName.Text);
   Response.BinaryWrite(bytes);
   Response.Flush();
}
catch (Exception ex)
{
   throw;
}

It's not throwing any error but it is not downloading file.

A: The file download will only begin if you set the HTML header accordingly at Page_Load. Meaning: you can't render any HTML DOM elements to the user because that would be 'html/textwhereas you requirepdf/documentorexcel/document` , etc as the content-type.
So to make it easier, have the file transfer code be in a new page with Page_Load event handling the file download code. Then from the page that user was originally at, let the user click on a link button or something that redirect him/her to the download page.
What is amazing is that the file transfer will happen without the user actually having to visit another page. The file will be downloaded, and the user will still be at the source page, even though you redirected to the download page

A: Downloading file from DB?
You have to save your file from DB into your Project Directory Folder.
You can put this in your button event:
 string s = "\\Image\\file1.jpg";
 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.ContentType = "application/octet-stream";
 Response.AddHeader("Content-Disposition", "attachment; filename=" + s);
 Response.TransmitFile(Server.MapPath("~" + s));
 Response.End();
 Response.Redirect("RedirectMe.aspx", false);


text:
Q: How to share angular library without NPM I'm developing a component library which I don't want to share in npmjs, is there any way to share my angular library with other angular projects with out sharing it with NPM.

A: yes try verdaccio which stores ur packaged library in your local storage when u npm i libraryname first it searches for library in local storage and then searches for public npm
https://verdaccio.org/docs/en/installation

A: The best way - to have your own npm registry and publish in it. It's often in medium or big companies.
Easier way - to publish your package library in git repository and add lobrary as package with git source. You can see how to do it in npm documentation. https://docs.npmjs.com/files/package.json#dependencies


text:
Q: salesforce1 Visualforce page iOS 9 issue I have a visualforce page that has the basic structure , and the elements are populated dynamically via jquery . It also uses bootstrap . The problem is the page loads as expected in iOS 8 but not iOS 9 . Any pointers to this would be good .
Thanks and Regards,
BK

A: As an workaround , i have wrapped the div with static height to give a auto scroll bar which works , and i am not using jQuery Mobile. Even with this workaround the iOS 9 scroll bar is bad , but far better than what it was.

*

*you can add webkit-scroll : touch  to fix this.


text:
Q: spring-boot: Ensure that the submitted value is one of a given set of valid choices In PHP/Symfony framework, we can validate a request value if it's one of a set of values using Choice constraint as described in this link:
https://symfony.com/doc/current/reference/constraints/Choice.html
for example, I want to test if category_id is one of the following: [1,2,3,4].
is there any way to this validation in spring-boot?

A: This problem lends itself to a simpler core java implementation. This is definitely better solved with enum, but if you'd rather use a validation library then hibernate validator is better for this case.
Example field declaration:
@Range(min = 1, max = 4)
int category_id;
https://hibernate.org/validator/

A: I found a solution to my question, I had to create a function annotated with @AssertTrue and check if the value is allowed to be submitted from the allowedValues array
like this:
int[] allowedValues = {1,2,3,4};
@AssertTrue
public boolean isValidType() {
    return IntStream.of(allowedValues).anyMatch(x -> x == this.typeId);
}


text:
Q: Mapping boundingRect()'s to parent item and intersecting yields unexpected results for collision handling Here is how I'm handling collision of two graphics items.  It gets called in mouseMoveEvent as well as itemChange.  Like so:
void GraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    auto delta = event->pos() - event->lastPos();
    auto new_pos = handleCollisions(pos() + delta);
    setPos(new_pos);
}

The new_pos thing is so I can call it in itemChange and return that as the value.  However, this version of collision handling leaves new_pos unchanged.  Instead, we move the items that collide with this one (as we move this one by mouse).  I'm trying to take the intersection of the two involved bounding rects and shifting the other one by the shorter dimension of the rectangls' intersection.  The result, which is unexpected, is that the rectangles aren't moving just that little amount, but instead by the entire width (or height) of either of the boundingRects() (they're the same size).  I've tracked it down to that, so the code below that computes the intersection of the bounding rects in the parent's position space (where pos(), setPos() are relative to), is wrong.
So how do I do I accomplish this?
Here is a picture of what I want:

QPointF GraphicsItem::handleCollisions(const QPointF& new_pos) const {
    auto collisions = collidingItems();
    auto rect = mapToParent(boundingRect().translated(new_pos - pos())).boundingRect();
    for(int k=0; k < collisions.count(); k++)
    {
        auto item = collisions[k];
        if (item->parentItem() == parentItem()) {
            auto rect1 = mapToParent(item->boundingRect()).boundingRect();
            rect1 = rect1.intersected(rect);
            qDebug() << (rect1.width());
            qDebug() << (rect1.height());
            auto v = rect1.center() - rect.center();
            if (v.x() >= 0) {
                if (v.y() >= 0) {
                    if (rect1.width() <= rect1.height())
                        item->setPos(item->pos() + QPointF(-rect1.width(), 0));
                    else
                        item->setPos(item->pos() + QPointF(0, -rect1.height()));
                }
                else {
                    if (rect1.width() <= rect1.height())
                        item->setPos(item->pos() + QPointF(rect1.width(), 0));
                    else
                        item->setPos(item->pos() + QPointF(0, rect1.height()));
                }
            }
            else {
                if (v.y() >= 0) {
                    if (rect1.width() <= rect1.height())
                        item->setPos(item->pos() + QPointF(rect1.width(), 0));
                    else
                        item->setPos(item->pos() + QPointF(0, -rect1.height()));
                }
                else {
                    if (rect1.width() <= rect1.height())
                        item->setPos(item->pos() + QPointF(rect1.width(), 0));
                    else
                        item->setPos(item->pos() + QPointF(0, rect1.height()));
                }
            }
        }
    }
    return new_pos;     // return this position unchanged
}

A: I have found it.
item->mapToParent(...)

instead of
mapToParent(...)

should be called in the loop.


text:
Q: Python Streamhandler over ftp doesn't work after second import I have the following problem:
I wrote a FTPHandler(StreamHandler), which connects via 'transport=paramiko.Transport(...)' and 'transport.connect(...)' to a server and opens a sftp connection with 'SFTPClient.from_transport(...)'.
I am importing this handler in a class named 'JUS_Logger.py', which is my module for logging. This 'FMP_Logger' is imported by another class, 'JUS_Reader'.
The problem is, that if I start 'JUS_Reader', the transport is being initialized, but the Connection fails. There is no exception, the program only hangs. If I kill it, I get the stacktrace
CTraceback (most recent call last):
  File "./JUS_Reader.py", line 24, in <module>
    from JUS_Logger import logger
  File "/<home>/.../JUS_Logger.py", line 74, in <module>
    ftpHandler=FTPHandler(ftpOut,10)
  File "/<home>/FTPHandler.py", line 21, in __init__
        self.transport.connect(username=ftpOut['user'].decode('base64'),password=ftpOut['passwd'].decode('base64'))
  File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 1004, in connect
    self.auth_password(username, password)
  File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 1165, in auth_password
    return self.auth_handler.wait_for_response(my_event)
  File "/usr/lib/python2.7/dist-packages/paramiko/auth_handler.py", line 158, in wait_for_response
    event.wait(0.1)
  File "/usr/lib/python2.7/threading.py", line 403, in wait
    self.__cond.wait(timeout)
  File "/usr/lib/python2.7/threading.py", line 262, in wait
    _sleep(delay)

However, if I'm running the 'JUS_Logger.py' by itself, everything works, the transport's connection establishes and the SFTClient connects also.
Any ideas? Or further questions?


text:
Q: UNION ALL on a Table Join I recently learned how to use the UNION ALL command. However, I don't know how to use it with a join.
Can someone show me how to modify the query below so that it performs a left join on TWO tables - gw_articles_usa and gw_articles_canada?
$stm = $pdo->prepare("SELECT WT.N, WT.URL, WT.Title,
 USA.URL, USA.Brief, USA.Article, USA.Pagedex, USA.Links
 FROM gw_topics WT
 LEFT JOIN gw_articles_usa USA ON USA.URL = WT.URL
 WHERE WT.URL = :MyURL");
 $stm->execute(array(
 'MyURL'=>$MyURL
 ));

A: Provided the usa and canada tables have the same column names and types, use the union in a subselect.
SELECT WT.N, WT.URL, WT.Title,
    COUNTRY.URL, COUNTRY.Brief, COUNTRY.Article,
    COUNTRY.Pagedex, COUNTRY.Links
 FROM gw_topics WT
 LEFT JOIN (select * from gw_articles_usa UNION ALL select * from gw_articles_canada) COUNTRY
    ON COUNTRY.URL = WT.URL
 WHERE WT.URL = :MyURL

If the two tables don't match, you can use aliases for the column names to make them match or use a constant/null for a missing column value and alias to the name of the other table.  If data types don't match, CAST or other conversion functions can be used to make them the same.  If the links was missing from one of the tables, you can do this.
select  URL, Brief, Article, Pagedex, Links from gw_articles_usa
UNION ALL
select URL, Brief, Article, Pagedex, null as Links from gw_articles_canada

This should resolve your problem.


text:
Q: How to plot 2 variables on top of each other in ggplot r? I wanted to ask how I can plot multiple variables in R so I can obtain plot like this:

On the x axis we have particular months, on y some counting variable (count is already in the data), on the legends we have 5 quantiles, but additionally I want to have 1 more variable in another legend, which is year. Ideally I would want to have It in alpha parameter, so the 5 bars and 8 months stay the same and we see 2 bars on top of each other and they are a bit transparent with 2 colors for other years (I just have 2 year) . We have this counting on top of the bars, so we can compare each quantile from 2 years.
I already wrote this, but it's plotting the data not 5 columns for each month, but stacking the quantiles in 1 bar instead.
ggplot(data, aes(month, sum, fill = year, alpha = quantiles)) +
   geom_bar(stat = "identity", position = "dodge", alpha = 0.5) +
   geom_text(aes(label = round(sum, digits = 3)), position = position_dodge(width = 1), na.rm = TRUE) +
   scale_x_continuous(labels=month, breaks =c(1,2,3,4,5,6,7,8))

A: From a data visualization point of view, having all these labels on your plot is going to make it look messy and unprofessional. If you need to display all the numbers, consider using a table instead, or a table alongside your plot.
However, you can achieve what you asked for like this:
library(ggplot2)

ggplot(data, aes(quantiles, sum, fill = factor(year))) +
  geom_col(position = "stack") +
  geom_text(aes(label = round(sum), group = year), vjust = -0.2,
            hjust = 0, angle = 45,
            position = position_stack(), na.rm = TRUE) +
  scale_x_continuous(expand = c(0.1, 0.3)) +
  facet_grid(.~month, switch = "x") +
  theme_minimal(base_size = 16) +
  labs(fill = "Year", x = "Month") +
  scale_fill_manual(values = c("lightblue", "orange")) +
  theme(axis.text.x = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank())

Data used
Obviously, we don't have your data, but I created a little data set with the same structure as yours to creste the above plot.
set.seed(1)

data <- data.frame(month = rep(rep(1:8, each = 5), 2),
                   year = rep(2021:2022, each = 40),
                   quantiles = rep(1:5, 16),
                   sum = rnorm(80, 5000, 750))


text:
Q: How to split the header of an image? I have designed a website which users upload some images and I store them in a folder.but anyone else can access the uploaded file via URL.
However I want to split the header of Uploaded images and insert the header in the database and store the rest of file in the folders.
How can I split the header of image?
If I convert the image to the array of binary how to distinguish the header part?

A: You can achieve that another way . First Encode the Bitmap to base64 and store it at an XML File ,keep XML Files if you want ordered by an ID and store within the XML 2 Items Value and BitmapString .Than from XML you can convert from Base64 to an Bitmap .
            //Convert Image to Base64
            Bitmap myBmp = new Bitmap(dialog.FileName);
            MemoryStream theStream = new MemoryStream();
            myBmp.Save(theStream, ImageFormat.Jpeg);
            String base64Containter = Convert.ToBase64String(theStream.ToArray());
            //Write String and Image ID to XML

Load image from XML assuming that you already identified the Item into XML:
            TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
            char[] theBytes = base64Containter.ToArray();
            Bitmap bitmap1 = (Bitmap)tc.ConvertFrom(Convert.FromBase64CharArray(theBytes, 0, theBytes.Length));
            this.pictureBox1.Image = bitmap1;

A: you can make use of an image handler to retrieve the image from the db instead of splitting the image,
check this link which explains how to create an use an image handler


text:
Q: Can I get Apache to alter Response Status Codes? I have a load of services all using the same block of code and all incorrectly returning a 406 (Not acceptable) when what was really wanted was a 410 (Gone). The difference is not simply one of correctness, but has other implications upstream as 410s can be cached and 406s can't.
In the long run all the underlying code is going to have to be altered and retested and it'll take time and money.
In the meanwhile it would be cool if I could simply alter all 406 responses to become a 410 as they pass through the Apache 2.2 front end.
Does anyone have a quick win for me here?
Thanks in advance.

A: This feels like a horrible hack but you could configure an error document for all 406 responses that itself sends a 410 status code:
ErrorDocument 406 http://yoursite.com/script-that-sends-410-status-code


text:
Q: What does "you are feeble and you know it " mean in the context? This part is in a Children's math book, it teaches how to use cancellation in dividing.
the sum is 270/18. 270 and 18 are both broken down to their prime factors, so it become 2x3x3x3x5/2x3x3, and the female character in the book suddenly sing "You are feeble and you know it"in the illustration nearby. What does the it mean in this context, why would she say that?
//Transcript:

270/18 = 2x3x3x3x5/2x3x3
Now we can cancel. This means if any number on the top has a matching number on the bottom, We can cross them both out!

[Illustration] "You are feeble and you know it" (the female character sings this out, holding a scarf with both hands above her head)

We are just left with 3*5 on the top, that gives the answer 15, so 270/18 = 15

A: Holding a scarf and singing shows that this is meant to be a football (soccer) chant.  Probably the suggestion is that by cancelling factors, the hard problem 270/18  has been reduced to an easy one.
Here is the point.  Many students, when faced with 270 ÷ 18 will use long division. Long division is slow and it is easy to make mistakes, but children will toil through  18 into 2 doesn't go, carry the 2, 18 into 27 goes ... once, with remainder ... 27 - 18 = 9, bring down the 0 .... and so on.
The "factorise and cancel" method breaks down the problem into small steps and you don't need to do this hard work. For a 10 year old, that is something to cheer!  And it is funny to insult the problem a bit. "You're feeble, and you know it!"
As with the rest of this book, unless you have the mind of a 10-year-old,  it will seem rather childish.


text:
Q: Firebase Cloud Function called twice onCreate I have this function:
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');

exports.myFunction = functions.database.ref('/my_node/{myId}/status').onCreate(event => {
  const data = event.data.val();
  if (data == 'STATE01') {
    return event.data.ref.set('STATE02');
  }
});

I am using onCreate, it should be called once only. But it has called 2 times

9:29:27.975 PM myFunction Function execution took 33 ms, finished with status: 'ok'
9:29:27.943 PM myFunction Function execution started
9:29:27.875 PM myFunction Function execution took 1059 ms, finished with status: 'ok'
9:29:26.818 PM myFunction Function execution started


text:
Q: Bound DataGridView is missing direction glyph on column click Using standard winforms
DataGridView in .net 2.0.
DataGridView is bound to the BindingSource.
BindingSource.DataSource is set to SortableBindingList.
Columns are created in my code and columns SortMode is set to DataGridViewColumnSortMode.Programmatic.
OnColumnHeaderClick I set multi-column sort with each column sort direction and glyph sorting order and refresh
DataGridView.
DataGridView gets sorted correctly but the column sort direction glyphs are gone.

A: In order to support multi-column sorting in SortableBindingList I had to implement IBindingView and its methods as well.
Which means in my implementation of ApplySort(ListSortDescriptionCollection sorts)
needed to set IsSorted to true or false.


text:
Q: Connection to Oracle without a username or password Oracle has this concept of allowing database users to be identified by the operating system user who is running the program that is connecting to Oracle. See here.
This allows you to do, as that user on a unix machine for example, a command such as:
sqlplus /

I am attempting to write a Java program for Oracle 10.2 which connects without a username or password. The obvious choice of url:
jdbc:oracle:thin:/@localhost:1521:MYDBSID

doesn't work, giving an error (Sorry I don't have the error available right now).
I have attempted many other forms of doing this as well, but with no luck.
Does anyone have any suggestions on how I can connect a Java program to Oracle using the OS identification method?

A: The JDBC Thin driver is a 100% pure Java implementation that cannot collect the needed information from the operating system.
The JDBC OCI driver can do this! Use jdbc:oracle:oci8:/@MYDBSID, it will require that the Oracle driver be installed on that machine, not a problem if this is a server (and is faster to boot and supports many more features than the thin driver)

A: The jdbc driver that oracle ships does NOT have the capability of gathering the OS username and password from the URL that you provide it. Suppose, there are 3rd party JDBC driver providers for ORACLE, one of them might provide the functionality that you're asking for. you should google around.

A: Thanks to those that answered. We've gone with the OCI driver.
I did find documentation to suggest that Oracle 11g does support OS user authentication via the thin driver though:
http://www.orindasoft.com/public/Oracle_JDBC_JavaDoc/javadoc1110/oracle/jdbc/OracleConnection.html#CONNECTION_PROPERTY_THIN_VSESSION_OSUSER
I don't have an 11g setup to test this on, so I can't be certain this works.

A: OS authentication support in the JDBC thin driver was added in 11g (you can download the JDBC thin driver from 11.2.0.4 on OTN).
Note that you have to allow remote OS authentication on the server (over TCP) otherwise it will only work with sqlplus using IPC or BEQ locally. In your init.ora file, add this:
REMOTE_OS_AUTHENT = TRUE

Then if you user is "osuserdemo" on the client machine, create a database user like this and restart the DB:
 CREATE USER OSUSERDEMO IDENTIFIED EXTERNALLY;
 GRANT CONNECT,CREATE SESSION,RESOURCE TO OSUSERDEMO;

And the JDBC thin driver should be able to connect without any username or password.
It's worth noting that this feature - considered as highly unsecured - has been de-supported in 12c.

A: If you're accessing Oracle from a J2EE appserver, you could achieve a similar end by using JNDI to acquire a datasource.

A: The 11g thin driver can connect using Kerberos authentication.
See Connect to an Oracle database using Kerberos

A: try following
jdbc:oracle:thin:username/password@localhost:1521:MYDBSID
you need to specify the account information
sqlplus / as sysdba on a unix machine which go through the operation system autentication

A: jdbc:oracle:oci:@ works with ojdbc6.jar and Oracle 11g2


text:
Q: SQLite Changing primary key value Is there any way to change the value of the only unique identifier for a row in SQLite? Something like
if(ID == 5) ID = 4;

I tried
UPDATE Table SET ID = Value WHERE ID = DifferentValue

But it does not seem to do a trick.
The reason for this is that I don't auto-increment IDs as I prefer them to be set by programme because I have different methods when ID is odd and ID is even and I might need to switch the IDs in case some entry gets deleted so to compress the numbers so they don't leave blank ID spaces between them.
Programme is written in C# if that helps.
EDIT: The column is NOT truly dedicated as a PK in the db, it is jut NOT NULL integer that I control myself on non-duplicates so that it can serve as a PK


text:
Q: How to call Cordova plugin methods from Meteor? New to Meteor here. I'm having trouble calling Cordova plugin methods from Meteor.
Here is the plugin I care about:
http://plugins.cordova.io/#/package/com.phonegap.plugins.barcodescanner
I added the package in command line:
meteor add cordova:com.phonegap.plugins.barcodescanner@2.0.1
Below is my javascript code. What ends up happening is on startup, the onCallback method loads, but no barcode scanning happens and neither onSuccess nor onError gets called. I've tried similar approach with other cordova packages but nothing works. I've also tried replacing 'cordova.plugins.barcodeScanner.scan' in the cordova.call with variations like all lower caps, 'barcodeScanner.scan', 'com.phonegap.plugins.barcodescanner.scan', etc., but to no avail.
if (Meteor.isCordova) {
    Meteor.startup(function () {
        cordova = new Cordova();
        cordova.addEventListener('deviceready', function() {
            function onSuccess(result) {
                alert("We got a barcode\n" +
                    "Result: " + result.text + "\n" +
                    "Format: " + result.format + "\n" +
                    "Cancelled: " + result.cancelled);
            }

            function onError(error) {
                alert("Scanning failed: " + error);
            }

            function onCallback(msg) {
                alert("Callback! " + msg);
            }

            cordova.call(
                'cordova.plugins.barcodeScanner.scan',
                [onSuccess, onError],
                onCallback);
        });
    }
}

A: In a Meteor Cordova App, Meteor.startup works as the deviceready event so you won't need the deviceready event. Also cordova is already defined in the global context so you won't need to try to creat a new instance. Finally, reading the plugin page on plugins.cordova.io explains that the plugin is namespaced to cordova.plugins.barcodeScanner. In your case the scan method on the barcodeScanner class is of particular interest. You can use it in meteor like below, but take note this will open the scanner when the app starts up from a full stop so it's probably better to invoke the scan method from something such as a click event.
if(Meteor.isCordova){
    Meteor.startup(function () {
        cordova.plugins.barcodeScanner.scan(
            function (result) {
                alert("We got a barcode\n" +
                  "Result: " + result.text + "\n" +
                  "Format: " + result.format + "\n" +
                  "Cancelled: " + result.cancelled);
            },
            function (error) {
                alert("Scanning failed: " + error);
            }
        );
    });
}


text:
Q: Trying to open the dialog to specify project path in netbeans takes literally 2 minutes What i mean is i'm trying to open a project and the window to specify the path comes up that takes 2 minutes to open. If i click desktop it takes another 2 minutes to open desktop contents. What is going on i'm going insane. That never happened before.
I tried using another java app and it does the same thing every time i have to choose the file.
Netbeans displays this message that i have found no fix yet: https://imgur.com/a/RVhewcf


text:
Q: rmagick install extconf.rb error Hi I'm trying to install rmagick for like 10 hours, the frustration is immense..
So here follows:
c:\>ruby -v
ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]

c:\>rails --version
Rails 5.0.0

c:\>gem --version
2.4.5.1

c:\Ruby22\bin>convert -version
Invalid drive specification.

c:\ImageMagick-6.9.5-Q16>convert -version
Version: ImageMagick 6.9.5-3 Q16 x86 2016-07-22 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2015 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Visual C++: 180040629
Features: Cipher DPC Modules OpenMP
Delegates (built-in): bzlib cairo flif freetype jng jp2 jpeg lcms lqr openexr pa
ngocairo png ps rsvg tiff webp xml zlib

and finally when im trying to install (i also have DevKit)
c:\Ruby22>gem install rmagick -- --with-opt-dir=c:\ImageMagick-6.9.5-Q16
Temporarily enhancing PATH to include DevKit...
Building native extensions with: '--with-opt-dir=c:\ImageMagick-6.9.5-Q16'
This could take a while...
ERROR:  Error installing rmagick:
        ERROR: Failed to build gem native extension.

    C:/Ruby22/bin/ruby.exe -r ./siteconf20160725-4412-1q7n0st.rb extconf.rb --wi
th-opt-dir=c:\ImageMagick-6.9.5-Q16
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/Ruby22/bin/$(RUBY_BASE_NAME)
extconf.rb:110:in ``': No such file or directory - identify -version (Errno::ENO
ENT)
        from extconf.rb:110:in `configure_compile_options'
        from extconf.rb:16:in `initialize'
        from extconf.rb:517:in `new'
        from extconf.rb:517:in `<main>'

extconf failed, exit code 1

Gem files will remain installed in C:/Ruby22/lib/ruby/gems/2.2.0/gems/rmagick-2.
15.4 for inspection.
Results logged to C:/Ruby22/lib/ruby/gems/2.2.0/extensions/x86-mingw32/2.2.0/rma
gick-2.15.4/gem_make.out

I've tried many many solutions , nothing works , just keep getting this error.
I messed with %PATH% ,tried different versions , read all the instructions , tried in 2 different machines. It seems impossible for me..
the suggested duplicate offers obsolete links that lead nowhere, even if it is a duplicate of an answered question , that answer is not up to date and offers no good.  I truly wish that could help , but i came across that answer a while ago...


text:
Q: Missing "minLength" in ReactDom in Safari React JSX:
<input
    type="password"
    name="password"
    value={this.state.password}
    minLength={2}
    maxLength={4}
    required="required"
    onChange={e => this.handleOnChange(e)}
    placeholder="Password"/>

handler:
handleOnChange = (e) => {
    console.dir(e.target)
    console.dir(e.target.minLength) // ==> expected value is 2, but undefined
    console.dir(e.target.maxLength) // ==> 4

In Chrome, I'm able to find the "minLength". But in Safari, missing key-value paris of "minLength".
"maxLength" does exist.
I don't have a grip of this problem, Does Safari not implement "minLength"?
Version:

*

*Safari 9.1.1 (11601.6.17)

A: Nope, Safari doesn't implement it: http://caniuse.com/#feat=input-minlength
You might want to try using the pattern attribute or one of the other answer to this question: Is there a minlength validation attribute in HTML5?


text:
Q: which is better using  or ? I've been writing an HTML/PHP code that sends data using a Form.
I found that I can use <button> with ajax to send the data, or use <input type= submit> to do the same task.
I want to know which is better or preferable to use and why?

A: Function of both tag is same in the form with type attribute.
<input type="submit" value="Post" />
<button type="submit">Post</button>


text:
Q: Excel 2013 - Transforming data in Excel I need advice as to how I can create a data entry worksheet in Excel and have it transform into a table in a separate worksheet. This is used for tracking the location of items shipped to different locations.
Sample Data - this is the page for data entry
Based on the data, plot into a table like this for easier reference
Once an item is taken back, the information is deleted and the shipping process continues.  Not sure if this can be done in Excel but am just exploring possibilities.

A: Assuming the source data (1st table) is located in Sheet1, Column A-D, and the 2nd table is in Sheet2, with the "Item Code" text is in A1, "WH1"-"WH3" is in B1-D1.
Put in A2 of sheet2 :
=IF(Sheet1!A2="","",Sheet1!A2)

and drag downwards. Then in B2, put :
=IFERROR(INDEX(Sheet1!$C:$C,MATCH(1,INDEX((Sheet1!$A:$A=$A2)*(Sheet1!$B:$B=B$1),0,1),0))&" ("&TEXT(INDEX(Sheet1!$D:$D,MATCH(1,INDEX((Sheet1!$A:$A=$A2)*(Sheet1!$B:$B=B$1),0,1),0)),"MM/DD/YY")&")","")

and drag till D6.
Idea : use multiple criteria index match to 'load' the values based on values in columnA Sheet2 and Row1 Sheet2.
Hope it helps. (:

Extra info :
The $ in the formula are used to 'lock' the column/row when we copy/drag the 1 cell formula. It saves a LOT of formula re-write when some of the formula element doesn't change per row/column.


text:
Q: Omit output when calling seqdef I wonder if it is possible to omit the output of the function seqdef of TraMineR. I do not see any verbose argument or similar.
Thank you!
Víctor

A: You probably mean suppressing messages. So just use suppressMessages(seqdef(...)) as in the example below. Note that suppressMessages is a base R function and can be used with other functions such as seqdist or seqrep.
library(TraMineR)
data(biofam)
biofam.lab <- c("Parent", "Left", "Married", "Left+Marr",
                "Child", "Left+Child", "Left+Marr+Child", "Divorced")
biofam.short <- c("P","L","M","LM","C","LC","LMC","D")
biofam.seq <- suppressMessages(seqdef(biofam[,10:25], alphabet=0:7,
                     states=biofam.short, labels=biofam.lab))


text:
Q: SQL Server performance: PREEMPTIVE_OS_DELETESECURITYCONTEXT dominant wait type I received a call yesterday from a customer who was complaining about high CPU usage on their SQL Server. We're using SQL Server 2012 64 bit SE. Server is running Windows Server 2008 R2 Standard, 2.20 GHz Intel Xeon (4 Cores), 16 GB RAM.
After making sure that the culprit was in fact SQL Server, I took a look at the top waits for the instance using the DMV query here. The top two waits were: (1) PREEMPTIVE_OS_DELETESECURITYCONTEXT and (2) SOS_SCHEDULER_YIELD.
EDIT: Here are the result of the "top waits query" (although someone restarted the server this morning against my wishes):

We do a lot of intense calculations/conversion, so I can understand SOS_SCHEDULER_YIELD. However, I am very curious about the PREEMPTIVE_OS_DELETESECURITYCONTEXT wait type and why it might be the highest.
The best description/discussion that I can find on this wait type can be found here. It mentions:

The PREEMPTIVE_OS_ wait types are calls that left the database engine, typically to a Win32 API, and are performing code outside of SQL Server for various task.  In this case, it is deleting a security context previously used for remote resource access.  The related API is actually named DeleteSecurityContext()

To my knowledge, we don't have any external resources like linked servers or filetables. And we don't do any impersonation, etc. Could a backup have caused this to spike or maybe a faulty domain controller?
What the heck could cause this to be the dominant wait type? How can I track this wait type further?
Edit 2: I checked the contents of the Windows Security Log. I see a few entries that may be of interest, but I'm not sure if these are normal:
Special privileges assigned to new logon.

Subject:
    Security ID:        NT SERVICE\MSSQLServerOLAPService
    Account Name:       MSSQLServerOLAPService
    Account Domain:     NT Service
    Logon ID:       0x3143c

Privileges:     SeImpersonatePrivilege

Special privileges assigned to new logon.

Subject:
    Security ID:        NT SERVICE\MSSQLSERVER
    Account Name:       MSSQLSERVER
    Account Domain:     NT Service
    Logon ID:       0x2f872

Privileges:     SeAssignPrimaryTokenPrivilege
            SeImpersonatePrivilege

Edit 3: @Jon Seigel, as you requested, here are the results of your query. A little different than Paul's:

Edit 4: I admit, I'm a first time Extended Events user. I added this wait type to the wait_info_external event and saw hundreds of entries. There is no sql text or plan handle, only a call stack. How can I further track down the source?

A: I know this question, based on the Title, is mainly concerned with the PREEMPTIVE_OS_DELETESECURITYCONTEXT wait type, but I believe that is a misdirection of the true issue which is " a customer who was complaining about high CPU usage on their SQL Server ".
The reason I believe that focusing on this specific wait type is a wild goose chase is because it goes up for every connection made. I am running the following query on my laptop (meaning I am the only user):
SELECT *
FROM sys.dm_os_wait_stats
WHERE wait_type = N'PREEMPTIVE_OS_DELETESECURITYCONTEXT'

And then I do any of the following and re-run this query:

*

*open a new query tab

*close the new query tab

*run the following from a DOS prompt: SQLCMD -E -Q "select 1"
Now, we know that CPU is high so we should look at what is running to see what sessions have high CPU:
SELECT req.session_id AS [SPID],
       req.blocking_session_id AS [BlockedBy],
       req.logical_reads AS [LogReads],
       DB_NAME(req.database_id) AS [DatabaseName],
       SUBSTRING(txt.[text],
                 (req.statement_start_offset / 2) + 1,
                 CASE
                     WHEN req.statement_end_offset > 0
                        THEN (req.statement_end_offset - req.statement_start_offset) / 2
                     ELSE LEN(txt.[text])
                 END
                ) AS [CurrentStatement],
       txt.[text] AS [CurrentBatch],
       CONVERT(XML, qplan.query_plan) AS [StatementQueryPlan],
       OBJECT_NAME(qplan.objectid, qplan.[dbid]) AS [ObjectName],
       sess.[program_name],
       sess.[host_name],
       sess.nt_user_name,
       sess.total_scheduled_time,
       sess.memory_usage,
       req.*
FROM sys.dm_exec_requests req
INNER JOIN sys.dm_exec_sessions sess
        ON sess.session_id = req.session_id
CROSS APPLY sys.dm_exec_sql_text(req.[sql_handle]) txt
OUTER APPLY sys.dm_exec_text_query_plan(req.plan_handle,
                                        req.statement_start_offset,
                                        req.statement_end_offset) qplan
WHERE req.session_id <> @@SPID
ORDER BY req.logical_reads DESC, req.cpu_time DESC
--ORDER BY req.cpu_time DESC, req.logical_reads DESC

I usually run the above query as it is, but you could also switch which ORDER BY clause is commented out to see if that gives more interesting / helpful results.
Alternatively you can run the following, based on dm_exec_query_stats, to find highest-cost queries. The first query below will show you individual queries (even if they have multiple plans) and is ordered by Average CPU Time, but you can easily change that to be Average Logical Reads. Once you find a query that looks like it is taking a lot of resources, copy the "sql_handle" and "statement_start_offset" into the WHERE condition of the second query below to see the individual plans (can be more than 1). Scroll to the far right and assuming there was an XML Plan, it will display as a link (in Grid Mode) which will take you to the plan viewer if you click on it.
Query #1: Get Query Info
;WITH cte AS
(
   SELECT qstat.[sql_handle],
          qstat.statement_start_offset,
          qstat.statement_end_offset,
          COUNT(*) AS [NumberOfPlans],
          SUM(qstat.execution_count) AS [TotalExecutions],

          SUM(qstat.total_worker_time) AS [TotalCPU],
          (SUM(qstat.total_worker_time * 1.0) / SUM(qstat.execution_count)) AS [AvgCPUtime],
          MAX(qstat.max_worker_time) AS [MaxCPU],

          SUM(qstat.total_logical_reads) AS [TotalLogicalReads],
   (SUM(qstat.total_logical_reads * 1.0) / SUM(qstat.execution_count)) AS [AvgLogicalReads],
          MAX(qstat.max_logical_reads) AS [MaxLogicalReads],

          SUM(qstat.total_rows) AS [TotalRows],
          (SUM(qstat.total_rows * 1.0) / SUM(qstat.execution_count)) AS [AvgRows],
          MAX(qstat.max_rows) AS [MaxRows]
   FROM sys.dm_exec_query_stats  qstat
   GROUP BY qstat.[sql_handle], qstat.statement_start_offset, qstat.statement_end_offset
)
SELECT  cte.*,
        DB_NAME(txt.[dbid]) AS [DatabaseName],
        SUBSTRING(txt.[text],
                  (cte.statement_start_offset / 2) + 1,
                  CASE
                      WHEN cte.statement_end_offset > 0
                          THEN (cte.statement_end_offset - cte.statement_start_offset) / 2
                      ELSE LEN(txt.[text])
                  END
                 ) AS [CurrentStatement],
        txt.[text] AS [CurrentBatch]
FROM cte
CROSS APPLY sys.dm_exec_sql_text(cte.[sql_handle]) txt
ORDER BY cte.AvgCPUtime DESC

Query #2: Get Plan Info
SELECT  *,
        DB_NAME(qplan.[dbid]) AS [DatabaseName],
        CONVERT(XML, qplan.query_plan) AS [StatementQueryPlan],
        SUBSTRING(txt.[text],
                  (qstat.statement_start_offset / 2) + 1,
                  CASE
                        WHEN qstat.statement_end_offset > 0
                        THEN (qstat.statement_end_offset - qstat.statement_start_offset) / 2
                        ELSE LEN(txt.[text])
                  END
                 ) AS [CurrentStatement],
        txt.[text] AS [CurrentBatch]
FROM sys.dm_exec_query_stats  qstat
CROSS APPLY sys.dm_exec_sql_text(qstat.[sql_handle]) txt
OUTER APPLY sys.dm_exec_text_query_plan(qstat.plan_handle,
                                        qstat.statement_start_offset,
                                        qstat.statement_end_offset) qplan
-- paste info from Query #1 below
WHERE qstat.[sql_handle] = 0x020000001C70C614D261C85875D4EF3C90BD18D02D62453800....
AND qstat.statement_start_offset = 164
-- paste info from Query #1 above
ORDER BY qstat.total_worker_time DESC

A: The SecurityContext is used by the sql server in several places. One example which you've named are the linked servers and filetables. Maybe you're using cmdexec? SQL Server Agent jobs with proxy accounts? Calling a webservice? Remote resources can be a lot of funny things.
Impersonation events can be logged in the windows security event. It could be that you're finding a clue there. Furthermore you might want to check the blackbox recorder aka extended events.
Have you checked whether these Wait-Types are new (and in connection to the high cpu) or just normal for your server?


text:
Q: When is getdate and strptime not included in time.h? So the function getdate_r seems to be undefined for me; compiling the following doesn't work in either gcc or clang, (the man page program also doesn't work)
#include <time.h>

int main() {
    char timeString[] = "2015/01/01 10:30:50";
    struct tm res = {0};
    int err = getdate_r(timeString, &res);
    return err;
}

clang reports the following
test.c:6:12: warning: implicit declaration of function 'getdate_r' is invalid
      in C99 [-Wimplicit-function-declaration]
        int err = getdate_r(timeString, &res);
                  ^
1 warning generated.

Other functions from time.h such as getdate, strptime also don't work in a similar manner.
Anyone have an explanation on whats going on?
clang version information
Ubuntu clang version 3.6.0-2ubuntu1 (tags/RELEASE_360/final) (based on LLVM 3.6.0)
Target: x86_64-pc-linux-gnu
Thread model: posix

A: To make getdate_r available you need to:
#define _GNU_SOURCE 1

before including any include files. Doing so will provide declarations for various GNU extensions including getdate_r:
#define _GNU_SOURCE 1
#include <time.h>

int main(void) {
    char timeString[] = "2015/01/01 10:30:50";
    struct tm res = {0};
    int err = getdate_r(timeString, &res);
    return err;
}


text:
Q: How is the child access another child's protected member via member method How is this compiled? variable d inside protected. How child class method works able to modify another instance of child class protected member variable? Can the child access another child's protected member via member method
#include <iostream>

using namespace std;

class Parent
{
public:
    void print()
    {
        cout << d;
    }
protected:
    int d = 2;
};

class Child : public Parent
{

public:
    void works(Child* some_other_child)
    {
        some_other_child->d = 3;
    }
};

int main()
{
    Parent *p = new Parent();
    Child *c = new Child();
    Child *co = new Child();
    c->works(co);
    co->print();
    return 0;
}

A: protected and private keywords limit which classes can access a member-variable, not which objects can access it.
As such, code in the Child::works() method is able to access the protected Parent::d member-variable of any Child object, because Child is a subclass of Parent.

A: Because the Child class is inherited from the Parent class, the Child class inherits the int d member variable. When the constructor of Child class is called, it creates the int d member variable as a member of Child class. The int d in Child is again a protected member variable.
Then if you call a method of Child class it naturally has access to all members of class it is owned by. So as the works method is owned by Child class, it has access to int d member variable and it is allowed to change it (if you don't make it a const method, such as void works(Child* some_other_child) const, it would mean, that the method is not allowed to change any member variables of its class).
When you pass a pointer (or a reference) to another object of Child, as it is called from Child's method it can change the members too, because it has access to Child's member variables.


text:
Q: Flutter webview_plugin performance implications The Flutter web team says that for the moment HTML documents are better for (dressing) large bodies of text than dressing with the Flutter Widget framework, Flutter excel at programmatic apps.
So I have a large amount of text & pictures & animations, which would benefit from HTML's dressing & flexibility, but there are elements I want to program.
The Flutter youtube teaching team says that Webview touch events are deprioritised when using Flutter's webview plugin, this could result in jank on scrolling or latency on HTML css buttons responding, or latency on CSS or SVG Smil animations firing.  A bad user experience.
The HTML files would mostly be kept in my apps asset folder on the device. Does anyone have some guidelines to maximise performance when working with Flutter webviews?
The ideal user experience would be a GoogleMap, tap a marker, and a SlidingPanel rides up, with a few native Flutter buttons as a header, below which is a very tall webView with lots of HTML.

*

*Would it be better to Navigate to a clean page when a Marker's
onTapped?  So the googlemap isn't sitting in the background.

*Would
it be better not to mix Flutter buttons in a header, with a HTML
webview as the body?

A: In my experience at least, having just emerged from some of this, when a webview is what the user is interacting with flutter uses almost no cpu. (I'm not sure if many touch events change this equation much). But it is easy to write a poor performing flutter widget tree. Since we tend to make widget trees more and more complex to do what looks right, and then check for performance at the end, and then discover performance is poor, there isn't much that can be done. A complex widget tree that isn't getting events and repainting, is ok, of course.
A web view can be confined to any size and if there is no overlap/interactin with flutter widgets then I think whatever goes on in the web view is not triggering cpu elsewhere on the page. So there is no benefit to making a webview full screen.


text:
Q: Validation message on span title - MVC I have the following sittuation:
    [Required(ErrorMessage = "Campo obrigatório!")]
    [MaxLength(10, ErrorMessage = "Tamanho excedido!")]
    [CustomDataAnnnotations.EhTelefoneViciado(ErrorMessage="Teste de validacao")]
    public string NumeroTelefone1 { get; set; }

    [CustomDataAnnnotations.ValidarDataAtual(ErrorMessage = "Data futura!")]
    [Required(ErrorMessage = "Campo obrigatório!")]
    [Display(Name = "Data Ocorrido *")]
    public string DataOcorridos { get; set; }

This, generate the following HTML:

 Data futura!

Why on first scenario the message is in the TITLE of the SPAN and on the second IN the SPAN ?
What i have to do, to generate like the second one?
I allready referenced the .js :
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/Scripts/jquery.validate.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.js")

@{Html.EnableClientValidation(true);}
@{Html.EnableUnobtrusiveJavaScript(true);}

Help me, please.
EDIT: Below are the CustomDataAnnotation:
  public class CustomDataAnnnotations
{
    public class ValidarDataAtualAttribute : ValidationAttribute
    {
        public ValidarDataAtualAttribute()
        {
        }

        public override bool IsValid(object value)
        {
            //var dt = (DateTime)value;
            var dt = DateTime.Parse(value.ToString());
            if (dt <= DateTime.Now)
            {
                return true;
            }
            return false;
        }

    }

    public class EhTelefoneViciadoAttribute : ValidationAttribute
    {
        public EhTelefoneViciadoAttribute()
        {
        }

        public override bool IsValid(object value)
        {
            if (value == null) { return true; }

            var numeroTelefone = value.ToString();

            if (numeroTelefone.Length >= 8)
            {
                numeroTelefone = numeroTelefone.PadRight(8);

                String[] telefonesViciados = { "00000000", "11111111", "22222222", "33333333", "44444444", "55555555", "66666666", "77777777", "88888888", "99999999", "21212121", "10101010", "12121212", "23232323", "65656565", "45454545", "56565656", "78787878", "89898989" };

                if (telefonesViciados.Contains(numeroTelefone))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return true;
            }
        }

    }
}

EDIT02: The HTML:
   @Html.EditorFor(model => model.NumeroTelefone1, new { htmlAttributes = new { @class = "border-corner", @onkeydown = "return ValidateNumber(event);" } })
   @Html.ValidationMessageFor(model => model.NumeroTelefone1, "", new { @class = "erro" }

EDIT03: The validation error ( The label "TESTE" has to be on the side of the red cross)

A: As i understand you are using some custom validation attributes (server-side validation only). So you expect the same validation to happen automatically on the client-side (with jquery validate).
First you need to add one more script which is jquery.unobtrusive-ajax.js. And if you want to have support on the client for your custom validation attributes take a look at this question in StackOverflow that i had made around 2 years ago. Hope it helps.

A: thank you all for replying !
I found the error on a javascript function that was implemented on the code:
 $(document).ready(function () {
      $('.field-validation-error').each(function () {
           $(this).attr('title', $(this).html());
            $(this).html("")
        });
    });

This little bugga, it's the reason for my headache !
Anyway, thanks for the help !


text:
Q: How do combine tables and views? How do you combine tables and views into one query? I have two Select statements one is inner join already I would like to combine the table and views in the second select and make one query.
SELECT PROJECT.PROJ_ID,
       PROJECT.HULL_NUM_ID,
       PROJECT.SHIP_TYPE_CD,
       PROJECT.PROJ_NM,
       ICP_SUMMARY.MOD_STOP_DT
  FROM BAIM.ICP_SUMMARY ICP_SUMMARY
 INNER JOIN BAIM.PROJECT PROJECT
    ON ICP_SUMMARY.PROJ_ID = PROJECT.PROJ_ID

SELECT ICP_SUMMARY_JS_VW.PROJ_ID,
       ICP_SUMMARY_JS_VW.LBR_EST_MANDAYS,
       ICP_SUMMARY_JS_VW.LBR_ICP_MANDAYS,
       ICP_SUMMARY_JS_VW.MATL_EST_COST,
       ICP_SUMMARY_JS_VW.MATL_ICP_COST,
       ICP_SUMMARY_JS_VW.TOTAL_EST_COST,
       ICP_SUMMARY_JS_VW.TOTAL_ICP
  FROM BAIM.ICP_SUMMARY_JS_VW ICP_SUMMARY_JS_VW

A: You treat views just like you would a table.  You can perform joins on views, and you can have as many views as you need in the select statement.

A: You just need to JOIN on the table and the view, similar to this:
SELECT PROJECT.PROJ_ID,
       PROJECT.HULL_NUM_ID,
       PROJECT.SHIP_TYPE_CD,
       PROJECT.PROJ_NM,
       ICP_SUMMARY.MOD_STOP_DT,
       ICP_SUMMARY_JS_VW.PROJ_ID,
       ICP_SUMMARY_JS_VW.LBR_EST_MANDAYS,
       ICP_SUMMARY_JS_VW.LBR_ICP_MANDAYS,
       ICP_SUMMARY_JS_VW.MATL_EST_COST,
       ICP_SUMMARY_JS_VW.MATL_ICP_COST,
       ICP_SUMMARY_JS_VW.TOTAL_EST_COST,
       ICP_SUMMARY_JS_VW.TOTAL_ICP
  FROM BAIM.ICP_SUMMARY ICP_SUMMARY
 INNER JOIN BAIM.PROJECT PROJECT
    ON ICP_SUMMARY.PROJ_ID = PROJECT.PROJ_ID
 INNER JOIN BAIM.ICP_SUMMARY_JS_VW ICP_SUMMARY_JS_VW -- do JOIN Here
    ON ICP_SUMMARY.PROJ_ID = ICP_SUMMARY_JS_VW.PROJ_ID -- select the field to JOIN on


text:
Q: Booting time too long and repatedly freezes the system I installed or upgraded to Ubuntu 16.04, but I'm having some problems with working on Netbeans IDE(PHP), the whole system freezes repeatedly .Does the issue related to netbeans or 16.04
`dmesg` results some errors like

[ 1469.495610] blk_update_request: I/O error, dev sdc, sector 15837560
[ 1469.495618] Buffer I/O error on dev sdc1, logical block 1979488, lost async page write
[ 1469.495630] Buffer I/O error on dev sdc1, logical block 1979489, lost async page write
[ 1469.495635] Buffer I/O error on dev sdc1, logical block 1979490, lost async page write
[ 1469.495640] Buffer I/O error on dev sdc1, logical block 1979491, lost async page write
[ 1469.495645] Buffer I/O error on dev sdc1, logical block 1979492, lost async page write
[ 1469.495651] Buffer I/O error on dev sdc1, logical block 1979493, lost async page write
[ 1469.495656] Buffer I/O error on dev sdc1, logical block 1979494, lost async page write
[ 1469.495662] Buffer I/O error on dev sdc1, logical block 1979495, lost async page write
[ 1469.495667] Buffer I/O error on dev sdc1, logical block 1979496, lost async page write
[ 1469.495671] Buffer I/O error on dev sdc1, logical block 1979497, lost async page write
[ 1469.497310] sd 7:0:0:0: [sdc] tag#0 FAILED Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK
[ 1469.497318] sd 7:0:0:0: [sdc] tag#0 CDB: Write(10) 2a 00 00 f1 aa 68 00 00 f0 00
[ 1469.497322] blk_update_request: I/O error, dev sdc, sector 15837800
[ 1469.504960] sd 7:0:0:0: [sdc] Synchronizing SCSI cache
[ 1469.505032] sd 7:0:0:0: [sdc] Synchronize Cache(10) failed: Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK

And  systemd-analyze blame giving output
 7.337s dev-sda6.device
      6.274s ModemManager.service
      5.634s snapd.refresh.service
      5.414s apparmor.service
      4.967s accounts-daemon.service
      4.744s apport.service
      4.214s networking.service
      3.897s systemd-logind.service
      3.895s speech-dispatcher.service
      3.735s thermald.service
      3.700s wpa_supplicant.service
      3.671s systemd-user-sessions.service
      3.670s pppd-dns.service
      3.293s avahi-daemon.service
      2.966s NetworkManager.service
      2.703s console-setup.service
      2.324s gpu-manager.service
      2.143s grub-common.service
      1.839s systemd-udevd.service
      1.192s dns-clean.service
      1.131s systemd-tmpfiles-setup.service
      1.129s systemd-tmpfiles-clean.service
      1.127s plymouth-start.service
      1.125s rsyslog.service
      1.073s systemd-modules-load.service
      1.050s keyboard-setup.service
      1.047s polkitd.service
       874ms systemd-journald.service
       823ms systemd-tmpfiles-setup-dev.service
       822ms irqbalance.service
       820ms lightdm.service
       737ms systemd-backlight@backlight:intel_backlight.service
       718ms ondemand.service
       681ms systemd-update-utmp.service
       593ms udisks2.service
       587ms apt-daily.service
       569ms systemd-hostnamed.service
       538ms resolvconf.service
       530ms upower.service
       464ms dev-hugepages.mount
       426ms systemd-journal-flush.service
       411ms kmod-static-nodes.service

then execute command fdisk -ls
    Disk /dev/ram0: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram1: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram2: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram3: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram4: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram5: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram6: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram7: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram8: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram9: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram10: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram11: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram12: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram13: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram14: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/ram15: 64 MiB, 67108864 bytes, 131072 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk /dev/sda: 298.1 GiB, 320072933376 bytes, 625142448 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: dos
Disk identifier: 0xc3ffc3ff

Device     Boot     Start       End   Sectors   Size Id Type
/dev/sda1  *       206848 102402047 102195200  48.7G  7 HPFS/NTFS/exFAT
/dev/sda2       102402048 335874047 233472000 111.3G  7 HPFS/NTFS/exFAT
/dev/sda3       335874048 581634047 245760000 117.2G  7 HPFS/NTFS/exFAT
/dev/sda4       581636094 625141759  43505666  20.8G  5 Extended
/dev/sda5       581636096 583634943   1998848   976M 82 Linux swap / Solaris
/dev/sda6       583636992 625141759  41504768  19.8G 83 Linux

Partition 4 does not start on physical sector boundary.

Can you please suggest any solution


text:
Q: How Do I GET a StreamResponseBody and save it as a ZIP file using Powershell I am trying to extract a streaming response from a standard http GET call using PowerShell.
I tried to do something like using this Invoke-RestMethod method, such as:
$response = Invoke-RestMethod -Uri $uri -Method GET -Headers $headers -Body

and then tried doing various things like accessing the streaming response in this way:
$Stream.Write($response.Content)

or
$Stream.Write($response.RawContentStream)

but nothing works.

A: In the end, I found out the following command does both the call and the response along with allowing you to save the result to a file directly. This surprised me because the response is a multipart record that includes headers and other data, not just the chunked file in the stream. But the folks at MS apparently knew that 99% of the time with a chunked reply, the user only wants to save the streamed chunks of data into the file, without the other response header data.
  $Response = Invoke-WebRequest @Params -Headers $headers -outfile $TempZipFileName

The key here is using the Invoke-WebRequest call with the -outfile option. This saved me a lot of headache and was super simple to use.


text:
Q: Exception when accessing active directory in asp.net using the default application pool identity I am getting an exception when trying to access active directory using the default application pool identity [IIS APPPOOL\{application pool name}].
the exception I get is

System.Runtime.InteropServices.COMException: An operations error occurred.

when attempting
var userFound = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, userName)

This same code works with when using Network Service as the application pool identity, but I would like to know how to get this working using the default application pool identity.
Thanks

A: I suspect the default identity doesn't have permission to access AD.  You could try using a domain account for the application pool identity, or specify a username and password when constructing your PrincipalContext.


text:
Q: Add Mobile XXM sitemap and "Desktop" sitemap for a site with different HTML on the same URL? On my sites, I used the scheme that Google defines: "Dynamically serving different HTML on the same URL" when I offer a mobile version of my code. I have only one URL for each page. By checking the user agent, I decide the version of the site that should appear. I have already a normal XML sitemap of my site and now I want to add a mobile sitemap. Something like this:
<?xml version="1.0" encoding="UTF-8" ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
 xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0">
 <url>
   <loc>http://mobile.example.com/articolo100.html</loc>
<mobile:mobile/>

I know that I can add only URLs that provide mobile contents, in my case any URL dynamic serves desktop and mobile needs. I don't want to know if my sites will gain some pagerank with the attribution of a Mobile sitemap. I want to know if is correct to add the mobile sitemap and the "desktop" sitemap in a site of type "Dynamically serving different HTML on the same URL". With this kind of content organization I have to remove all the sitemaps?


text:
Q: External SSD won't unmount due to socketfilterfw When trying to unmount my Samsung T3, which I store various applications like Mathematica on, I am told it is being used by some software socketfilterfw
$ diskutil unmount /dev/disk2s1
Volume External on disk2s1 failed to unmount: dissented by PID=304
(/usr/libexec/ApplicationFirewall/socketfilterfw)

This also shows when unmounting using the GUI and checking in Console.app
I think socketfilterfw is involved in the firewall, however I'm not sure how to fix it or why it is happening, and whether or not it is safe for the SSD to force unmounting.
What options do I have?

A: The easiest and safest thing is to log out of the account on the Mac. (Apple Menu - log out)
This does two things:

*

*All applications are told to quit and you can identify any apps that are stuck / hung.

*All drives are safely unmounted as part of the normal log out process (unless you have an odd setup where you installed software that mounts the drive before the user logs in).

Once you have done that, you can either power off the Mac (to ensure all possibility that the drive is safely shut down and open files are not corrupted) or disconnect the drive.
Pulling a drive that's journaled and HFS+ (or the new APFS) is safe in that you won't corrupt the filesystem. What is at risk is each data file that's still open - so you would lose your word file, your iTunes library that lists playlists / ratings, etc.. (but not the songs themselves).
As to the socket filter - you might need to dig a bit in activity monitor or terminal to know why that was identified as using the device. It's probably relating to the apps you run off that device - Google Chrome will run updaters, perhaps Mathematica runs some licensing software that connects to the network (a school license server or back to the vendor). If you can make this error happen on a newly rebooted Mac several times - then it should be easy to look over each running app and trace why the filesystem is blocked and active.


text:
Q: C# WPF Want to store data in a class and use it in multiple different classes in different wpf windows I have 3 classes. 1st stores info, 2nd assigns info to 1nd class, 3rd reads the info from the 1st class.
1st Class, not assigned to any WPF window
public class ProfileInfo //Used to store Name and Surname Data
    {
        public string User_Name { get; set; }
        public string User_Surname { get; set; }
    }

2nd Class, located in WPF window 1
public class InsertInfo //Reads data and stores it in Class 1
    {
        ProfileInfo p = new ProfileInfo();
        p.User_Name = "Bob"; //Example value but normally is read from db
        p.User_Surname = "Jhones"; //Example value but normally is read from db
    }

3rd Class, located in WPF window 2
public class ReadInfo //Reads data from Class 1 and displays it using MessageBox.Show
    {
        ProfileInfo p = new ProfileInfo();
        MessageBox.Show(p.User_Name); // I want this to display Bob but it displays an empty value
        MessageBox.Show(p.User_Surname);
    }

I want Class 1 to store the information until i end the program so that i can retrieve the data in multiple classes.
As i understand this doesn't work because in the 3rd Class im calling for a completely different instance of Class 1 that has no data stored in it??? If so how do i make this work?
I have looked all over the internet for a way to share data between classes but everything seems so difficult and not understandable. Im a beginner so please try to explain it in not so technical language if possible.

A: The problem is that you create an instance of ProfileInfo inside  your InsertInfo class but in the 3rd class, ReadInfo, you create another ProfileInfo instance which is by default, empty. I do not know the details of your system but what you could try is make the ProfileInfo field inside your InsertInfo class a static Property and then you could access it from your other classes:
public class InsertInfo
{
    private static ProfileInfo p = new ProfileInfo();
    public static ProfileInfo P { get { return p; } }

    public void AssignProfileInfo(string username, string surname)
    {
        p.User_Name = username;
        p.User_Surname = surname;
    }
}

And then, to access the stored ProfileInfo you could access the static property:
public class ReadInfo
{
    ProfileInfo p = InsertInfo.P;

    public void ShowInfo()
    {
        MessageBox.Show(p.User_Name);
        MessageBox.Show(p.User_Surname);
    }
}


text:
Q: Lucene/Solr Test inconsistent endOffset I'm using BaseTokenStreamTestCase to perform some tests... against a custom TokenFilter.
The test is failing in an inexplicable way.
You can see from my debug output, that the token it's complaining about, has an endOffset of 17...
inconsistent endOffset 1 pos=1 posLen=1 token=hello expected:<11> but was:<17>
   original: wheel chair hello there foo bar
  increment:      1        1     1      1
     tokens: wheel chair hello there foo bar
  positions: ----------- ----- ----- -------
    lengths:      2        1     1      2
   sequence:      1        2     3      4
             0123456789012345678901234567890
                      10        20        30
  start-end: 1:[0-11], 2:[12-17], 3:[18-23], 4:[24-31]

Heres the test code:
assertAnalyzesTo(analyzer, input,
        new String[] {"wheel chair", "hello", "there", "foo bar"},
        new int[] {0, 12, 18, 24},  // start offsets
        new int[] {11, 17, 23, 31}, // end offsets
        null,                       // types
        new int[] {1, 1, 1, 1},     // positionIncrement
        new int[] {2, 1, 1, 2});    // positionLength

Why does it think the 2nd token should end at 11 ?

A: BaseTokenStreamTestCase is generating the error from this source:
... near line 248
  final int endPos = pos + posLength;

  if (!posToEndOffset.containsKey(endPos)) {
    // First time we've seen a token arriving to this position:
    posToEndOffset.put(endPos, endOffset);
    //System.out.println("  + e " + endPos + " -> " + endOffset);
  } else {
    // We've seen a token arriving to this position
    // before; verify the endOffset is the same:
    //System.out.println("  + ve " + endPos + " -> " + endOffset);
    assertEquals("inconsistent endOffset " + i + " pos=" + pos + " posLen=" + posLength + " token=" + termAtt, posToEndOffset.get(endPos).intValue(), endOffset);
  }

Because endPos is calculated to be pos + posLength the test assumes that
posToEndOffset.get(endPos) will return the end position offset of the current token position + length.
This means that its reading-ahead 1 token, because the first token has a length = 2.
This is why the test is failing.  Length is being used improperly.
Leaving the length attribute set to its default of 1 corrected the test errors.


text:
Q: 11.1 LiPo battery lead got too hot and shows 0 voltage now I was working on my project using the LiPo battery. I mistakenly connected the battery terminals + to - and - to +, due to which the leads become too hot that it give me a heat shock. The charge in battery returned to zero. I placed it on charge with its charger, but the lights on the charger were not all red to show that it is discharged, one of the three lights was green. I took it out and check it after some time but it wasnt charged. I placed it again , this time 2 lights were green 1 off. I am confused whats wrong. Is the battery out of work? What if I charge it from another battery that is fully charged, connecting it + to + and - to - ?

A: Please throw away the battery. Do not attempt to charge it with the charger, and please, please, please do not attempt to charge it with another battery. The best case scenario is two dead batteries intstead of one.
If you short circuited plus and minus and they got so hot you got burned you "possibly" exceeded the maximum discharge current (by a factor of 10, possibly), destroying the battery. If you care about it so much you should disconnect the three cells and test them separately and carefully, but they're probably dead.
Search the web on how to dispose of LiPo batteries, there's a somewhat funny procedure you should follow.


text:
Q: Unicode regex in JavaScript I have the following regex:
/^([\p{L}])*[\p{L},.'-]+$/u

it is a unicode version, which I use for international firstnames.
When I try this:
const value = "Hello"
const criteria = value.match(/^([\p{L}])*[\p{L},.'-]+$/u);
console.log(criteria);

It always returns null, no matter which value the variable has.
I tried it in Regex Debugger / Tester on a Browser and it worked there.


text:
Q: C++: having problems with instantiation of func template I am working on a project which includes class and function templates, which I wrote.
when compiling i'm having this error:
SNN.h In function `void KNN(const std::vector<T, std::allocator<_CharT> >&, std::vector<Cluster<T, K>, std::allocator<Cluster<T, K> > >&) [with T = int, unsigned int K = 5u]':

followed by this errors (i think they're connected):
1)instantiated from `void ClusteringExample() [with T = int]'
2)instantiated from here:ClusteringExample<int>();
3)SNN.h [Warning] comparing floating point with == or != is unsafe
**4) conversion from `<unknown type>' to non-scalar type `__gnu_cxx::__normal_iterator<const Product*, std::vector<Product, std::allocator<Product> > >' requested**

When ClusteringExampke is the func template. here's it's implementation:
template <typename T>
void ClusteringExample()
    {
        std::vector<T> T_input;
        std::vector<Cluster<T,cluster_size> > clusters_T;
        FillVector( T_input, count_per_line );
        SNN( T_input, clusters_T);
        for (typename std::vector<Cluster<T,cluster_size> >::size_type i=0;
    i<clusters_T.size(); i++ )
        {
            clusters_T[i].Print();
            std::cout << std::endl;
        }
        std::cout  << "===="<< std::endl;
    }

code of KNN:
**
void  KNN( const std::vector<T>& all_items, std::vector<Cluster<T,K> >& result )
{
     result.clear();
     if ( K > all_items.size() ) return; //we cannot create clusters bigger than the number of all items
     //for each item in all_items we will create a cluster
     for (typename std::vector<T>::size_type i=0; i < all_items.size(); i++ )
     {
         //this vector will save distances to the item i
         std::vector<double> distances;
         //passing over all items and calculating distance to the item i
         for (typename std::vector<T>::size_type j=0; j < all_items.size(); j++ )
         {
             distances.push_back( Distance(all_items[i], all_items[j] ));
         }
          //creating new cluster
         Cluster<T,K> new_cluster;
         //we are looking for K nearest distances
         std::sort( distances.begin(), distances.end() );
         for ( std::vector<double>::size_type d=0; d<K; d++ )
         {
              for (typename std::vector<T>::size_type j=0; j < all_items.size(); j++ )
               {
                  if (Distance(all_items[i], all_items[j] ) == distances[d] ) //every item which is closer then the "farest" is added to the cluster
                  {
                     new_cluster.Add( all_items[j] ); //we don't use the return value of Add in this implementation, but you need to support it
                  }
               }
         }
         result.push_back( new_cluster );

**
Have to say: it is happening for all types i'm trying to instantiate for (int,double and a class type).
This error is not much informative to me.
Anyone has a clue for where the problem can be?

A: If you really have this code:
template<typename T, size_t K> void Cluster<T,K>::Print() const {
  for(typename vector<T>::const_iterator iter=_cluster_vec.begin;iter!=_cluster_vec.end();++iter) {
    cout<<(*iter)<<" ";
  }
}

Then (a) you need to change begin to begin() and (b) you would have got an answer sooner if you'd posted the code with the error in your original question.

A: The expression Distance(all_items[i], all_items[j] ) == distances[d] might have surprising effects some times... You should never compare floating point numbers (float or double) for equality or inequality.
I recommend that you read the IEEE 754 standard and google for double equality comparison to get more information.
Additionally, the comparison and the comment do not seem to go hand by hand, you are comparing equality but the comment claims:
//every item which is closer then the "farest" is added to the cluster

Maybe you meant <=?


text:
Q: Bootstrap jquery methods Magento's prototype lib Wonder if anyone has had this issue.
I've integrated Bootstrap nicely into a Magento theme I'm building, all good.
That is, until I try using the accordian functions. There seems to be an issue with the code finding the Prototype Libs Methods instead of jQuery's. I've tried the usual fixes, $ - jQuery and no conflict but it only works when I disable the prototype lib - which obviously is not good.
Anyone out there come across this and can advise me on a work round? At the moment I'm resigned to using Scriptaculous for the accordian.

A: I suspect this is occurring due to the transitional conflict in prototype which is used in Magento front-end and admin areas.
Please see: Twitter Bootstrap Transition Conflict prototypejs
You can try this library: https://github.com/jwestbrook/bootstrap-prototype and see if it resolves your issue you are having with your accordian.

A: Using jQuery in Magento can be sometimes tricky. I normally make something like:
jquery-ui-1.8.9.noconflict.min.js
and put jQuery.noConflict() right at the end of the file.
Also make sure that jQuery is loaded after Prototype & there is only 1 version of jQuery included on any page.
I normally like to use jQuery instead of $ all the time but I guess anonymous functions should work too:
(function($) {  /* use $ here */  })(jQuery);

A: Instead of bootstrap.js or bootstrap.min.js use below  js files to get the solution.

*

*jquery.js

*prettify.js

*bootstrap-transition.js

*bootstrap-alert.js

*bootstrap-modal.js

*bootstrap-dropdown.js

*bootstrap-scrollspy.js

*bootstrap-tab.js

*bootstrap-tooltip.js

*bootstrap-popover.js

*bootstrap-button.js

*bootstrap-collapse.js

*bootstrap-carousel.js

*bootstrap-typeahead.js

*application.js more if required.


text:
Q: XML Validation error : EntityRef: expecting';' <url>
  <loc>http://www.ezed.in/ezed/courseDemoIntroPage.do?courseId=COU10000000138003530&checkingCourseFrom=preLogin#.U2DcKvmSySo</loc>
</url>

error on line 102 at column 103: EntityRef: expecting';'
Not able to figure out what could be the problem.

A: Another way as below:
Instead of "CDATA" we could use htmlspecialchars PHP native function for url node. it will work few of xml feed they don't want CDATA in xml output so this will be helpful for someone.
Thanks

A: I stumbled on the same problem today, if you are building the links with PHP you can use this function:
htmlspecialchars();

It will format the desired string for you to HTML chars so you can insert it as a <loc>.

A: Your URL must be escaped.
& character is used in XML to insert a character reference with syntax &name; (note ; after name). Parser expects a ; but it can't find it (there are more available delimiters, this is just most common case).
Solution is then escaping (how it's done depends on language you use to generate that XML file) but final result must be something like this:
<url>
  <loc>http://www.ezed.in/ezed/courseDemoIntroPage.do?courseId=COU10000000138003530&checkingCourseFrom=preLogin#.U2DcKvmSySo</loc>
</url>

Note that plain & has been replaced with its escaped version &. For further details see this simple article.
Another possible solution (if you don't want/you can't escape) is to enclose URL inside a CDATA section like this:
<url>
  <loc><![CDATA[http://www.ezed.in/ezed/courseDemoIntroPage.do?courseId=COU10000000138003530&checkingCourseFrom=preLogin#.U2DcKvmSySo]]></loc>
</url>


text:
Q: Watch output of MySQL query over time I'd like to run a query every few seconds and show the output in a console window.  From bash, using watch:
watch "mysql -A -pXXXXX -h host -D dbname -u username --vertical -e \"SELECT rowID FROM IDs LIMIT 1\""

With the output:
*************************** 1. row ***************************
rowID: 68434810

I'd like to not disconnect and reconnect every 2 seconds though.  Is there a better way?

A: There's a cheap/low-tech way of doing this:
while [ 1 ] ; do echo "select rowid from ids limit 1;" ; sleep 2; done \
 | mysql -u ...

Ctrl C to interrupt.


text:
Q: Looking for IP Addresses of devices connected So the problem which I got was that I was shown a HiL setup with a lot of KVM switches and other computers connected. I was asked to check if say device A was working or not. By working I mean if it was communicating or not.
My solution was to use ifconfig which will produce a list of devices connected to the laptop. What I tried to do was that I try to disconnect all the sockets in the hub and see if the packets would drop but nothing happened. I want to know how to single out devices just by using the command line. I mean I see four Lidar sensors connected but I don't know which one is which, how can I know which sensor is which and with what ID.
This was an interview question and I am curious to how should have I done it. Right now I am looking into broadcast and trace commands but I am not sure if I am on the right path.


text:
Q: Form values from custom HTML element input field not displaying when using on-screen keyboard I am trying to get values that I type using an on-screen keyboard into a custom HTML element input field to display.
However I am currently getting empty strings. If I use a normal input field then it works fine.
Here is a snippet of my code and a stackblitz example which will have detailed code.
HTML
<form-input
    appOskInput
    [formStatus]="formStatus"
    [parentFormGroup]="setupForm"
    [data]="{
             formControlName: 'email',
             name: 'email'
            }">
</form-input>

<app-keyboard></app-keyboard>

Keyboard directive
 private onKey(key: string) {
    let element = this.el.nativeElement;
    let inputEl = element.querySelector('input');
    let start = inputEl.selectionStart;
    let end = inputEl.selectionEnd;
    this.measure.textContent = inputEl.value.substr(0, start) + key;
    inputEl.value = inputEl.value.substr(0, start) + key + inputEl.value.substr(end);
    if (this.control)
    this.control.control.setValue(inputEl.value)
    inputEl.focus();
    inputEl.selectionStart = inputEl.selectionEnd = start + 1;
    this.updateScrollPosition();
 }

Here is the stackblitz https://stackblitz.com/edit/onscreen-keyboard-hlmkvv?file=src/app/app.component.ts
You will see that the values are displaying when inputted from a normal input field but I can't get the same to happen when using my custom HTML element input field. I have commented out the custom HTML input field in the code on the HTML page. Can anyone help please?

A: Issue:
You are adding the directive to a custom element & listening the events on the custom element instead of actual input field. Since, you have @HostListener for focus & blur events inside the directive, these events don't fire in case of custom component. Because your custom component doesn't fire focus and blur events. (If we want any custom element to be focusable, we add tabindex=0 to make it focusable in the natural tabbing order of the webpage).
Why it work on native input elements?
Because native input elements emit focus & blur events. Therefore, you are able to see the virtual keyboard when you apply the directive to native input.
Solution:
You need to add event listeners to the native input field inside your custom component. Since, the directive is generic, you can use querySelector() on the nativeElement inside OskInputDirective to access the particular input field.
In OskInputDirective, add focus & blur listeners in ngAfterViewInit:
 ngAfterViewInit(){
    this.inputEl=this.el.nativeElement.querySelector('input');
    this.inputEl?.addEventListener('focus',this.onFocus.bind(this));
    this.inputEl?.addEventListener('blur',this.onBlur.bind(this));
  }

Now, you can use this.inputEl to refer to the input element inside your onKey() method.
Note 1: Here, we are binding the callbacks with the context of OskInputDirective. Else, this will refer to the DOM event.
Note 2: Since we are manually subscribing to the DOM event, Angular won't be able to detect changes & update your FormControl value. You need to emit an event when you change the input value from virtual keyboard.
In onKey(), call event emitter at the end. Now, listen to this event in the parent & update the corresponding form control value:
this.inputChanged.emit(element.value);
    this.updateScrollPosition();

Here is the forked stackblitz with a custom input element created for reference. https://stackblitz.com/edit/onscreen-keyboard-na5kqr?file=src/app/app.component.ts