text:
Q: Help with FOR XML EXPLICIT query I have an audit table constructed (basically) as follows:
CREATE TABLE [dbo].[AUDIT](
[UNIQUE_ID] [int] IDENTITY(1,1) NOT NULL,
[TABLE_NAME] [nvarchar](50) NOT NULL,
[TABLE_UNIQUE_ID] [int] NOT NULL,
[TABLE_USER_ID] [int] NOT NULL,
[XML] [nvarchar](max) NULL,
[DESCRIPTION] [nvarchar](max) NULL,
[TIMESTAMP] [datetime] NOT NULL,
[EXPLANATION] [nvarchar](max) NULL,
[DATE_INDEX] [datetime] NOT NULL CONSTRAINT [DF_SYS_ADUIT_DATE_INDEX] DEFAULT ('01/01/1900')
PRIMARY KEY CLUSTERED
(
    [UNIQUE_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

This table represents records and associated actions from other tables, where the TABLE_UNIQUE_ID and TABLE_USER_ID are a composite key from the table they originated, XML is the XML representation of the data, and the DATE_INDEX a date the user defines for record (which doesn't necessarily equal the timestamp). This table is large, ranging from 1-10 million records. The main table that records are inserted from is generally in the thousands to hundreds of thousands range.
In short, each set of TABLE_UNIQUE_ID and TABLE_USER_ID combined (and TABLE_NAME, but I'm not worried about that right now) represents one record in the main table and everything that ever occurred to this record (they are uniquely identified by the UNIQUE_ID)
For example, here's a set of records from this table that represents ONE record and its history in our 'main' table:

So here's what I'm trying to do:
I am trying to write a query that returns an XML formatted document that represents an 'Audit' of any particular date range. That means that the user will enter a date range and a report will be produced that includes all records from the MAIN table in that range and their history (description/explanation fields only) from the AUDIT table, as well as the current state of the record and the very original state of the record. Note that the 'current' record will always be found as the highest UNIQUE_ID in the audit table for a given combination of TABLE_UNIQUE_ID and TABLE_USER_ID. So basically, from the given picture, I should have XML similar to the following:
RECORD>
  <AUDITID>914588</AUDITID>
  <UID>316</UID>
  <UNIQUEID>541</UNIQUEID>
  <CURRENTDATA>
    <Record>
      <Data>Current record data and other xml goes here, not important right now</Data>
    </Record>
  </CURRENTDATA>
  <CURRENTAUDITID>914588</CURRENTAUDITID>
  <HISTORY>
    <TIMESTAMP>8/8/11 9:45</TIMESTAMP>
    <DESCRIPTION>Record was created.</DESCRIPTION>
    <EXPLANATION></EXPLANATION>
  </HISTORY>
  <HISTORY>
    <TIMESTAMP>8/8/11 10:01</TIMESTAMP>
    <DESCRIPTION>Record locked</DESCRIPTION>
    <EXPLANATION></EXPLANATION>
  </HISTORY>
  <HISTORY>
    <TIMESTAMP></TIMESTAMP>
    <DESCRIPTION>Record unlocked</DESCRIPTION>
    <EXPLANATION></EXPLANATION>
  </HISTORY>
  <HISTORY>
    <TIMESTAMP>8/15/11 13:11</TIMESTAMP>
    <DESCRIPTION>Record changes : </DESCRIPTION>
    <EXPLANATION></EXPLANATION>
  </HISTORY>
  <HISTORY>
    <TIMESTAMP>8/15/11 14:13</TIMESTAMP>
    <DESCRIPTION>Record was exported.</DESCRIPTION>
  </HISTORY>
  <ORIGINAL>
    <DATA>
      <Record>
          <Data>Orignal record data and other xml goes here, not important right now</Data>
      </Record>
    </DATA>
  </ORIGINAL>
</RECORD>

I was able to write a query that gets MOST record sets correct, which is something like this:
declare @from nvarchar(20) = '8/8/2011', @through nvarchar(20) = '8/8/2011', @currentRecord int

--rownum = 1 represents the latest record in a set
;with CTERow as (
        SELECT UNIQUE_ID,
        TABLE_USER_ID,
        TABLE_UNIQUE_ID,
        TIMESTAMP,
        DATE_INDEX,
        XML,
        DESCRIPTION,
        ROW_NUMBER() OVER(PARTITION BY TABLE_USER_ID, TABLE_UNIQUE_id ORDER BY UNIQUE_ID DESC) AS RowNum
    FROM [AUDIT]
    where (DATE_INDEX >= @from AND DATE_INDEX <= @through))

--This query selects current records that have a date (AUDIT.DATE_INDEX) that falls between the from/through dates
select 1 AS [TAG], NULL AS PARENT,
    --LEVEL 1
    A.UNIQUE_ID AS [RECORD!1!AUDITID!ELEMENT],
    A.TABLE_USER_ID AS [RECORD!1!UID!ELEMENT],
    A.TABLE_UNIQUE_ID AS [RECORD!1!UNIQUEID!ELEMENT],
    (SELECT XML from CTERow where CTErow.Unique_ID = A.UNIQUE_ID AND ROWNUM = 1) AS [RECORD!1!CURRENTDATA!XML],
    A.UNIQUE_ID AS [RECORD!1!CURRENTAUDITID!XML],
    --LEVEL 2
    NULL as [ORIGINAL!2!DATA!XML],
    NULL as [ORIGINAL!2!ORIGUID!HIDE],

    --LEVEL 3
    NULL AS [HISTORY!3!TIMESTAMP!ELEMENT],
    NULL AS [HISTORY!3!DESCRIPTION!ELEMENT],
    NULL AS [HISTORY!3!EXPLANATION!ELEMENT]

from AUDIT A
WHERE
    (SELECT XML from CTERow where CTErow.Unique_ID = A.UNIQUE_ID) IS NOT NULL -- make sure that we're pulling the latest record of a set
    AND (A.DATE_INDEX >= @from AND A.DATE_INDEX <= @through)

UNION ALL

-- This query pulls the original record
SELECT 2 AS [TAG], 1 AS [PARENT],
    --LEVEL 1
    C.UNIQUE_ID,
    C.TABLE_USER_ID,
    C.TABLE_UNIQUE_ID,
    NULL,
    NULL,
    --LEVEL 2
    C.[XML],
    null,
    --LEVEL 3
    NULL,
    NULL,
    NULL
from AUDIT C
where (C.DATE_INDEX >= @from AND C.DATE_INDEX <= @through) --or
and C.DESCRIPTION like '%record was created%'

UNION ALL

--This query pulls the history of the record
select 3 AS [TAG], 1 AS [PARENT],
    --LEVEL 1
    UNIQUE_ID,
    TABLE_USER_ID,
    TABLE_UNIQUE_ID,
    NULL,
    NULL,
    --LEVEL 3
    NULL,
    NULL,
    --LEVEL 2
    B.[TIMESTAMP],
    B.[DESCRIPTION],
    B.[EXPLANATION]
from AUDIT B
where (B.DATE_INDEX >= @from AND B.DATE_INDEX <= @through)

ORDER BY [RECORD!1!UID!ELEMENT], [RECORD!1!UNIQUEID!ELEMENT], [ORIGINAL!2!DATA!XML], [HISTORY!3!TIMESTAMP!ELEMENT]
FOR XML EXPLICIT

However, I am running into problems where I don't capture all the history OR original records (because the DATE_INDEX on the historical records don't necessarily fall in the date range defined by the user).
My question is - what might be the best way to produce output, for a given date range (which will be queried in the date_index column), that selects the following:

*

*the xml of the current record in the main table (this is represented by the the last/highest unique_id of a record set that has XML attached) with a date_index in the date range

*the xml of the above original record (will always have a description with 'record was created' in it)

*the description/explanations of all historical records
Thanks in advance for the help! This has been wracking my brain. Note that I am re-writing the original query, which had HORRENDOUS performance due to lots of joins on the main table (which is also large). Oh yeah, there should be another couple of columns in the index, but I'm more concerned with getting the correct result set first and THEN I'll consider the performance next.

A: You could carve off the data you are interested in into a temp table and work with it there.  I've used FOR XML PATH in this example as it's easier to work with:
USE tempdb
GO

IF OBJECT_ID('[dbo].[AUDIT]') IS NOT NULL DROP TABLE [dbo].[AUDIT]
GO

CREATE TABLE [dbo].[AUDIT](

    [UNIQUE_ID] [int], --IDENTITY(1,1) NOT NULL,
    [TABLE_NAME] [nvarchar](50) NOT NULL,
    [TABLE_UNIQUE_ID] [int] NOT NULL,
    [TABLE_USER_ID] [int] NOT NULL,
    [XML] [nvarchar](MAX) NULL,
    [DESCRIPTION] [nvarchar](MAX) NULL,
    [TIMESTAMP] [datetime] NOT NULL,
    [EXPLANATION] [nvarchar](MAX) NULL,
    [DATE_INDEX] [datetime] NOT NULL CONSTRAINT [DF_SYS_ADUIT_DATE_INDEX] DEFAULT ('01/01/1900')

PRIMARY KEY CLUSTERED
(
    [UNIQUE_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

INSERT INTO [dbo].[AUDIT] ( UNIQUE_ID, TABLE_NAME, TABLE_UNIQUE_ID, TABLE_USER_ID, XML, DESCRIPTION, TIMESTAMP, EXPLANATION, DATE_INDEX )
VALUES
    ( 848098, 'MAIN', 500187, 317, '<Record><Data>Original record data and other xml goes here, not important right now</Data></Record>', 'Record was created', '8 Aug 2011 9:45', NULL, '1 Jan 1900' ),
    ( 849901, 'MAIN', 500187, 317, '<Record/>', 'Record locked', '8 Aug 2011 10:01', NULL, '1 Jan 1900' ),
    ( 854269, 'MAIN', 500187, 317, '<Record/>', 'Record unlocked', '8 Aug 2011 10:51', NULL, '3 Aug 2011' ),
    ( 911382, 'MAIN', 500187, 317, '<Record><Data>Change record data and other xml goes here, not important right now</Data></Record>', 'Record changes:', '8 Aug 2011 10:52', NULL, '8 Aug 2011' ),
    ( 927795, 'MAIN', 500187, 317, '<Record/>', 'Record locked', '15 Aug 2011 13:11', NULL, '1 Jan 1900' ),
    ( 931013, 'MAIN', 500187, 317, '<Record><Data>Current record data and other xml goes here, not important right now</Data></Record>', 'Record was exported', '15 Aug 2011 14:13', NULL, '1 Jan 1900' )
GO

IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp

DECLARE @from DATETIME = '8 Aug 2011 00:00', @through DATETIME = '8 Aug 2011 23:59:59:999', @currentRecord int

-- Get all records for that id and date range into a temp table
SELECT
    UNIQUE_ID,
    TABLE_USER_ID,
    TABLE_UNIQUE_ID,
    [TIMESTAMP],
    DATE_INDEX,
    [XML],
    [DESCRIPTION]
INTO #tmp
FROM dbo.[AUDIT]
WHERE DATE_INDEX >= @from
AND DATE_INDEX <= @through
--AND presumably some other criteria to limit the records ...
AND TABLE_UNIQUE_ID = 500187
AND TABLE_USER_ID = 317

-- Add unique index and RowNum column
ALTER TABLE #tmp ADD PRIMARY KEY ( UNIQUE_ID )
ALTER TABLE #tmp ADD RowNum INT

-- Get any associated records (date criteria not used), which don't already exist
INSERT INTO #tmp ( UNIQUE_ID, TABLE_USER_ID, TABLE_UNIQUE_ID, TIMESTAMP, DATE_INDEX, XML, DESCRIPTION )
SELECT
    UNIQUE_ID,
    TABLE_USER_ID,
    TABLE_UNIQUE_ID,
    [TIMESTAMP],
    DATE_INDEX,
    [XML],
    [DESCRIPTION]
FROM dbo.[AUDIT] a
WHERE EXISTS ( SELECT * FROM #tmp t WHERE a.TABLE_UNIQUE_ID = t.TABLE_UNIQUE_ID AND a.TABLE_USER_ID = t.TABLE_USER_ID )
  AND NOT EXISTS ( SELECT * FROM #tmp u WHERE a.UNIQUE_ID = u.UNIQUE_ID )

-- Add the row number
;WITH cte AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY TABLE_USER_ID, TABLE_UNIQUE_ID ORDER BY UNIQUE_ID ) x, *
FROM #tmp
)
UPDATE cte
SET RowNum = x

-- Have a look at the data before we create the xml
SELECT 't' s, * FROM #tmp
GO

SELECT
    (
    SELECT
        UNIQUE_ID AS AUDITID,
        TABLE_USER_ID AS [UID],
        TABLE_UNIQUE_ID AS UNIQUEID,
        CAST( [XML] AS XML ) AS "CURRENTDATA/*"
    FROM #tmp
    WHERE RowNum = ( SELECT MAX(RowNum) FROM #tmp )
    FOR XML PATH(''), TYPE
    ),
    (
    SELECT
        [TIMESTAMP] AS [TIMESTAMP],
        [DESCRIPTION] AS [DESCRIPTION],
        '' AS EXPLANATION
    FROM #tmp
    WHERE RowNum > 1
      --AND RowNum = ( SELECT MAX(RowNum) FROM #tmp )   -- ??
    FOR XML PATH('HISTORY'), TYPE
    ),
    (
    SELECT
        CAST( [XML] AS XML ) AS "DATA/*"
    FROM #tmp
    WHERE RowNum = 1
    FOR XML PATH('ORIGINAL'), TYPE
    )

FOR XML PATH('RECORD'), TYPE
GO

A: After much soul searching and something of an "aha!" moment in the shower (although it was more like an "mmhmmm" moment), I realized what I was doing. I knew my filters were wrong, but I changed how I was thinking about building the query from "how does the whole thing work" to "how do I build this particular query from small query to big query". Anyways, here's what I came up with, which I think is correct (at least, it seems to be - needs more testing to prove its correctness):
declare @from nvarchar(20) = '8/8/2015', @through nvarchar(20) = '8/8/2016', @currentRecord int
--This CTE is simply a subquery to allow us to find all sets of a particular user record
--rownum = 1 represents the latest record in a set
--This query represents all of our "candidate" records to be selected from in this query.
;with CTERow as (
        SELECT UNIQUE_ID,
        TABLE_USER_ID,
        TABLE_UNIQUE_ID,
        TIMESTAMP,
        DATE_INDEX,
        XML,
        DESCRIPTION,
        ROW_NUMBER() OVER(PARTITION BY TABLE_USER_ID, TABLE_UNIQUE_id ORDER BY UNIQUE_ID DESC) AS RowNum
    FROM [AUDIT]
    where (DATE_INDEX >= @from AND DATE_INDEX <= @through))

--This query selects current records that have a worked date (AUDIT.DATE_INDEX) that falls between the from/through dates
select 1 AS [TAG], NULL AS PARENT,
    --LEVEL 1
    A.UNIQUE_ID AS [RECORD!1!AUDITID!ELEMENT],
    A.TABLE_USER_ID AS [RECORD!1!UID!ELEMENT],
    A.TABLE_UNIQUE_ID AS [RECORD!1!UNIQUEID!ELEMENT],
    (SELECT XML from CTERow where CTErow.Unique_ID = A.UNIQUE_ID AND ROWNUM = 1) AS [RECORD!1!CURRENTDATA!XML],
    A.UNIQUE_ID AS [RECORD!1!CURRENTAUDITID!XML],
    --LEVEL 2
    NULL as [ORIGINAL!2!DATA!XML],
    NULL as [ORIGINAL!2!ORIGUID!HIDE],

    --LEVEL 3
    NULL AS [HISTORY!3!TIMESTAMP!ELEMENT],
    NULL AS [HISTORY!3!DESCRIPTION!ELEMENT],
    NULL AS [HISTORY!3!EXPLANATION!ELEMENT]

from AUDIT A
WHERE UNIQUE_ID in
    (select max(unique_id) FROM CTERow C
    WHERE A.TABLE_UNIQUE_ID = C.TABLE_UNIQUE_ID and A.TABLE_USER_ID = C.TABLE_USER_ID)

UNION ALL

-- This query pulls the original record
SELECT 2 AS [TAG], 1 AS [PARENT],
    --LEVEL 1
    B.UNIQUE_ID,
    B.TABLE_USER_ID,
    B.TABLE_UNIQUE_ID,
    NULL,
    NULL,
    --LEVEL 2
    B.[XML],
    null,
    --LEVEL 3
    NULL,
    NULL,
    NULL
from AUDIT B
where UNIQUE_ID in
    (select min(unique_id) FROM CTERow C
    WHERE B.TABLE_UNIQUE_ID = C.TABLE_UNIQUE_ID and B.TABLE_USER_ID = C.TABLE_USER_ID)

UNION ALL

--This query pulls the history of the record
select 3 AS [TAG], 1 AS [PARENT],
    --LEVEL 1
    UNIQUE_ID,
    TABLE_USER_ID,
    TABLE_UNIQUE_ID,
    NULL,
    NULL,
    --LEVEL 2
    NULL,
    NULL,
    --LEVEL 3
    B.[TIMESTAMP],
    B.[DESCRIPTION],
    B.[EXPLANATION]
from AUDIT B
where
    convert(nvarchar(20), B.TABLE_UNIQUE_ID) + convert(nvarchar(20), B.TABLE_USER_ID) in
        (select convert(nvarchar(20),TABLE_UNIQUE_ID) + convert(nvarchar(20),TABLE_USER_ID) FROM CTERow c)

ORDER BY [RECORD!1!UID!ELEMENT], [RECORD!1!UNIQUEID!ELEMENT], [ORIGINAL!2!DATA!XML], [HISTORY!3!TIMESTAMP!ELEMENT], [HISTORY!3!DESCRIPTION!ELEMENT], [HISTORY!3!EXPLANATION!ELEMENT]
FOR XML EXPLICIT


text:
Q: UWP , Why Sideload package can not include PDF files? I put my software manual (PDF) at Assets/manual folder.
and I make Sideload application package. and I confirm installed folder.
There is No PDF and folder "manual".
Why ?
Here is my step.

*

*in VisualStduio, I open Assets/manual folder.

*Copy all file to the folder.

*Include the PDF into Assets/manual with VisutalStuido.

*In DEBUG mode, I copy manual folder to "bin\x64\Debug\AppX\Assets\manual" manually.

*In Release mode, I also copy to "bin\x64\Release\AppX\Assets\manual" , manually.

What wrong ???

A: You need to set BuildAction=Content on the PDF to make them part of the package output. Then it will work automatically in VS when you deploy the app or create the package.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Material UI Autocomplete dropdown positioning Is there any easy way to customize Material UI Autocomplete so it Popper dropdown can be positioned relative to the text cursor (Similar to the VS Code Intellisense dropdown)? I have a multiline Textfield component as an input field.
Code looks something like this:
import React from "react";
import { createStyles, makeStyles, Theme } from '@material-ui/core/styles';
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import Chip from '@material-ui/core/Chip';
import { Popper } from "@material-ui/core";

const targetingOptions = [
  { label: "(", type: "operator" },
  { label: ")", type: "operator" },
  { label: "OR", type: "operator" },
  { label: "AND", type: "operator" },
  { label: "Test Option 1", type: "option" },
  { label: "Test Option 2", type: "option" },
];

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      '& .MuiAutocomplete-inputRoot': {
        alignItems: 'start'
      }
    },
  }),
);

export default () => {
  const classes = useStyles();

  const CustomPopper = function (props) {
    return <Popper {...props} style={{ width: 250, position: 'relative' }} />;
  };

  return (
    <div>
        <Autocomplete
        className={classes.root}
        multiple
        id="tags-filled"
        options={targetingOptions.map((option) => option.label)}
        freeSolo
        disableClearable
        PopperComponent={CustomPopper}
        renderTags={(value: string[], getTagProps) =>
          value.map((option: string, index: number) => (
            <Chip variant="outlined" label={option} {...getTagProps({ index })} />
          ))
        }
        renderInput={(params) => (
          <TextField {...params} variant="outlined" multiline={true} rows={20} />
        )}
      />
    </div>
  );
};

A: Autocomplete from material ui has a PopperComponent property which you can use to create a custom popper that has placement property you want.
check this : https://github.com/mui-org/material-ui/issues/19376


text:
Q: Proper way to update ImageView in a RemoteViews? I'm trying to fetch an image from a remote URL and put it into an ImageView.  The ImageView itself is within an app widget, so from my current understanding that means it is encapsulated within a RemoteViews and isn't really handled directly.
But I can never get the app widget to display an image.  I'm fetching the image as a Bitmap from a remote URL using an AsyncTask extension, and it seems like the image is being fetched OK (a non-null bitmap is returned anyway), though as yet I can't display it to confirm.
I reckon I must be using the wrong method to actually update the app widget's ImageView.
Here is all the relevant code:
layout/new_app_widget.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/widget_margin" >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:contentDescription="@string/content" />
</RelativeLayout>

relevant bit from NewAppWidget.java:
public class NewAppWidget extends AppWidgetProvider {

...

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
        int appWidgetId) {

    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

    String strURL = "http://example.com/YqLOSfr4.png";

    new ImageFetchAsyncTask(strURL, R.id.imageView).execute();
    // ^^^^^
    // in the above, I pass the URL and the id of the imageview, fetch
    // the bitmap, and in the onPostExecute() method I use
    // setImageViewBitmap(viewId, bitmap) to load the bitmap into the imageview
    //
    // I don't have the code to hand, but I can provide it.  For now, someone
    // may be able to tell me somewhere else I'm doing something wrong

    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

}

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mike.widgetapptest" >
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        android:debuggable="true"
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".NewAppWidget" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/new_app_widget_info" />
        </receiver>
    </application>

</manifest>

A: Classic beginner's error... I was attempting to do something immediately following an async task, expecting the async task to have completed.  So I moved what depends on the result of the async task into the onPostExecute() method of the async task, and voila... image displayed in my app widget!


text:
Q: How do I write a program that creates new shared queries for a team project in TFS?
Is it possible using the TFS client object model to create new shared
  queries for the team project?
If so can you provide a code sample or a link to the MSDN
  documentation?

We keep a couple queries for each team member and when someone joins then team we have to create new ones for the new member. It doesn't take long, but I'd like to just write a quick program that copies a template query definition, changes the name of the developer, and saves a copy of it. It would be especially useful when we decide to add a column to the query. Currently I have to manually modify 20+ queries definitions. I couldn't find anything on MSDN, but I'm hoping I just missed it somehow.


text:
Q: Running to Selects and grouping results with PHP I am trying to display a row of data from my main table (parents details) and then under each of those rows display the children's names from another table. I have had a go using the following code:
$sql="select distinct members_main.first_name as main_firstname,
    members_main.first_name as main_firstname,
    members_main.last_name as main_lastname,
    members_main.address_1 as main_address_1,
    members_main.address_2 as main_address_2,
    members_main.address_3 as main_address_3,
    members_main.address_4 as main_address_4,
    members_main.post_code as main_post_code,
    members_main.home_tel as main_home_tel,
    members_main.mobile as main_mobile,
    members_main.home_email as main_home_email
    from members_main, members_family where members_main.contact_id=members_family.contact_id";

$sql2="select members_family.first_name as fam_firstname,
    members_family.last_name as fam_lastname
    from members_family, members_main
    where members_main.contact_id=members_family.contact_id";

$result=mysql_query($sql);

while($rows=mysql_fetch_array($result)){

echo '

First Name
Last Name
Address 1
Address 2
Address 3
Address 4
Post Code
Home Tel
Mobile
Email

';

echo '

'.$rows['main_firstname'].'
'.$rows['main_lastname'].'
'.$rows['main_address_1'].'
'.$rows['main_address_2'].'
'.$rows['main_address_3'].'
'.$rows['main_address_4'].'
'.$rows['main_post_code'].'
'.$rows['main_home_tel'].'
'.$rows['main_mobile'].'
'.$rows['main_home_email'].'

';

$result2=mysql_query($sql2);

echo '

First Name
Last Name

';

while($rows=mysql_fetch_array($result2)){

echo '

'.$rows['fam_firstname'].'
'.$rows['fam_lastname'].'

';

}

}

echo "
";

I am getting all rows from the members_family table per each record from the members_main. There can be more than one record in the members_family which will be associated to one record in the members_main. Bascially, members_main (parent) can have multiple children in the members_main.

A: I think you just need to retrieve your members_main.contact_id from first table to use later in second while loop. Then you will have to move your second query inside first query while loop so the code will look like that:
$sql="select distinct
members_main.contact_id as ID,
members_main.first_name as main_firstname,
members_main.first_name as main_firstname,
members_main.last_name as main_lastname,
members_main.address_1 as main_address_1,
members_main.address_2 as main_address_2,
members_main.address_3 as main_address_3,
members_main.address_4 as main_address_4,
members_main.post_code as main_post_code,
members_main.home_tel as main_home_tel,
members_main.mobile as main_mobile,
members_main.home_email as main_home_email
from members_main, members_family where members_main.contact_id=members_family.contact_id";

$result = mysql_query($sql);
while($rows=mysql_fetch_array($result)) {

//script goes on with table printing untill
'.$rows['main_home_email'].'

';

Now it's time for the query
$sql2="select members_family.first_name as fam_firstname,
members_family.last_name as fam_lastname
from members_family, members_main
where members_main.contact_id=members_family.contact_id and members_main.contact_id = '".$rows['ID']."'";

As you see i added in WHERE condition to limit result for specified ID wich i retrieved from first query. Now you can print the rest of the table. Oh and by the way you closing table should look like that
echo "

";

This is because you opened two tables.
Then I would like you to remember that mysql_* functions are deprecated so i would advise you to switch to mysqli or PDO

A: I feel some confusion with your second query. I am thinking that you have to construct your second query with the contact_id which is coming from first query(members_main). I assumes in that way and i have coded below. May be it will help you
        <?php
        $sql = "select distinct members_main.first_name as main_firstname,
            members_main.first_name as main_firstname,
            members_main.last_name as main_lastname,
            members_main.address_1 as main_address_1,
            members_main.address_2 as main_address_2,
            members_main.address_3 as main_address_3,
            members_main.address_4 as main_address_4,
            members_main.post_code as main_post_code,
            members_main.home_tel as main_home_tel,
            members_main.mobile as main_mobile,
            members_main.home_email as main_home_email
            from members_main, members_family where members_main.contact_id=members_family.contact_id";
        $result = mysql_query($sql);
        ?>

                First Name
                Last Name
                Address 1
                Address 2
                Address 3
                Address 4
                Post Code
                Home Tel
                Mobile
                Email

            <?php
            while ($rows = mysql_fetch_array($result))
            {
                $conId = $rows['contact_id']; //Which is comming from first Query
                $sql2 = "select members_family.first_name as fam_firstname,
            members_family.last_name as fam_lastname
            from members_family, members_main
            where members_family.contact_id=$conId";

                $result2 = mysql_query($sql2);
                ?>

                    <?= $rows['main_firstname']; ?>
                    <?= $rows['main_lastname']; ?>
                    <?= $rows['main_address_1']; ?>
                    <?= $rows['main_address_2']; ?>
                    <?= $rows['main_address_3']; ?>
                    <?= $rows['main_address_4']; ?>
                    <?= $rows['main_post_code']; ?>
                    <?= $rows['main_home_tel']; ?>
                    <?= $rows['main_mobile']; ?>
                    <?= $rows['main_home_email']; ?>

                                First Name
                                Last Name

                            <?php
                            while ($rowsFamily = mysql_fetch_array($result2))
                            {
                                ?>

                                    <?= $rowsFamily['fam_firstname']; ?>
                                    <?= $rowsFamily['fam_lastname']; ?>

                                <?php
                            }
                            ?>

                <?php
            }
            ?>


text:
Q: Can I use constants to avoid Class instance variables? To become thread-safe, I need to refactor the Class instance variables in my code.
original
# frozen_string_literal: true

class Score < ApplicationRecord

  def self.init_score
    return @init_score if @init_score.present?

    @init_score = new(multiplier: 4.0)

    @init_score.readonly!
    @init_score
  end
end

Score.init_score
refactored

# frozen_string_literal: true

class Score < ApplicationRecord

  INIT_SCORE = self.init_score.freeze

  def self.init_score
    init_score = new(multiplier: 4.0)
    init_score.readonly!
  end
end

Score::INIT_SCORE
So this approach makes sense, is this a good solution?
I want to know if a const can be used as a cache.


text:
Q: Can't Use Data from Selection in HTML with PHP To Validate RegEx Pattern <?php

$selectedOption = $_POST['patOption'];
$text = "";
$replaceText = "";
$replacedText = "";
$containString = "/\b($text)\b/";
$containEmail = "/\b([A-Za-z0-9._%+-]{2,})+@([A-Za-z0-9._]{2,})+\.[A-Za-z]{2,6}\b/";
$containPhone = "/^(\+(998))+\-([0-9]{2})+\-([0-9]{3})+\-([0-9]{4})/";

$match = "Not checked yet.";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $pattern = $_POST["pattern"];
    $text = $_POST["text"];
    $replaceText = $_POST["replaceText"];

    $replacedText = preg_replace($pattern, $replaceText, $text);

    if (preg_match($pattern, $text)) {
        $match = "Match!";
    } else {
        $match = "Does not match!";
    }
}

?>

html

Validation Tests

Choose Pattern:

    <select name="patOption">
        <option>OPTIONS...</option>
        <option value="<?= $containString ?>">Contain_String</option>
        <option value="<?= $containEmail ?>">Contain_Email</option>
        <option value="<?= $containPhone ?>">Contain_Phone</option>
    </select>

    <form action="regex_valid_form.php" method="post">

Pattern

<input type="text" name="pattern" value="<?= $selectedOption ?>">

Text (Ex.)

<input type="text" name="text" value="<?= $text ?>">

Replace Text

<input type="text" name="replaceText" value="<?= $replaceText ?>">

Output Text

<?= $match ?>

Replaced Text

 <?= $replacedText ?>

<input type="submit" value="Check">

    </form>

I Wanna Use Choosen Value From Options To Validate RegEx Pattern in PHP:

*

*It should get RegEx from Var in PHP and insert into 'Pattern' field when I
choose corresponding option and validate with given 'value' in 'Text' field
and Output whether it Matched or Not

Validation Page:


text:
Q: Understanding recursive function in linked-list C Let's suppose I write a program that simulates the Dominoes game, so I'd like to define a struct the following way:
typedef struct nodo {
    int casella1;
    int casella2;
    struct nodo *next;
} Tessera;
typedef Tessera *Lista;

And then after some input in casual order that ends when a number outside the range 0 <= x <= 6 is entered, I'd like to delete the possible duplicates that don't respect the domino rules. The number casella2 should always be succeeded by the same number in ->next->casella1, using a recursive function, that goes like this:
void legale(Lista *head) {

    Lista aux,aus = *head;

    if(aus->next == NULL) {
      return;
    }

    else if(aus->casella2 == aus->next->casella1)   {
      legale(&(aus->next));
    }
    else {
      aux = aus->next;
      aus->next = aus->next->next;
      free(aux);
    }
}

But for example the sequence " 1 2, 2 3, 3 4, 4 5, 5 4, 6 2, 7" gives  "1 2, 2 3, 3 4, 4 5,6 2 " So it doesn't delete 6,2 as it should.
I think the way I deleted the pointer is correct, so why is the function wrong?
The code goes like this :
#include<stdio.h>
#include<stdlib.h>
typedef struct nodo {
    int casella1;
    int casella2;
    struct nodo *next;
    }Tessera;
typedef Tessera *Lista;

void stampa(Lista *head) {

    Lista ausil = *head;

    while(ausil != NULL) {
    printf("%d\t%d\n",ausil->casella1,ausil->casella2);
    ausil = ausil->next;
    }
}

void legale(Lista *head) {

    Lista aux,aus = *head;

    if(aus->next == NULL) {
    return;
}

    else if(aus->casella2 == aus->next->casella1)   {
    legale(&(aus->next));
}
    else {
    aux = aus->next;
    aus->next = aus->next->next;
    free(aux);
}

}

void write (Lista *head) {
    Lista corr,aux,aus;
    int x,y;
    scanf("%d%d",&x,&y);
    aus = *head;

    while((x >= 0 && x <= 6) && (y >= 0 && y <= 6)) {

    if(aus == NULL) {

    aus = malloc(sizeof(Tessera));
    aus->casella1 = x;
    aus->casella2 = y;
    aus->next = NULL;
    *head = aus;
}
    else {
    aux = *head;

    corr = malloc(sizeof(Tessera));
    corr->casella1 = x;
    corr->casella2 = y;
    corr->next = aux;
    *head = corr;
}
    scanf("%d%d",&x,&y);
    }

}

int main() {
    Lista Lista1 = NULL;
    write(&Lista1);
    legale(&Lista1);
    stampa(&Lista1);
return 0;
}

A: You are at least missing a recursive call after you remove a duplicate,

else {
  aux = aus->next;
  aus->next = aus->next->next;
  free(aux);
}

If you don't recurse you stop after the first removal.
Also by precaution, before checking whether aus->next == NULL you should check whether aus == NULL so it doesn't break if you pass it an empty list.

EDIT
You are constructing your linked list backwards when you read it.
You insert each pair at the head, so in the end you have your sequence backwards. It's always a good idea to print out your list after you read it to make sure it's OK ;)


text:
Q: What's this statistics-looking icon on my TouchBar? I've just discovered this icon on my MacBook Pro's TouchBar:

Looks like some sort of statistics, or so? It only appears occasionally. Tapping on it I get this slider:

This doesn't do anything though. When sliding I get a "0:00" count next to it and nothing happens. What is this supposed to do?
Looks like I'm also unable to take TouchBar screenshots via ⌘+⇧+6 for some reason.

A: Are you watching a video in Safari? That slider is telling you that you're watching a video in the app displayed in the icon, scrubbing on that slider scrub the video you're playing. Or if you're not watching a video, it might just be a bug. Try refreshing the Control Strip by going into activity monitor and find the process "Control Strip" and quit that process(it won't do any harm, your touch bar will blink once).
P.S. As for taking screenshot of the touch bar you need 10.12.2 beta.


text:
Q: how to type for object of object in typescript How to type for following data. I have to type for progress object
const progress = {
   "1": {
      topic: [1,3,4],
      assessment: [1,2,4,],
   },
   "2": {
      topic: [1,3,4],
      assessment: [1,2,4,],
   },
   ....
}

A: There is built-in type - Record<K, V>
type Obj = Record<string, {topic: number[], assessment: number[]}>


text:
Q: HTTPwebresponse not working, I can't get anything to POST So I get a bad request error whenever I run this. I have looked on stack overflow but can't seem to get any of the responses from users to work. Any help would be appreciated.
//Make a request to the SendGrid API to add the email address to the globabl unsubscirbe
        HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("https://api.sendgrid.com/v3/asm/suppressions/global");
        request1.Headers.Add("authorization", "My_API_KEY");
        string Data = "{" + "recipient_emails:[" + "\"" +(txtEmail.Text) + "\"" + "]}"; //place body here
        request1.Method = "POST";
        request1.ContentType = "application/json";

        using (StreamWriter sw = new StreamWriter(request1.GetRequestStream()))
        {

            sw.Write(Data);

        }

        HttpWebResponse response1= (HttpWebResponse)request1.GetResponse();

        using (var streamReader = new StreamReader(response1.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            result.ToString();
        }

A: It is an excerpt.
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");

var client = new SendGridClient(apiKey);

string data = @"{
  'recipient_emails': [
    'test1@example.com',
    'test2@example.com'
  ]
}";
Object json = JsonConvert.DeserializeObject<Object>(data);
data = json.ToString();
var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "asm/suppressions/global", requestBody: data);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();


text:
Q: Makefile make: Nothing to be done for `default' I write a hello.c:
#include <linux/init.h>
#include <linux/moudle.h>

static int hello_init(void)
{
    printk(KERN_ALERT "Hello, World\n");
    return 0;
}

static void hello_exit(void)
{
    printk(KERN_ALERT "GoodBye, cruel Workd!\n");
}

module_init(hello_init);
module_exit(hello_exit);
module_LICENSE("GPL");
module_AUTHOR("ChangZhi");

And this is Makefile:
obj-m := hello.o
KERNEL_DIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
make -C $(KERNEL_DIR) SUBDIRS=$(PWD) modules
#clean:
#rm *.o *.ko *.mod.c

.PHONY:clean

when I run make, the shell displays make: Nothing to be done fordefault'.`. Could someone help me? Thanks a lot !

A: As per ymonad says you require TAB before make -C
default:
    make -C $(KERNEL_DIR) SUBDIRS=$(PWD) modules


text:
Q: How to get the only the 2nd best score in MySqL? not the others i have one server whit minigames, and i have a problem whit my database, i need to get in query of mysql only the 2nd best score name.. can anyone help-me?
this is my database:
DATA_BASE
name  | kills
------+------
Leon  | 22
Andy  | 14
Brian | 8

i need to get just Andy name and kills from Andy!
code:
"SELECT * FROM `DATA_BASE` ORDER BY `kills` DESC"

please help-me! can i use limit to do this? what should i do? Thks

A: This should do the trick :
SELECT * FROM DATA_BASE ORDER BY kills DESC LIMIT 1 OFFSET 1;

LIMIT 1 limits the number of rows selected and OFFSET 1 offsets the rows by 1 resulting in only second row being selected.

A: Try:
SELECT name FROM DATA_BASE ORDER BY kills DESC LIMIT 1,1

This should return only the second best, because we want 1 option (the second number) and we want to offset it by 1 (the first number)

A: You can use LIMIT keyword like as follows:
 SELECT * FROM DATA_BASE ORDER BY kills DESC LIMIT 1, 1

A: Try that.
Should limit to one 1 record and start on record 2.
"SELECT * FROM DATA_BASE ORDER BY kills DESC LIMIT 1 OFFSET 1"

A: SELECT * FROM (SELECT * FROM DATA_BASE ORDER BY kills DESC LIMIT 2) AS DB ORDER BY kills LIMIT 1;

We can do the same without using LIMIT by using MAX native function:
SELECT MAX(kills) FROM DATA_BASE WHERE kills NOT IN ( SELECT Max(kills) FROM DATA_BASE);

which is quite easier compared to earlier one


text:
Q: How do I define a friend class from the global namespace in another namespace? In a previous Q&A (How do I define friends in global namespace within another C++ namespace?), the solution was given for making a friend function definition within a namespace that refers to a function in the global namespace.
I have the same question for classes.
class CBaseSD;

namespace cb {
class CBase
{
    friend class ::CBaseSD; // <-- this does not work!?
private:
    int m_type;
public:
    CBase(int t) : m_type(t) {};
};
}; // namespace cb

class CBaseSD
{
private:
    cb::CBase*  m_base;
public:
    CBaseSD(cb::CBase* base) : m_base(base) {};
    int* getTypePtr()
    { return &(m_base->m_type); };
};

If I put CBaseSD into a namespace, it works; e.g.,
    friend class SD::CBaseSD;
but I have not found an incantation that works for the global namespace.
I am compiling with g++ 4.1.2.

A: As stated in some of the comments below the question, the code in the question appears to work with me (Linux-Ubuntu-16.04, gcc version 5.4.0), provided that the friend class was forward-declared.
In pursuit of an answer, I came across this post that both explains proper technique for making friend class of a global namespace and answers why it needs to be declared the way it does. It is a nice thread because it references the standard.
As stated earlier, the class of a global namespace must be forward declared before it can be used as a friend class to a class within a namespace.

A: add the forward declaration like below

namespace {
  // anonymous namespace declaration
  class CBaseSD;
}

then your normal

friend class CBaseSD;// no need of ::

works in CBase


text:
Q: Magento2- getLastRealOrderId() returns null I am creating a payment gateway. When ever the last order has the state/status as complete, getLastRealOrderId() returns null. Is there any work around or a way to solve it ? I am new to magento

A: Use this code in block or in your helper class.
protected $_checkoutSession;
    protected $_orderFactory;
    protected $_scopeConfig;

    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Framework\View\Element\Context $context
    ) {
        $this->_checkoutSession = $checkoutSession;
        $this->_orderFactory = $orderFactory;
        $this->_scopeConfig = $context->getScopeConfig();
    }

    // Use this method to get ID
    public function getRealOrderId()
    {
        $lastorderId = $this->_checkoutSession->getLastOrderId();
        return $lastorderId;
    }

    public function getOrder()
    {
        if ($this->_checkoutSession->getLastRealOrderId()) {
             $order = $this->_orderFactory->create()->loadByIncrementId($this->_checkoutSession->getLastRealOrderId());
        return $order;
        }
        return false;
    }

    public function getShippingInfo()
    {
        $order = $this->getOrder();
        if($order) {
            $address = $order->getShippingAddress();

            return $address;
        }
        return false;

    }

Using this function, you can get the latest order Id. Hope this will help you too.

A: I think your question lacks a bit more context but I can talk about the default Magento checkout process.
If you check the code in Magento, you'll notice this information is set on Checkout Session by this method.
That said, something on your checkout process is probably clearing the checkout session information before the process reaches the success page.
A simple and easier workaround for this is making your payment method set a different value on the Magento session and then grabbing it rather than the default checkout one (getLastRealOrderId). Or you can debug your process with Xdebug by watching the checkout session throughout the process to understand where it's being cleared or modified.
I'd put breakpoints throughout the code wherever there's a call to setLastRealOrderId() to see how it goes.


text:
Q: waitForImages for background-image This is the part of the image I found with browsers inspector and I want to get recognized by waitforImages:

Already tried it with $('.jtpl-background-area'), $('.jqbga-container') or $('.jtpl-background-area, .jqbga-container, .jqbga-web--image') but with the same result, it does not 'fire'. I think it simply does not find the picture on that url...(or I do something wrong as I am new to this stuff, maybe a syntax error)?
What do I have to do now, to get it recognizing that the image is that url/background-image? Any idea what I do wrong?
$('.jtpl-background-area').waitForImages(true).done(function() {
    $('.jtpl-background-area').css('-webkit-animation', 'fadein 4s');
});

or
$(".jtpl-background-area jqbga-container jqbga-web-image").waitForImages(true).done(function() {
    $('.jtpl-background-area').velocity({ opacity: 1 },{ duration: 4000});
});

Do not work. The page is loading - but without background-image at all.
A
//        $(window).on('load', function() {
//        $(".jtpl-background-area").velocity({ opacity: 1 },{ duration: 3000});
//});

works - but bakgrounds popping up too late.

A: According to the documentation, you need to enable an option for the plugin to scan for images in CSS properties.
Your code should be...
$('.jqbga-web--image').waitForImages(true).done(function() {
    $('.jtpl-main').css('visibility', 'visible');
});


text:
Q: tikzpicture fails with date input coordinates taken from file I have a problem implementing a tikzpicture. I want to plot the file with date and TIME and a climatic variable. I followed the PGF manual in section 4.21.2 "Dates as Input Coordinates" and if i do the table of the coordinates "by hand", everything works as intended:
    \begin{tikzpicture}
            \begin{axis}[
            date coordinates in=x,
            xtick=data,
            xticklabel style=
            {rotate=90,anchor=near xticklabel},
            xticklabel={\day.\month.},
            xlabel={2015},
            date ZERO=2015-01-01,% <- improves precision!
            ]
                    \addplot coordinates {
                    (2015-12-21 00:00, 17.54)
                    (2015-12-21 00:59, 17.23)
                    (2015-12-21 01:58, 16.96)
                    (2015-12-21 02:57, 16.88)
                    (2015-12-21 03:56, 16.70)
                    (2015-12-21 04:55, 16.36)
                    (2015-12-21 05:54, 17.02)
                    (2015-12-21 06:53, 19.24)
                    (2015-12-21 07:52, 20.40)
                    (2015-12-21 08:51, 22.06)
                    };
            \end{axis}
    \end{tikz

But when the parser has to look for the file, as in here:
    \begin{tikzpicture}
            \begin{axis}[
            date coordinates in=x,
            xtick=data,
            xticklabel style=
            {rotate=90,anchor=near xticklabel},
            xticklabel={\day.\month.},
            xlabel={2015},
            date ZERO=2015-01-01,% <- improves precision!
            ]
            \addplot table[x=date,y=temperature] {plotdata/temp_summer.dat};
            \end{axis}
    \end{tikzpicture}

then the following error appears:
! Package PGF Math Error: Could not parse input '00:00,' as a floating point number, sorry. The unreadable part was near ':00,'..
See the PGF Math package documentation for explanation. Type  H <return>  for immediate help.
 ...
l.421 ...=temperature] {plotdata/temp_summer.dat};

I get the error messages about the 00:00 or any other hour. The funny thing that it is working if I introduced the coordinates in the .tex file itself.
Í suspect this is a BUG in PGF file parser but I'm not sure, my .tex system is:
pdfTeX, Version 3.1415926-2.5-1.40.14 (MiKTeX 2.9 64-bit)
Package pgfplots notification 'compat/show suggested version=true': document has been generated with the most recent feature set
(\pgfplotsset{compat=1.13}).
Let me tell you guys that if I removed the HH:MM then, the file compilation is successful but then, is not what I need!.
Any ideas, any help is GREATLY appreciated.
Thank you in advance.....

A: Here is a MWE
\begin{filecontents*}{data.dat}
date, temperature
2015-12-21 00:00, 17.54
2015-12-21 00:59, 17.23
2015-12-21 01:58, 16.96
2015-12-21 02:57, 16.88
2015-12-21 03:56, 16.70
2015-12-21 04:55, 16.36
2015-12-21 05:54, 17.02
2015-12-21 06:53, 19.24
2015-12-21 07:52, 20.40
2015-12-21 08:51, 22.06
\end{filecontents*}
\documentclass[margin=5pt]{standalone}
\usepackage{pgfplots}
\usepgfplotslibrary{dateplot}
\pgfplotsset{compat=newest}

\begin{document}
\begin{tikzpicture}
        \begin{axis}[
        date coordinates in=x,
        xtick=data,
        xticklabel style=
        {rotate=90,anchor=near xticklabel},
        xticklabel={\day.\month. \hour:\minute},
        xlabel={2015},
        date ZERO=2015-01-01,% <- improves precision!
        ]
        \addplot table[x=date,y=temperature,col sep=comma] {data.dat};
        \end{axis}
\end{tikzpicture}
\end{document}

which results in

Note that you have to use col sep=comma as option of table if the column sep in your file is a comma:
\addplot table[x=date,y=temperature,col sep=comma] {data.dat};

Then the comma must also be used as seperator between the column headers: date, temperature. I guess this , is missing in your file.


text:
Q: How to make input fields (text) end where the divs end? How to make input fields (text) end where the divs end? Now they go pass the grey box. See jsfiddle.
http://jsfiddle.net/FNZD6/
input[type="text"].normal100{
display:block;
font-size: 1.6em;
width:100%;
margin:0px;
padding: 0px;
}

A: I'm not quite sure why this happens, but here is a fix.
*{
  box-sizing: border-box;
}

You'll need to prefix that too. I always set the box-sizing on everything but you can set it on specific elements if you wish.
Demo

A: The input field is slightly bigger than the divs in your example because of the left and right borders. Easiest way to fix that is to explicitly set those to 0:
input[type="text"].normal100{
    display:block;
    font-size: 1.6em;
    width:100%;
    margin:0;
    padding:0;
    border-left:0;
    border-right:0;
}

You'll probably want to add a border to your div.


text:
Q: Why pandas column not converted to Int64? Here is my code:
import pandas as pd
import numpy as np

data = {'ID': [1,2,3,4,5,6,7,8,9],
       'Doc':['Order','Order','Inv','Order','Order','Shp','Order', 'Order','Inv'],
       'Rep':[101,101,101,102,102,102,103,103,103]}
df = pd.DataFrame(data)

#df['concat']= (df['ID'].convert_dtypes(convert_string = True) + "1").convert_dtypes(convert_integer = True)

df['concat']= (df['ID'].astype(str) + "1").convert_dtypes(convert_integer = True)

print(df['concat'].dtype)

output:
string

Why df['concat'] is not Int64 and how to get it?

A: Try
>>> df['concat'] = df['ID'].astype(str).add('1').astype('int64')
0    11
1    21
2    31
3    41
4    51
5    61
6    71
7    81
8    91
Name: ID, dtype: int64


text:
Q: How do I create an auto-updating chart on my Sharepoint site I have a seemingly simple usecase, that I can't figure out how to do, so here it is:
The Setup:
I gather a set data via PowerShell and write it into a CSV. For simplicity, just assume it's the amount of money in my wallet and the counts of specific bills.
That data is gathered every hour and the new values are appended to the existing CSV.
The Task:
Now I want to visualize this data on my Sharepoint site, with a simple Pie-Chart, that details what percentage of the total amount of money consists of each bill.
Uploading or updating the CSV on the sharepoint automatically is fairly trivial, however I can't seem to get behind the visualisation part.
What I tried so far:
I tried using PowerBI, but for some reason if I add the CSV as a datasource it will only allow me to use aggregates of each column as datavalues (e.g. the sum of all entries, which is nonsensical)
I can't seem to be able to use some kind of MIN or MAX function on the columns, to get the desired value to visualize.
Sharepoint itself only supports its inbuilt lists as a more or less dynamic source of data. I was playing around with this option as well, but the quick-chart function of sharepoint won't let me adjust whether the data is horizontal or vertical and will only allow single comumns as source (which utterly baffles me...)
I am sure there is a simple and straightforward way of doing this, but I am seemingly blind to it, so please help.
Here is a quick mock-example of the data I try to visualize:

totalMoney
ones
twos
fives
tens
twenties
fifties
hundreds

50
6
2
2
1
1
0
0

53
7
3
2
1
1
0
0

.
.
.
.
.
.
.
.


text:
Q: Best SOCKS proxy server for Linux I want to setup a SOCKS proxy server on linux, any recommendations?
I currently use SS5 and want to know if there are any better alternatives.

A: I dunno whether it's the best one or not, but I can mention DeleGate.

A: Depends on what you need, but the good old Squid can do almost anything.

A: Better? sure, try Zeus's ZXTM, way better but tens of thousands of dollars per license - could you try narrowing down your requirements please.

A: I recommend SSH as well, mainly because of the strong crypto and maturity of the code. Here is the command I use:
ssh -p 22 -C2qTnN -D 8080 user@remote-ssh-server.net


text:
Q: Rewrite Image URL I am using a RESTful API provided by monitoring software and it works great to pull resource usage graphs. Unfortunately the entire URL including the private hash key is exposed in the image URL meaning I cannot publicly display the information.
As I would like to avoid caching the images by saving them to disk on the web-server, is there any way that I can mask/rewrite the image URL? Currently I use the following format to pull it and this is what is displayed when you right click -> view image info.
http://domain.net/chart.png?type=graph&graphid=&width=840&height=300&id=9776&username=myuser&passhash=mypasshash

A: If the url is on the same server, you can use an internal rewrite. If you go to http://example.com/mygraph.png it will be internally rewritten to that filepath and the client will still see http://example.com/mygraph.png in their url bar.
RewriteRule ^mygraph.png$ /chart.png?type=graph&graphid=&width=840&height=300&id=9776&username=myuser&passhash=mypasshash [L]

If the image is on an external domain, you'll have to proxy the request. When http://example.com/mygraph.png is requested, your server will redo the request to an external server via an internal proxy. Because of this, the external server will see you as the other end of the line, and your server will pass the response of the external server to the client.
RewriteRule ^mygraph.png$ http://externaldomain.com/chart.png?type=graph&graphid=&width=840&height=300&id=9776&username=myuser&passhash=mypasshash [P,L]

The documentation of mod_rewrite can be found here. This documentation gives more information about proxying.


text:
Q: CTE to replace JOIN Can I use CTE instead of the my code here  ? Here are the two tables and my code .
tbl1

D_ID    department      employee name            manager name
112         d01         john d                   Peter k
113         d01         Emily f                  kevin s

tbl2

Emp_id   employee name    D_ID
100      john d           112
200      peter k          112
800      Emily f          113
500      kevin s          113

My code below  , what I did is I joined tbl1 with tbl2 on D_ID and employee name and then filter out the records where employee's emp_id > manager's emp_id .
DECLARE @level nvarchar(MAX) =
(
     select X.D_ID ,x.employee_NAME, x.emp_ID as employee_id,
         y.manager_name ,y.emp_id as manager_id
) + ' '
from (
    select distinct b.d_id , a.emp_id as employee_id
    from tbl1  a , tbl2 b
    where a.d_id=b.d_id and a.employee_NAME=b.employee_NAME
) x ,
(
    select distinct b.d_id , a.emp_id as manager_id
    from tbl1  a , tbl2 b
    where a.d_id=b.d_id and a.employee_NAME=b.manager_NAME
) Y
where x.department=y.department and x.employee_id>=y.manager_id

FOR XML PATH('')
)
IF @level IS NOT NULL
        BEGIN
            RAISERROR(' employee ID>manager_id:  %s',16, 1, @level)
            with log;
        END;

DESIRED OUTPUT is below as Emily f's employee id is > than her manager's ID .
 D_ID  employee_NAME  employee_id manager_name  manager_id
 113   Emily f         800        kevin s       500

A: I think you just need some joins:
select t1.d_id, t1.employee_name, te.emp_id,
       t1.employee_name as manager_name, tm.emp_id as manager_id
from tbl1 t1 join
     tbl2 te
     on t1.employee_name = te.employee_name join
     tbl2 tm
     on t1.manager_name = tm.employee_name
where te.emp_id > tm.emp_id;

It is quite curious that you are using the names to connect the two tables.  Normally, you would use the employee id for this purpose and look up the name using the id.


text:
Q: import .car file in IBM WebSphere 8 I am very new to WebSphere. I have managed to install .war file successfully but application is not starting/running. I found it is depending on Environment settings and other parameters from log file.
Now I have a .car file which on import will complete all settings and my application will run without any issues.
Please help me how to import .car file into WebSphere.

A: This has been tested with Eclipse Mars 4.5.2 and IBM Websphere Application Server 8.5

*

*Start your Websphere server using Eclipse or from command prompt.

*Navigate to %WAS_INSTALL_DIR%\WebSphere\AppServer\profiles\profile_name\bin.

*Launch wsadmin batch script and login using your profile security credentials.

*Use the following commands
$AdminTask importWasprofile {-archive c:\backup\was_restore.car}

$AdminConfig save

Further details can be found at:
https://www-304.ibm.com/support/docview.wss?uid=swg21207526

A: See details about importing car files here - ConfigArchiveOperations command.
If you exported whole profile, then to import use:
AdminTask.importWasprofile('[-archive c:/myCell.car]')

Instead of car files, you can consider also using property based configuration - Using properties files to manage system configuration


text:
Q: Python-Append results of multiple inputs and print them all together as single output n=int(input("Enter no. of divisions:"))
for i in range(n):
    (x, y) = map(int,input().split())
    m=x/y
    print(m)

This is a sample code which takes 2 inputs at a time  and gives the result after entering each input.
The output i'm getting is:
Enter no. of divisions:3
6 3
2.0
8 4
2.0
15 3
5.0

But i need the output as
Enter no. of divisions:3
6 3
8 4
15 3
2.0
2.0
5.0

I need all the results to print together.How do i append the results?plz help

A: You can do two loops, saving the results on the first:
n = int(input("Enter no. of divisions:"))
results = []
for i in range(n):
    (x,y) = map(int,input().split())
    results.append(x/y)
for result in results:
    print(result)


text:
Q: Need to implement or duplicate url rewritings for membership project - but don't want to use heavy framework I have a simple membership project and teh client wishes that urls be simple rather than having something like:
index.php?p=view-member&id=568157&hash=00218546598797898798162454712
he would like to see it as so:
website.com/member/username
Now I've worked with Zend and understand you need to do some htaccess alterations to get this done and this is like already easy to do in Zend Framework but I don't want to use the Zend framework for this as I already have a fully functional membership project I built which I would like to tweak for this project.
I thought of creating empty member folders with a simple php file that would include my main php file but am not sure of what complications I would run into if I use such a system. I'm open to ideas here guys. What do I do?

A: You don't need a framework to do this. Just use Apache URL rewriting with mod_rewrite. For example, in .htaccess in your document root (top-level directory that is served):
RewriteEngine On
RewriteBase /
RewriteRule ^member/(\w+)$ /index.php?p=view-member&id=$1

If you need some sort of hash to identify the user, don't put it in the URL (like your hash parameter is). Use a cookie.
You can of course use other Webservers such as IIS or nginx.

A: If you are running Apache a RewriteRule with mod_rewrite could do the trick. You also have to change index.php so that it takes username as a parameter and stores the hash in a cookie/session instead of in the URL.


text:
Q: changing bounding box color in object detection Is there a way to make the bounding box color matches the detected object color.
Say I'm doing car detection using YOLO, and we want for the bounding box color to match the detected car, per say.
Thanks in advance.
I'm using YOLOv4.


text:
Q: Different approaches to calculating the Christoffel symbols I would be very grateful to whoever can debug the following calculations...
We have the metric for static spacetime: $$ds^2 = -\exp(2U(\vec x))dt^2+h_{ij}(\vec x) d x^i d x^j$$
I want to find the associated Christoffel symbols.
I know of 2 ways:
The first is to use the formula $$\Gamma^a_{bc}={1\over 2}g^{ad}(g_{dc,b}+g_{db,c}-g_{bc,d})$$
Using this formula, I get $$\Gamma^0_{0i}={\partial U\over \partial x^i}$$ for $i=1,2,3$.
However, by using a second way -- by reading off the Euler-Lagrange equation ,I got an extra factor of $2$ and I can't spot where I have made a mistake. Here is what I did:
The Lagrangian $$L=\exp(2U(\vec x))\dot t^2-h_{ij}(\vec x) \dot x^i \dot x^j$$
So by the Euler-Lagrange equation for the $t$ component, $${d\over d\tau}(\exp(2U(\vec x))\dot t)=0$$
which leads to $$\ddot t +2{\partial U\over \partial x^i} \dot x^i \dot t=0$$
Therefore giving $$\Gamma^0_{0i}=2{\partial U\over \partial x^i}$$
What went wrong, where? Are my approaches and formulae correct?
Thanks.

A: The first one is probably correct, and you are likely not counting correctly in the second method. You should compare you result
$\ddot{t}+ 2 \frac{\partial U}{\partial x^{i}} \dot{x}_i \dot{t}=0$
to
$\ddot{t}+ \Gamma^0_{\mu \nu} \dot{x}^\mu \dot{x}^{\nu}=0  $
or
$\ddot{t}+ \Gamma^0_{i 0} \dot{x}^i \dot{x}^{0}+ \Gamma^0_{0 i} \dot{x}^0 \dot{x}^{i}=0  $
which is
$\ddot{t}+ \Gamma^0_{i 0} \dot{x}^i \dot{t} + \Gamma^0_{0 i} \dot{t} \dot{x}^{i}=
\ddot{t}+ 2\Gamma^0_{i 0} \dot{x}^i \dot{t} = 0$.
Which yields
$\Gamma^0_{i 0} = \frac{\partial U}{\partial x^{i}}$.

A: Couple mistakes:

*

*The second term in the metric should read $h_{ij}(\vec x)dx^idx^j$ not $h_{ij}(\vec x) \dot x^i\dot x^j$

*The first term in the Langrangian should have $\dot t^2$ instead of $dt^2$ which means that in the equation after the Lagrangian you should have a $\dot t^2$, and (I redid the calc.) this gives an answer that matches the first method without the extra factor of $2$.
Edit. My #2 doesn't solve the problem of the factor of two; BJBunk's answer does.


text:
Q: JSON.stringify output to div in pretty print way I JSON.stringify a json object by
result = JSON.stringify(message, my_json, 2)

The 2 in the argument above is supposed to pretty print the result.  It does this if I do something like alert(result).  However, I want to output this to the user by appending it inside a div.  When I do this I get just a single line showing up.  (I don't think it is working because the breaks and spaces are not being interpreted as html?)
{ "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 }

Is there a way to output the result of JSON.stringify to a div in a pretty print way?

A: My proposal is based on:

*

*replace each '\n' (newline) with a

*replace each space with

var x = { "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 };

document.querySelector('#newquote').innerHTML = JSON.stringify(x, null, 6)
     .replace(/\n( *)/g, function (match, p1) {
         return '
' + ' '.repeat(p1.length);
     });

A: Full disclosure I am the author of this package but another way to output JSON or JavaScript objects in a readable way complete with being able skip parts, collapse them, etc. is nodedump, https://github.com/ragamufin/nodedump

A: Please use a
  tag
demo : http://jsfiddle.net/K83cK/

var data = {
  "data": {
    "x": "1",
    "y": "1",
    "url": "http://url.com"
  },
  "event": "start",
  "show": 1,
  "id": 50
}

document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);

A: Consider your REST API returns:
{"Intent":{"Command":"search","SubIntent":null}}

Then you can do the following to print it in a nice format:

Output will de displayed here.

var ciResponseText = document.getElementById('ciResponseText');
var obj = JSON.parse(http.response);
ciResponseText.innerHTML = JSON.stringify(obj, undefined, 2);

A: A lot of people create very strange responses to these questions that make alot more work than necessary.
The easiest way to do this consists of the following

*

*Parse JSON String using JSON.parse(value)

*Stringify Parsed string into a nice format - JSON.stringify(input,undefined,2)

*Set output to the value of step 2.

In actual code, an example will be (combining all steps together):
    var input = document.getElementById("input").value;
    document.getElementById("output").value = JSON.stringify(JSON.parse(input),undefined,2);

output.value is going to be the area where you will want to display a beautified JSON.

A: Make sure the JSON output is in a
 tag.

A: print the state of a component with JSX
render() {
  return (

Adopt Me!

        {JSON.stringify(this.state, null, 4)}

  );
}

stringify

A: If your
 tag is showing a single-line of JSON because that's how the string is provided already (via an api or some function/page out of your control), you can reformat it like this:
HTML:

{"some":"JSON string"}

JavaScript:
    (function() {
        var element = document.getElementById("json");
        var obj = JSON.parse(element.innerText);
        element.innerHTML = JSON.stringify(obj, undefined, 2);
    })();

or jQuery:
    $(formatJson);

    function formatJson() {
        var element = $("#json");
        var obj = JSON.parse(element.text());
        element.html(JSON.stringify(obj, undefined, 2));
    }

A: Wrap it by pre tag

 { JSON.stringify(todos, null, 4)}

and the output will be
[
    {
        "id": "6cbc8fc4-a89e-4afa-abc1-f72f27b14271",
        "title": "shakil",
        "completed": false
    },
    {
        "id": "5ee68df8-e152-46ae-82e2-8eb49f477d6f",
        "title": "kobir",
        "completed": false
    }
]

A: If this is really for a user, better than just outputting text, you can use a library like this one https://github.com/padolsey/prettyprint.js to output it as an HTML table.

A: use style white-space: pre the
 tag also modifies the text format which may be undesirable.

A: you can try this repository :  https://github.com/amelki/json-pretty-html

A: for those who want to show collapsible json can use renderjson
Here is the example by embedding the render js javascript in html

<!DOCTYPE html>

A: it's for Laravel, Codeigniter
Html:

Controller: Return the JSON value from the controller as like as
return json_encode($data, JSON_PRETTY_PRINT);
In script:

result will be

A: You can also use react-json-tree package if you are using React.
I created a component for it like below that accept a data props.
import React from 'react';
import JSONTree from 'react-json-tree'
import './style.css';

const theme = {
    scheme: 'monokai',
    base00: '#272822',
    base01: '#383830',
    base02: '#49483e',
    base03: '#75715e',
    base04: '#a59f85',
    base05: '#f8f8f2',
    base06: '#f5f4f1',
    base07: '#f9f8f5',
    base08: '#f92672',
    base09: '#fd971f',
    base0A: '#f4bf75',
    base0B: '#a6e22e',
    base0C: '#a1efe4',
    base0D: '#66d9ef',
    base0E: '#ae81ff',
    base0F: '#cc6633',
};

const TreeView = (props) => {

    return (

            <JSONTree
                data={props.data}
                theme={theme}
                invertTheme={true}
                hideRoot
                labelRenderer={([key]) => {
                    return {key}:
                }}
                valueRenderer={(valueAsString, value) => {
                    return {value};
                }}
                getItemString={() => ''}
            />

    );
}

export default TreeView;

Then I use it inside an html element like below after importing the component.

 <TreeView data={s.value} />


text:
Q: openSSL rackspace ubuntu update Given the recent heartbleed and requirement to update the openSSL version I have followed all the instructions to do so.
I've run
sudo apt-get update
sudo apt-get upgrade

openssl version -a
OpenSSL 1.0.1c 10 May 2012
built on: Wed Jan  8 20:51:55 UTC 2014
platform: debian-amd64
options:  bn(64,64) rc4(8x,int) des(idx,cisc,16,int) blowfish(idx)
compiler: cc -fPIC -DOPENSSL_PIC -DZLIB -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -    DHAVE_DLFCN_H -m64 -DL_ENDIAN -DTERMIO -g -O2 -fstack-protector --param=ssp-buffer-size=4 -    Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -    Wa,--noexecstack -Wall -DOPENSSL_NO_TLS1_2_CLIENT -DOPENSSL_MAX_TLS1_2_CIPHER_LENGTH=50 -    DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/usr/lib/ssl"

Yet everytime I run version -a, it does not update the built on date to April 7.
Why is this. What commands can I run to upgrade the OPENSSL to 1.0.1g or to the latest build? Im using a Rackspace Ubuntu server.


text:
Q: React- Destruct State error in Typescript I am trying to implement a react component for AutoComplete by referring to a Tutorial.I am using Typescript for my development. When I try to destruct the state inside the render suggestions method the TSLint compiler shows an error saying 'Property Suggestions does not exist on type {}'. Could any one help me to overcome this. It is a big big help.
import * as React from 'react';

export default class Autocomplete extends React.Component<{},{}> {
    items: string[];
    constructor( props){
        super(props);
        this.state = {
            suggestions :[],
        };
        this.items =['David','Damian','sara'];
    }

    render() {
        return (

            <input
                type="text" onChange={this.onTextChanged}
            />
                {this.renderSuggestions()}

        );
    }

    onTextChanged = (e) =>{
        console.log(e.target.value);
        const value = e.target.value;
        let suggestions =[];
        if(value.legth>0){
            const regex = new RegExp(`^${value}`,'i');
            suggestions = this.items.sort().filter(v => regex.test(v));
        }
        this.setState(()=> ({suggestions}));
    }

    renderSuggestions() {
        const {suggestions } = this.state;
        if(suggestions.length === 0){
            return null;
        }
        return (

                {suggestions.map((item)=>
{item}
)}

        );
    }
}

[EDIT : Attached the Screen Capture]

A: The error was in your
if(value.legth>0){}, you missed n for length. It was just a typo error.
Also I tried the typescript version and this was the only mistake
Link to typescript version
Updated working code is
 import * as React from 'react';

export default class Autocomplete extends React.Component {
    items=[];
    constructor( props){
        super(props);
        this.state = {
            suggestions :[],
        };
        this.items =['David','Damian','sara'];
    }

    render() {
        return (

            <input
                type="text" onChange={this.onTextChanged}
            />
                {this.renderSuggestions()}

        );
    }

    onTextChanged = (e) =>{
        console.log(e.target.value);
        const value = e.target.value;
        let suggestions =[];
        if(value.length>0){
            const regex = new RegExp(`^${value}`,'i');
            suggestions = this.items.sort().filter(v => regex.test(v));
        }
        this.setState(()=> ({suggestions}));
    }

    renderSuggestions() {
        const {suggestions } = this.state;
        if(suggestions.length === 0){
            return null;
        }
        return (

                {suggestions.map((item)=>
{item}
)}

        );
    }
}

A: You specify in your component that the state is of type {} by doing React.Component<{}>. You can usually avoid this by letting typescript infer the state but it has a bit of a problem doing that when the state is assigned inside the constructor. You can usually fix these by assigning them directly as fields inside the class like
export default class Autocomplete extends React.Component {
    items = ['David','Damian','sara']
    state = { suggestions :[] }
    // rest of your component here
}

You can do this in your current class because you don't use the constructor for anything other than setting state, but if that's not an option, you can make sure typescript understands the state properly by assigning it as an explicit generic argument for your component like such.
interface AutocompleteState {
  suggestions: Suggestion[]
}

export default class Autocomplete extends React.Component<AutocompleteState> {
  constructor() {
    // ...
  }
}

A: By Considering all the comments and bit of struggling and some readings I made it work. Thank you for all your suggestions.
import * as React from 'react';
import { Suggestions } from 'office-ui-fabric-react';

export interface IServiceState {
    suggestions ?: string []
}

export default class Autocomplete extends React.Component<{},IServiceState> {
    items =['David','Damian','sara'];
    constructor( props){
        super(props);
        this.state = {
            suggestions : [],
        };

    }

    render() {
        return (

            <input
                type="text" onChange={this.onTextChanged}
            />
                {this.renderSuggestions()}

        );
    }

    onTextChanged = (e) =>{
        console.log(e.target.value);
        const value = e.target.value;
        let suggestions :string[];
        if(value.length>0){
            const regex = new RegExp(`^${value}`,'i');
            suggestions = this.items.sort().filter(v => regex.test(v));
            console.log(suggestions);
        }
        //this.setState(()=> ({suggestions1}));
       //this.setState()
        this.setState({suggestions : suggestions});
    }

    renderSuggestions() {
       const suggestions :string[]= this.state.suggestions;
       console.log('render Suggestions');
       console.log(this.state.suggestions);
       console.log('render1 Suggestions');
        if(Suggestions.length === 0){
            return null;
        }
        return (

                {suggestions.map((item)=>
{item}
)}

        );
    }
}


text: Q: 'find-tag' Cannot Locate Emacs Source I've been working through An Introduction to Programming in Emacs Lisp and have run into an issue on an exercise in section 4.6. The exercise states Using find-tag, find the source for the copy-to-buffer function. However, when using find-tag on my Mac installation of Emacs 24.2, it is unable to find the tag for the copy-to-buffer function. I have already created a tags file in the Emacs /usr/local/share/emacs/24.2/lisp directory, and find-tag is able to find many functions within this directory, but not copy-to-buffer. Any thoughts?


text:
Q: Make Outlook understand "all day" event invites from Google Calendar I'm creating an all-day event in my personal Google Calendar, and am inviting myself on my work e-mail account to keep my calendars in sync for that event. I'm using Outlook 2016 on Windows 10 for the second account.
For some reason, Outlook thinks an "All Day" event is shifted 1 hour. Suppose an ICS with this info:
BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
DTSTART;VALUE=DATE:20171103
DTEND;VALUE=DATE:20171104
DTSTAMP:20171004T080944Z
....etc.

This shows up in Outlook like this:
When: vrijdag 3 novemeber 2017 01:00 to zaterdag 4 november 2017 01:00

What happens is that it's shifted exactly one hour, and in the "Month" view it would awkwardly show up on both Friday ("vrijdag") and Saturday ("zaterdag").
What I would like is for the event to show as an "All Day" event on Friday in Outlook too.
How can I get Outlook to behave?

More details about the reverse situation:
If I create an "All Day" event in Outlook and save it to ICS it would look like this:
BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 16.0 MIMEDIR//EN
VERSION:2.0
METHOD:PUBLISH
X-MS-OLK-FORCEINSPECTOROPEN:TRUE
BEGIN:VEVENT
CLASS:PUBLIC
CREATED:20171004T082925Z
DTEND;VALUE=DATE:20171104
DTSTAMP:20171004T082925Z
DTSTART;VALUE=DATE:20171103
LAST-MODIFIED:20171004T082925Z
....etc.

In Google Calendar this does show up correctly as an "All Day" event.

Some info on my time zone settings:

*

*Google Calendar says, when I click "Timezone" on an event that does have times, that I'm in the "GMT +02:00 (Amsterdam)" timezone.

*Windows Date & Time says I'm in Time zone "(UTC+01:00) Amsterdam, Berlin...". Outlook Options under "Calendar" reports the same Time zone.

A: I have had a related frustration for a long time and have come up with an easy workaround.  I create all day appointments in my Google calendar and invite my Outlook calendar.  Both calendars are set to US Eastern Standard Time (5 hours GMT).  My all day Google appointments shift 5 hours in my Outlook or 6 hours during daylight savings time.
The fix:  In Google, I now create appointments 12:00 a.m. on the day of the event through 12:00 a.m. the next day.  I do not use the "all day" check box.  This automatically includes the time zone when I send an invitation.  When I accept these invites in Outlook, they correctly display in a single day.

A: I had the same problem. The solution is to add the timezone information into the .ics file like this:
BEGIN:VTIMEZONE
TZID:W. Europe Standard Time
BEGIN:STANDARD
DTSTART:16011028T030000
RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:16010325T020000
RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=3
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
END:DAYLIGHT
END:VTIMEZONE

This should fix your problem and give you an all-day-event. Your event will now start at 0:00:00 and end there as well. You should obviously enter your preferred timezone if you are not in CET.


text:
Q: Cannot connect to SQL Server using SSMS, but application can access it In my ASP.NET MVC application, I have a connection string that connects to remote SQL Server TestServer1.
I ran the web application and I see the data in the application from the remote SQL Server with out any issues.
But when I try to connect to the remote SQL Server using SSMS, I get time out error.
I ran below commands in the command prompt
ping TestServer1 - success
telnet TestServer1 1433 - failed

I know we need to open port 1433 to connect from SSMS. But how the database is accessed from the web application?


text:
Q: PMU for multi threaded environment I am planning to measure PMU counters for L1,L2,L3 misses branch prediction misses , I have read related Intel documents but i am unsure about the below scenarios.could some one please clarify ?
//assume PMU reset and PERFEVTSELx configurtion done above
ioctl(fd, IOCTL_MSR_CMDS, (long long)msr_start)  //PMU start counters
my_program();
ioctl(fd, IOCTL_MSR_CMDS, (long long)msr_stop)   ///PMU stop
//now reading PMU counters

1.what will happen if my process is scheduled out when my_program() is running, and scheduled to another core?
2.what will happen if process scheduled out and schedule back to same core again, meanwhile some other process reset the PMU counters?
How to make sure that we are reading the correct values from PMU counters.?

Machine details:CentOS with Linux kernel 3.10.0-327.22.2.el7.x86_64 , which is powered up with Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz

Thanks

A: Summary of the Intel forum thread started by the OP:

*

*The Linux perf subsystem virtualizes the performance counters, but this means you have to read them with a system call, instead of rdpmc, to get the full virtualized 64-bit value instead of whatever is currently in the architectural performance counter register.

*If you want to use rdpmc inside your own code so it can measure itself, pin each thread to a core because context switches don't save/restore PMCs.  There's no easy way to avoid measuring everything that happens on the core, including interrupt handlers and other processes that get a timeslice.  This can be a good thing, since you need to take the impact of kernel overhead into account.

More useful quotes from John D. McCalpin, PhD ("Dr. Bandwidth"):

For inline code instrumentation you should be able to use the "perf events" API, but the documentation is minimal.  Some resources are available at http://web.eece.maine.edu/~vweaver/projects/perf_events/faq.html
You can use "pread()" on the /dev/cpu/*/msr device files to read the
MSRs -- this may be a bit easier to read than IOCTL-based code.  The
codes "rdmsr.c" and "wrmsr.c" from "msr-tools-1.3" provide excellent
examples.

There have been a number of approaches to reserving and sharing
performance counters, including both software-only and combined
hardware+software approaches, but at this point there is not a
"standard" approach.  (It looks like Intel has a hardware-based
approach using MSR 0x392 IA32_PERF_GLOBAL_INUSE, but I don't know what
platforms support it.)

your questions

what will happen if my process is scheduled out when my_program() is running, and scheduled to another core?

You'll see random garbage, same if another process resets PMCs between timeslices of your process.

A: i got the answers from some Intel forum, the link is below.
https://software.intel.com/en-us/forums/intel-moderncode-for-parallel-architectures/topic/673602


text:
Q: AbstractMethodError due to method missing on a trait (library update) I have a fairly basic scenario, where I'm using a trait from an external library, add an object to a list that's a "global" in that lib:
// my code, list is a Seq in an object from the external library
list.add(new LibraryTrait(){ override def method() = { /* code */ } })

// from an external library, version used at compile time
trait LibraryTrait {
    def method() = {}
}

// from an external library, version used at runtime
trait LibraryTrait {
    def method() = {}
    def method2() = {}
}

At runtime it's failing with an AbstractMethodError, since the anonymous class I'm creating is missing method2() and the library I'm using at runtime is doing a call list.foreach(x -> x.method2()).
Is there anything else I can do, besides compiling against the version that's used at runtime, for it to work?
Not being a scala compiler expert I tried changing my code into this (hoping it will add the method properly):
list.add(new LibraryTrait(){
    override def method() = { /* code */ }
    def method2() = { /* code */ }
})

But it does not work.

A: To answer my own question the fix from my post doesn't work but this seems to compile to a correct form, which works with both versions:
trait MyTrait extends LibraryTrait {
  def method2() {}
}

class MyClass extends MyTrait {
  override def method() = { /* code */
}

list.add(new MyClass)

This is a "hack" solution - meaning it works but I'm not sure why so if there's anyone more proficient in the ways of the compiler and could describe the difference in bytecode (anonymous class vs this solution) I'd greatly appreciate it and accept it as the answer.


text:
Q: which CSS selector should I use for accessing the numbers on a graph in a website ( python) I am trying to exatract some numbers from a graph on this page ( https://www.zoopla.co.uk/local-info/?outcode=cm15&incode=9bq )
There are 5 tabs in that graph.
I am interested in the 5th tab (Newspapers).
When I run this piece of code, I get some info about the first tabbed graph.
but soup.find_all('',id='neighbours-newspapers') returns a blank.
from bs4 import BeautifulSoup as bs
import requests

res=requests.get('https://www.zoopla.co.uk/local-info/?outcode=cm15&incode=9bq')
soup = bs(res.content, 'lxml')

housing = [item.text.replace('\n','').strip() for item in soup.find_all('',id='local-info-neighbours')]
print(housing)

newspapers = [item.text.replace('\n','').strip() for item in soup.find_all('',id='neighbours-newspapers')]
print(newspapers)

I am not sure how to access an id within an id if that's what it is. Could someone help please?

A: You can use regex and requests
import requests
import re
import ast

headers = {
    'Referer' : 'https://www.zoopla.co.uk/',
    'User-Agent' : 'Mozilla/5.0'
}
res = requests.get('https://www.zoopla.co.uk/widgets/local-info/neighbours-chart.html?outcode=cm15&incode=9bq&category=Newspapers', headers = headers)
data = re.search(r'categories: (\[.*])', res.text ,flags=re.DOTALL).group(1)
items = re.findall(r'(\[.*])', data)

papers = ast.literal_eval(items[0])
numbers = ast.literal_eval(items[1])
result = list(zip(papers, numbers))
print(result)


text:
Q: Weak-minded vs Unintelligent? My sense, despite the literal interpretation one might make, is that stupidity and being weak-minded are different but possibly related. I think weak-minded might mean easily swayed which I think is not a characteristic of intelligence.
At the same time, being stubborn, which I think might be the opposite of weak-mindedness, is also not a mark of intelligence, just the opposite sometimes.
So what does weak-minded really mean and does it indeed imply that the someone described that way might be unintelligent?

A: Being "weak-minded" can imply weakness of the will, i.e. a lack of self-control that causes one to act against one's better judgment. (The technical term for this is "akrasia.")

A: The term "weak-minded" has multiple common meanings that are different. It can mean stupid. It can mean just a little bit stupid. It can mean easily swayed. It can mean passive as opposed to aggressive. Basically any mental defect is grounds to fairly call someone "weak-minded".
Contrast with "stupid", which has only one common meaning. In idiosyncratic slang it can mean "really good" or it can intensify an adjective, eg "stupid big", but adoption of use cases like these is generally isolated and fleeting.


text:
Q: A shorter way to indicate "living in luxury"
I hate......... I exercise moderation…It will be easy to forget your vision and purpose one you have fine clothes, fast horses and beautiful women. [In which case], you will be no better than a slave, and you will surely lose everything. [Genghis Khan.]

a) luxury
b) luxurious life
c) luxurious lifestyle
I was wondering which choice conveys the message of "living in luxury" best in my provided context.


text:
Q: Getting Abort trap: 6 from Google Speech API My specific question is how do you fix an "Abort trap: 6" error from Google gRPC (the Speech API).  More generally, as someone trying to ramp up on using the services, any tips on troubleshooting would be appreciated.  I haven't found good C++ documentation, just random hints around the internet.
I've got the streaming example transcribe running successfully.  When I try to modify the code to pass in data from a microphone, my new code is crashing around the time it returns the first interim response.
I'm running with debug output, using GRPC_VERBOSITY=debug GRPC_TRACE=api ./testSpeech
The key difference I see in the output between my failing code and the working sample is the following:
Working log
I1221 07:01:42.805304000 123145420480512 completion_queue.cc:764]      cq_end_op_for_pluck(cq=0x7faa705043e0, tag=0x7000070b1990, error="No Error", done=0x10f9e3740, done_arg=0x7faa70467310, storage=0x7faa70467388)
I1221 07:01:42.805330000 123145420480512 completion_queue.cc:1297]     RETURN_EVENT[0x7faa705043e0]: OP_COMPLETE: tag:0x7000070b1990 OK
I1221 07:01:43.029567000 4652266944 completion_queue.cc:764]           cq_end_op_for_pluck(cq=0x7faa705043e0, tag=0x7ffee04f8350, error="No Error", done=0x10f9e3740, done_arg=0x7faa705304d0, storage=0x7faa70530548)
I1221 07:01:43.029637000 4652266944 completion_queue.cc:1297]          RETURN_EVENT[0x7faa705043e0]: OP_COMPLETE: tag:0x7ffee04f8350 OK
Result stability: 0.01
0   how

Failing log
I1221 08:00:32.559490000 4561257920 call.cc:1967]                      grpc_call_start_batch(call=0x7fe4f1033660, ops=0x7ffeec81b2d0, nops=1, tag=0x7ffeec81b630, reserved=0x0)
I1221 08:00:32.559509000 4561257920 call.cc:1566]                      ops[0]: SEND_MESSAGE ptr=0x7fe4f0571e00
I1221 08:00:32.559619000 4561257920 completion_queue.cc:764]           cq_end_op_for_pluck(cq=0x7fe4f0615f60, tag=0x7ffeec81b630, error="No Error", done=0x1036c18f0, done_arg=0x7fe4f0616820, storage=0x7fe4f0616898)
I1221 08:00:32.559650000 4561257920 completion_queue.cc:1297]          RETURN_EVENT[0x7fe4f0615f60]: OP_COMPLETE: tag:0x7ffeec81b630 OK
After write
I1221 08:00:32.559680000 4561257920 metadata_array.cc:34]              grpc_metadata_array_destroy(array=0x7ffeec81bc50)
I1221 08:00:32.559687000 4561257920 metadata_array.cc:34]              grpc_metadata_array_destroy(array=0x7ffeec81bc18)
After sending chunk
I1221 08:00:32.712612000 123145462775808 completion_queue.cc:764]      cq_end_op_for_pluck(cq=0x7fe4f0615f60, tag=0x7000099075d0, error="No Error", done=0x1036c18f0, done_arg=0x7fe4f040cc10, storage=0x7fe4f040cc88)
I1221 08:00:32.712655000 123145462775808 completion_queue.cc:1297]     RETURN_EVENT[0x7fe4f0615f60]: OP_COMPLETE: tag:0x7000099075d0 OK
I1221 08:00:32.712712000 123145462775808 call.cc:573]                  grpc_call_unref(c=0x7fe4f1033660)
Result stability: 0.01
0   what time
I1221 08:00:32.712930000 123145462775808 call.cc:1967]                 grpc_call_start_batch(call=0x7fe4f1033660, ops=0x700009907300, nops=2, tag=0x7000099075d0, reserved=0x0)
I1221 08:00:32.712945000 123145462775808 call.cc:1566]                 ops[0]: RECV_INITIAL_METADATA ptr=0x7ffeec81bc18
I1221 08:00:32.712954000 123145462775808 call.cc:1566]                 ops[1]: RECV_MESSAGE ptr=0x7000099075f8
E1221 08:00:32.712961000 123145462775808 call_op_set.h:947]            assertion failed: false
Abort trap: 6

Note the grpc_metadata_array_destroy calls in my failing version but not the working sample.  They occur for each chunk of audio samples I send.  Any suggestions from those more familiar with these APIs?
Edit: the assert that failed is from the following code segment in gRPC:
if (err != GRPC_CALL_OK) {
  // A failure here indicates an API misuse; for example, doing a Write
  // while another Write is already pending on the same RPC or invoking
  // WritesDone multiple times
  // gpr_log(GPR_ERROR, "API misuse of type %s observed",
  //        g_core_codegen_interface->grpc_call_error_to_string(err));
  GPR_CODEGEN_ASSERT(false);
}

Uncommenting the log says the error is "GRPC_CALL_ERROR_TOO_MANY_OPERATIONS", although I'm only processing a single audio stream.  The sample code just puts in a (seemingly) arbitrary sleep for 1 second after each write.


text:
Q: Change Url Params I got lost here with an issue when I try to achieve a case which a user can click on a button and change the language of a form in visual force page.
I know a way which works but don't support IE browsers -( which is kind of a problem for my users) with the URLSearchParams JS method.
The second way I tried is to put the language param for the apex:page :
language="{!$CurrentPage.parameters.lang}" :
<apex:page id="formPageId" controller="PaymentFormController" docType="html-5.0" showHeader="false" standardStylesheets="false" language="{!$CurrentPage.parameters.lang}">

and then, to get the lang param with js function and set it to the value that clicked.
for Example :
const param = new URL(location.href).searchParams;
param.set('lang','es')

My issue here is when I try to refresh the page with my new url (new param that i just had changed).
Anyone have any idea or a better way to do so?
Thanks!

A: Why not use action:function to pass language param in URL and re-render whole page by providing id to the page? I have provided page with id formPageId and re-rendering in action function.
<apex:page id="formPageId" controller="PaymentFormController" docType="html-5.0" showHeader="false" standardStylesheets="false" language="{!$CurrentPage.parameters.lang}" >

    <apex:form>
        <!-- Define the JavaScript function sayHello-->
        <apex:actionFunction name="changeLanguage" action="{!changeLanguageApex}" rerender="formPageId" status="myStatus">
             <apex:param id="lang" name="lang" value="" />
        </apex:actionFunction>
    </apex:form>

    <script>
        function onbuttonClick() {
            changeLanguage('es');
        }
    </script>

    <button type="button" onclick="onbuttonClick()">Change Language</button>
</apex:page>

Apex:
public class PaymentFormController{

    public PageReference changeLanguageApex(){
        PageReference pageRef = ApexPages.currentPage();

        pageRef.setRedirect(true);

       return pageRef;
    }

}


text:
Q: In emacs, how do I find the length of an identifier (or of the kill ring)? PL/SQL is restricted to a 30-character identifier length. I'd like to find the size of the identifier under my cursor without counting manually. (Underscores are breaking the identifier by word, so a solution by word may not work. I'm using emacs 24.3.1.)

A: I figured it out. Move the cursor to the beginning of the identifier. Then use C-M-@ to select the whole identifier (a "balanced expression") and M-= to show the statistics of the region. (On my Windows machine, C-M-2 works in lieu of C-M-shift-2.)

A: You found the answer (M-=) in 10 minutes -- good. Another thing that can help (no need to hit M-=):
Library modeline-posn.el shows the size of the active region in the mode line. See Mode-Line Position.


text:
Q: Windows XP - cmd.exe - Cannot execute batch file after switching to utf8 codepage After switching to utf8 codepage with "mode con cp select=65001", batch processing seams to stop working without any error messages.
Thus, executing "cmd.exe /c test.bat" in a freshly started console with codepage 437 or 850 being active works fine.
Executing "mode con cp select=65001" works fine.
Display of UTF-8-characters works fine.
Executing something like "echo Hallo!" works fine.
But executing "cmd.exe /c test.bat" stops working with no error message displayed.
It's not only a display error: The batch file does not get executed.
Switching back to any "old" character set lets it work fine again.
Switching forth to UTF8 character set lets it stop working again.
Of course, abstaining from UTF8 IS a solution - but with bad side effects in the background.

A: I don't know how you can start a batch file after the codepage is changed to 65001.
Even if you save the batch file in utf16-le or utf16-be it doesn't start.
But you can run a batch file and change the codepage inside,
but it is important that the rest of the code is cached in a block (parenthesis or ampersand line).
@echo off
(
chcp 65001
rem Do my UTF work
chcp 850
)
echo This works

chcp 65001 & type myFile & chcp 850
echo This also works


text:
Q: AWS EC2 UTC timezone conversion off by a day with moment JS Yesterday I posted this question about MongoDB UTC record timestamp issues when using MomentJS:
MomentJS not converting date correctly
Blakes Seven's answer solved the issue locally, but when I deployed to AWS EC2, the problem reoccurred. Here are the steps I took to understand the issue:

*

*I verified the Elastic Beanstalk instance was using the correct zip from S3 bucket. So the code fix is definitely live.

*EC2 location: US East (N. Virginia)

*The request location to MongoDB for records is the same for the local and live

*Launch Time: October 21, 2015 at 4:51:31 PM UTC-4 (2684 hours): I can't find the actual time zone config of my EC2, but this tells me it's UTC.

So my questions are:

*

*How can I verify that my EC2 is set to UTC time

*Is the server timezone even the issue? Somehow the dates aren't being read or parsed correctly

A: I have a simular issue. Everything was going fine with moment.locale('fr') but wen wrong on AWS EBS/EC2.
I solved it by using moment-timezone and force to 'Europe/Paris':

moment.tz('Europe/Paris')