text:
Q: The Connection String Property Has Not Been Initialized vb.net Please can you tell me why my database info is not pulling through. i am fearly new to vb and i have been trying to create this project with the help of google but stuck on linking my db
Imports System.Data.OleDb

Public Class MyeventDB

    Public Shared Function GetEvent(eventID As Integer) As Myevent
        Dim myevent As New Myevent
        Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
        Dim selectStatement As String =
            "SELECT EventID, Title, Date, Fee, Location, Distance " &
            "FROM Events " &
            "WHERE EventID = @EventID"
        Dim selectCommand As New OleDbCommand(selectStatement, connection)
        selectCommand.Parameters.AddWithValue("@EventID", eventID)
        Try
            connection.Open()
            Dim reader As OleDbDataReader _
                = selectCommand.ExecuteReader(CommandBehavior.SingleRow)
            If reader.Read Then
                myevent.EventID = CInt(reader("EventID"))
                myevent.Title = reader("Title").ToString
                myevent.DDate = reader("Date").ToString
                myevent.Fee = reader("Fee").ToString
                myevent.Location = reader("Location").ToString
                myevent.Distance = reader("Distance").ToString
            Else
                myevent = Nothing
            End If
            reader.Close()
        Catch ex As Exception
            Throw ex
        Finally
            connection.Close()
        End Try
        Return myevent
    End Function

    Public Shared Function AddEvent(myevent As Myevent) As Integer
        Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
        Dim insertStatement As String =
            "INSERT Events " &
            "(Title, Date, Fee, Location, Distance) " &
            "VALUES (@Title, @Date, @Fee, @Location, @Distance)"
        Dim insertCommand As New OleDbCommand(insertStatement, connection)
        insertCommand.Parameters.AddWithValue("@Title", myevent.Title)
        insertCommand.Parameters.AddWithValue("@Date", myevent.DDate)
        insertCommand.Parameters.AddWithValue("@Fee", myevent.Fee)
        insertCommand.Parameters.AddWithValue("@Location", myevent.Location)
        insertCommand.Parameters.AddWithValue("@Distance", myevent.Distance)
        Try
            connection.Open()
            insertCommand.ExecuteNonQuery()
            Dim selectStatement As String _
                = "SELECT IDENT_CURRENT('Events') FROM Events"
            Dim selectCommand As New OleDbCommand(selectStatement, connection)
            Dim eventID As Integer = CInt(selectCommand.ExecuteScalar)
            Return eventID
        Catch ex As Exception
            Throw ex
        Finally
            connection.Close()
        End Try
    End Function

    Public Shared Function UpdateEvent(oldEvent As Myevent,
            newEvent As Myevent) As Boolean
        Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
        Dim updateStatement As String =
            "UPDATE Events SET " &
            "Title = @NewTitle, " &
            "Date = @NewDate, " &
            "Fee = @NewFee, " &
            "Location = @NewLocation, " &
            "Distance = @NewDistance " &
            "WHERE EventID = @OldEventID " &
            "AND Title = @OldTitle " &
            "AND Date = @OldDate " &
            "AND Fee = @OldFee " & "AND Location = @OldLocation " &
            "AND Distance = @OldDistance"
        Dim updateCommand As New OleDbCommand(updateStatement, connection)
        updateCommand.Parameters.AddWithValue("@NewTitle", newEvent.Title)
        updateCommand.Parameters.AddWithValue("@NewDate", newEvent.DDate)
        updateCommand.Parameters.AddWithValue("@NewFee", newEvent.Fee)
        updateCommand.Parameters.AddWithValue("@NewLocation", newEvent.Location)
        updateCommand.Parameters.AddWithValue("@NewDistance", newEvent.Distance)
        updateCommand.Parameters.AddWithValue("@OldEventID", oldEvent.EventID)
        updateCommand.Parameters.AddWithValue("@OldTitle", oldEvent.Title)
        updateCommand.Parameters.AddWithValue("@OldDate", oldEvent.DDate)
        updateCommand.Parameters.AddWithValue("@OldFee", oldEvent.Fee)
        updateCommand.Parameters.AddWithValue("@OldLocation", oldEvent.Location)
        updateCommand.Parameters.AddWithValue("@OldDistance", oldEvent.Distance)

        Try
            connection.Open()
            Dim count As Integer = updateCommand.ExecuteNonQuery
            If count > 0 Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Throw ex
        Finally
            connection.Close()
        End Try
    End Function

    Public Shared Function DeleteEvent(myevent As Myevent) As Boolean
        Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
        Dim deleteStatement As String =
            "DELETE FROM Events " &
            "WHERE EventID = @EventID " &
            "AND Title = @Title " &
            "AND Date = @Date " &
            "AND Fee = @Fee " &
            "AND Location = @Location " &
            "AND Distance = @Distance"
        Dim deleteCommand As New OleDbCommand(deleteStatement, connection)
        deleteCommand.Parameters.AddWithValue("@EventID", myevent.EventID)
        deleteCommand.Parameters.AddWithValue("@Title", myevent.Title)
        deleteCommand.Parameters.AddWithValue("@Date", myevent.DDate)
        deleteCommand.Parameters.AddWithValue("@Fee", myevent.Fee)
        deleteCommand.Parameters.AddWithValue("@Location", myevent.Location)
        deleteCommand.Parameters.AddWithValue("@Distance", myevent.Distance)

        Try
            connection.Open()
            Dim count As Integer = deleteCommand.ExecuteNonQuery
            If count > 0 Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Throw ex
        Finally
            connection.Close()
        End Try
    End Function

End Class

Imports System.Data.OleDb

Public Class MyAthleteEvents

    Public Shared Function GetConnection() As OleDbConnection
        ' If necessary, change the following connection string
        ' so it works for your system
        Dim connectionString As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\lebom\Desktop\ICT3611Assignment\AthletesEvents.accdb")

        Return New OleDbConnection()
    End Function

End Class

A: In your MyAthleteEvents.GetConnection, you create one OleDbConnection object with a connection string but then, instead of returning that object, you return a second new OleDbConnection object.
This:
Return New OleDbConnection()

should be this:
Return connectionString

That said, why would you use the name 'connectionString' for a variable of type OleDbConnection?  It's not a connection string so why name it as though it is?  It would have to be a String to be a connection string.


text:
Q: Reformatting for Angular style guide 1.5 I am using the Angular spyboost utility wrapper. I am trying to reformat it for this angular 1 style guide.  I'm having a hard time with parts of it. I think I have most of it correct but the angular.forEach function is throwing me off. I am and am getting an error `Expected '{' and instead saw 'result'. Could someone help me please ?
 angular
    .module('myMod')
    .factory('MyService');
MyService.$inject = ['$rootScope', 'atmosphereService', 'atmosphere'];

function MyService ($rootScope, atmosphere) {
    return {
        subscribe: subscribe,
        getMessage: getMessage
    };

    function subscribe (r) {
        var responseParameterDelegateFunctions = ['onOpen', 'onClientTimeout', 'onReopen', 'onMessage', 'onClose', 'onError'];
        var delegateFunctions = responseParameterDelegateFunctions;
        var result = {};

        delegateFunctions.push('onTransportFailure');
        delegateFunctions.push('onReconnect');

        angular.forEach(r, function (value, property) {
            if (typeof value === 'function' && delegateFunctions.indexOf(property) >= 0) {
                if (responseParameterDelegateFunctions.indexOf(property) >= 0)
                    **result[property] = function (response) {**
                        $rootScope.$apply(function () {
                            r[property](response);
                        });
                    };
                else if (property === 'onTransportFailure')
                    result.onTransportFailure = function (errorMsg, request) {
                        $rootScope.$apply(function () {
                            r.onTransportFailure(errorMsg, request);
                        });
                    };
                else if (property === 'onReconnect')
                    result.onReconnect = function (request, response) {
                        $rootScope.$apply(function () {
                            r.onReconnect(request, response);
                        });
                    };
            } else
                result[property] = r[property];
        });

        function getMessage () {
            var vm = this;
            var request = {
                url: '/chat',
                contentType: 'application/json',
                transport: 'websocket',
                reconnectInterval: 5000,
                enableXDR: true,
                timeout: 60000
            };

            request.onMessage(response); {
                vm.$apply (function () {
                    vm.model.message = atmosphere.util.parseJSON(response.responseBody);
                });
            }
        }
        return atmosphere.subscribe(result);
    }

}

})(window.angular);

A: if (responseParameterDelegateFunctions.indexOf(property) >= 0)

is missing its curly braces?
if (responseParameterDelegateFunctions.indexOf(property) >= 0) {
    result[property] = function (response) {
           $rootScope.$apply(function () {
                    r[property](response);
                });
           };
}
else if (property === 'onTransportFailure') {
     result.onTransportFailure = function (errorMsg, request) {
         $rootScope.$apply(function () {
             r.onTransportFailure(errorMsg, request);
          });
      };
}
else if (property === 'onReconnect') {
     result.onReconnect = function (request, response) {
         $rootScope.$apply(function () {
              r.onReconnect(request, response);
         });
     };
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: parallel sparse matrix multiplication For sparse matrix multiplication, it is less efficiency than dense one mainly because more time is spent on locating and seeking elements in memory rather than CPU computation.
I am using matlab, and here, I need to do a very sparse matrix multiplication with a dense one, i.e. S times D where S is sparse and D is dense.
Then, my questions are that

*

*if D has k columns, and do S times D(:,k) in parallel for each k, will it be faster than matlab default routine S times D?

*if so, is it better for me to write .mex files, and do multi-threads computation in them?

Thanks very much~


text:
Q: how to change particular column cell foreground and background color in oracle forms 6i using visual attribute I am using this code
IF :SAL > 4000 THEN
     SET_ITEM_PROPERTY('EMP.SAL',VISUAL_ATTRIBUTE,'VA_COLOR');
END IF;

This code is colored all column, but i want to color only particular cell where i am changing the salary value.

A: maybe you can use SET_ITEM_INSTANCE_PROPERTY
set_item_instance_property('EMP.SAL', current_record, visual_attribute,'VA_COLOR' );


text:
Q: parse data between controller and partialview Hi i want to parse data to my partial view from controller. I get data from database and convert it into List and said list string want to send to partial view so i could do stuff with it ...
    public ActionResult ManipulateData()
    {
        List<string> str = new List<string>();
        DataTable data = LoadDBData();

        foreach (DataRow row in data.Rows)
        {
            foreach (DataColumn Col in data.Columns)
            {
                str.Add(row[Col].ToString());
            }
        }
        return View(str);
    }

this is the code that i have been trying out and now how to acces the str data inside a partial view?
(second idea was to return List with function and somehow call a function and pass data to variable inside view)

A: You can pass data from view to view as far as you want.
Say you have this view:
@model IEnumerable<DataLayer.StructuresList_Result>

@ViewBag.Title

@{
    Html.RenderPartial("_StructureList", Model);
}

As you can see, I have a main view with a model and I'm passing that model directly to the partial view.
You can also create wrappers for your model.
public class Wrapper
{
  public string Name {get;set;}
  public IEnumerable<MyClass> SubClasses {get;set;}
}

public class SubClass
{
  //your subclass code here
}

Then pass this wrapper to your model in the traditional way:
public ActionResult Index()
{
  //get my wrapper object
  Warpper w = new Wrapper();
  return View(w);
{

And then use it in your parent view and pass the SubClass to the partial:
@model YourProjectName.Wrapper

Model.Name

@{
   Html.RenderPartial("_StructureList", Model.SubClasses);
}

Which then you can access that data the same way you access data in your parent view.
@model IEnumerable<string>
@foreach(var item in Model)
{
 //do something with model data
}

I didn't test any of this but it looks right.

Chris is right about one thing, this is pretty basic asp.net MVC stuff here.  I suggest you read some MVC tutorials:
ASP.NET site: http://www.asp.net/mvc
Youtube Videos: https://www.youtube.com/watch?v=-pzwRwYlXMw&list=PL6n9fhu94yhVm6S8I2xd6nYz2ZORd7X2v


text:
Q: flatten array and put child array into an array of object I struggled with a problem for more than an hour, how can I turn this nested array
[
    [
        {
            "name": "1",
        }
    ],
    [
        {
            "name": "a",
        },
        {
            "name": "b",
        }
    ]
]

into this:
[
    {
      name: '1',
    },
    {
      id: 'a-b',
      grouped: [
        {
          name: 'a',

        },
        {
          name: 'b',
        },
      ],
    },
  ]

I don't mind using lodash. Not sure should I flatten it before anything else would make things easier.

A: You could use map() to form the id and grab the parts needed to reconstruct the new array.

const data = [
  [{
    "name": "1",
  }],
  [{
      "name": "a",
    },
    {
      "name": "b",
    }
  ]
];

const result = [
 ...data[0],
 {
   id: data[1].map(r => r.name).join("-"),
   grouped: data[1]
 }
];

console.log(result);

A: to flatten the array is a good start. That will remove the superfluous dimension from the rawArray:
const newArray = array.flat()

Now you have an array with three simple objects. The first will remain unchanged. The second element of your finalArray needs to be an object, so let's create it:
const obj = {}

the obj has two keys: id and grouped. The property of id is a string that we can create like this:
obj.id = newArray[1].name + "-" + newArray[2].name

the property of grouped remains the same:
obj.grouped = array[1]

so the finalArray is now straight forward:
const finalArray = [ newArray[0], obj ]

Put it all together in a function:

const rawArray1 = [
    [
        {
            "name": "1a",
        }
    ],
    [
        {
            "name": "a",
        },
        {
            "name": "b",
        }
    ]
]
const rawArray2 = [
    [
        {
            "name": "1b",
        }
    ],
    [
        {
            "name": "aa",
        },
        {
            "name": "bb",
        }
    ]
]

transformArray( rawArray1 )
transformArray( rawArray2 )
function transformArray( array ){
    const newArray = array.flat()
    const obj = {}
    obj.id = newArray[1].name + "-" + newArray[2].name
    obj.grouped = array[1]
    const finalArray = [ newArray[0], obj ]

    console.log(finalArray)
    return finalArray
}

A: I managed to solve it using simple forEach, push, and flat. It's more simple than I thought, I was confused and stuck with map and reduce.

let result = [];

[
  [{
    "name": "1",
  }],
  [{
      "name": "a",
    },
    {
      "name": "b",
    }
  ]
].forEach((val) => {
  const [{
    name
  }] = val

  if (val.length === 1) {
    result.push({
      name,
    })
  } else if (val.length > 1) {
    result.push({
      id: val.map(val2 => val2.name).join('-'),
      grouped: val
    })
  }
})

console.log(result.flat())

A:

const array1 = [
  [{ name: "1" }],
  [
    { name: "a" },
    { name: "b" }
  ]
]
const array2 = [
  [{ name: "2" }],
  [
    { name: "aa" },
    { name: "bb" },
    { name: "cc" }
  ]
]

transformArray( array1 )
transformArray( array2 )

function transformArray( array ){
  const result = []
    // destructure first array element for the first object:
  const [ nameObj ] = array[0]
  result.push( nameObj )

    // map each object of the second array element into an
    // an array of names, and then join the names together:
  const dataObj   = {}
  dataObj.id      = array[1].map(obj => obj.name).join('-')
  dataObj.grouped = array[1]
  result.push( dataObj )

  console.log( result )
  return result
}


text:
Q: How to call BlockInput in VBS I have found on this site code for VBS to block user input. To simplify, code is:
Sub StopKeyMouse()
    Set Def_DLL = DLL.DefineDLL("USER32")
    Def_Proc = Def_DLL.DefineProc("BlockInput", vt_b1, vt_b1)
    Set Lib = DLL.Load("USER32.DLL", "USER32")
    Lib.BlockInput(True)
End Sub

Sub ResumeKeyMouse()
  Set Def_DLL = DLL.DefineDLL("USER32")
  Def_Proc = Def_DLL.DefineProc("BlockInput", vt_b1, vt_b1)
  Set Lib = DLL.Load("USER32.DLL", "USER32")
  Lib.BlockInput(False)
End Sub

Sub Test()
    StopKeyMouse()

    WScript.Sleep 1000

    ResumeKeyMouse()
End Sub

Test()

When I run it, I get the error Object required: 'DLL'. Since the post is from 2004, I assume that VBS interaction with User32.dll has been changed.
I am missing a line with CreateObject, something like Set DLL = CreateObject("User32.dll").
Does anybody know what is correct code for script to work?
I have also found that it was possible to use
Set oAutoIt = CreateObject("AutoItX.Control")
oAutoIt.BlockInput "on"

But this is obsolete.
Is it possible to call BlockInput from VBS?
Thank you for any help.


text:
Q: Listview go to next item after timer expires I want to change the index of my parent widget which is a Listview.builder after the timer expires. Basically, it would go to the next item of the list.
here is the code from my parent widget:
EDIT I posted the wrong code. Here is the right code for the parent
Widget build(BuildContext context) {
    return Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        color: Colors.black,
        child: Swiper(
          index: widget.inititalIndex,
          itemBuilder: (BuildContext c, int i) {
            return StoriesPerUser(
              storiesList: widget.storiesList,
              selectedIndex: i,
            );
          },
          itemCount: widget.storiesList.length,
          loop: false,
          duration: 1000,
        ));
  }

I am passing the whole List to the ViewStoryModal and the index of the item that the user has selected.
here is the code of ViewStoryModal:
class StoriesPerUser extends StatefulWidget {
  StoriesPerUser({
    @required this.storiesList,
    @required this.selectedIndex,
  });

  final List<Stories> storiesList;
  int selectedIndex;

  _StoriesPerUserState createState() => _StoriesPerUserState();
}

class _StoriesPerUserState extends State<StoriesPerUser> {
  int _index = 0;
  int storiesLength = 0;
  CountDown _countDown;
  StreamSubscription _countDownSubscription;

  @override
  void initState() {
    super.initState();
    this._initTimer();
    print(widget.storiesList.length);
  }

  _initTimer() {
    if (mounted)
      setState(() {
        this._countDown = CountDown(Duration(seconds: 5));
        this._countDown.remainingTime = Duration(seconds: 5);
        this._countDownSubscription = this._countDown.stream.listen(null);
      });

    this._countDownSubscription.onData((d) {
      setState(() {}); // Updates the UI to animate the progress bar
    });

    this._countDownSubscription.onDone(() {
      if (widget.storiesList[widget.selectedIndex].story.length ==
          this._index + 1) {
        setState(() {
          storiesLength++;
        });
        if (widget.storiesList.length == storiesLength) {
          Navigator.of(context).pop();
        } else {
          setState(() {
             //THIS IS WHERE THE UPDATING SHOULD HAPPEN
            //IT SHOWS NEXT ITEM OF MY LISTVIEW BUT DOESN'T CHANGE THE INDEX OF THE ACTUAL LISTVIEW
            widget.selectedIndex++;
            this._index = 0;
            this._initTimer();
          });
        }
      } else {
        if (mounted)
          setState(() {
            this._index++;
            this._initTimer();
          });
      }
    });
  }


text:
Q: In MVC cross domain service call returning undefined function error, but able to see the json object in browser calling an cross domain ajax call with jsonp, but returning undefined function error.
Service side:-
I have one WCF service which returning list of complex items. The function is decorated with
[WebGet(UriTemplate="/Menu/callBackFunctionName",ResponseFormat=WebMessageFormat.Json)]
List<MenuItem> GetMenu();

Client Side:-
From MVC view calling ajax function
   $.ajax({   type:     "GET",
   url:      "https://abc.com/Menu",
   dataType: "jsonp",
   jsonCallback: function GetMenu(data){
   //alert statement 1
   },

   success: function(data){   // alert statement 2   },

   Error: function(){ // alert statement 3}
});

Ajax call the function in the server side, but the response return is undefined, when we used chrome java developer tool json result is there, but function GetMenu is undefined error is showing.
showing  // alert 1
showing // alert 3
Please suggest how i can get response in field data and used in my view.

A: You can open chrome using following code in "RUN" it will disable web security and this might solve your problem
chrome.exe --allow-file-access-from-files --disable-web-security


text:
Q: Using multilist column as foreign key reference I have a table TABLEA that store data in a Columns which are basically multilist columns like this ColumnA ',2562,2563,2564,' and ColumnB with values ',121,122,123,'.
These column are actually foreign key values coming from another table.
Data is something like this in Table A.
ID NAME   ColumnA           ColumnB
1  ITEM1  ,2562,2563,2564,  ,121,122,123
2  ITEM2  NULL              ,6455,545,
3  ITEM3  ,1221,1546,       NULL
4  ITEM4  NULL              NULL

I want to join these columns with there parent tables and extract data.
I am hoping the result set would have 8 rows.
For example
ITEM   ColumnA   ColumB
ITEM1  2562      121
ITEM1  2563      122
ITEM1  2564      123
ITEM2  NULL      6455
ITEM2  NULL      545
....

I have tried this query with some help but this is not working when I try to use ColumnB as well and also it ignores the Items with NULL values.
The Column A is saving Ids of USER_GROUP table but ColumnB is fetching the Ids from some other table lets say GROUP1 and there could be another Column ColumnC that might be storing values from another table so that's kind of situation I am stuck in and hope I have explained so someone can understand but I am open if you want me to improve more
SELECT ug.*
FROM USER_GROUP ug
WHERE EXISTS (SELECT 1
              FROM TableA t1
              WHERE t1.COLUMNA LIKE '%,' || ug.ID || ',%'
             )
AND EXISTS (SELECT 1
              FROM TableA t1
              WHERE t1.COLUMNB LIKE '%,' || ug.ID || ',%'
             );

A: Here's one option:
SQL> with test (id, name, cola, colb) as
  2    (select 1, 'item1', ',2562,2563,2564,', ',121,122,123,' from dual union all
  3     select 2, 'item2', null              , ',6455,545,'    from dual union all
  4     select 3, 'item3', ',1221,1546,'     , null            from dual union all
  5     select 4, 'item4', null              , null            from dual
  6    ),
  7  remcom
  8    -- remove leading and trailing commas
  9  as (select id,
 10        name,
 11        rtrim(ltrim(cola, ','), ',') cola,
 12        rtrim(ltrim(colb, ','), ',') colb
 13      from test
 14     )
 15  select id,
 16    name,
 17    regexp_substr(cola, '[^,]+', 1, column_value) cola,
 18    regexp_substr(colb, '[^,]+', 1, column_value) colb
 19  from remcom r cross join
 20    table(cast(multiset(select level from dual
 21                        connect by level <= regexp_count(nvl(r.cola, r.colb), ',') + 1
 22                       ) as sys.odcinumberlist))
 23  order by id, name, cola, colb;

        ID NAME  COLA       COLB
---------- ----- ---------- ----------
         1 item1 2562       121
         1 item1 2563       122
         1 item1 2564       123
         2 item2            545
         2 item2            6455
         3 item3 1221
         3 item3 1546
         4 item4

8 rows selected.

SQL>

Now that you have it, join this result with another table you have.
By the way, this example nicely shows what it is a bad idea to store multiple values into the same column. Don't do that.

A: You don't need to use (slow) regular expressions and can do it with simple string functions in a recursive sub-query factoring clause:
WITH split_data ( id, name, columna, columnb, starta, enda, startb, endb ) AS (
  SELECT id,
         name,
         columna,
         columnb,
         INSTR(columna,',',1,1),
         INSTR(columna,',',1,2),
         INSTR(columnb,',',1,1),
         INSTR(columnb,',',1,2)
  FROM   test_data
UNION ALL
  SELECT id,
         name,
         columna,
         columnb,
         enda,
         CASE WHEN enda = 0 THEN 0 ELSE INSTR(columna,',',enda+1,1) END,
         endb,
         CASE WHEN endb = 0 THEN 0 ELSE INSTR(columnb,',',endb+1,1) END
  FROM   split_data
  WHERE  enda > 0
  OR     endb > 0
)
SELECT id,
       name,
       CASE
       WHEN starta = 0 THEN NULL
       WHEN enda = 0 THEN SUBSTR( columna, starta + 1 )
       ELSE SUBSTR( columna, starta + 1, enda - starta - 1 )
       END AS valuea,
       CASE
       WHEN startb = 0 THEN NULL
       WHEN endb = 0 THEN SUBSTR( columnb, startb + 1 )
       ELSE SUBSTR( columnb, startb + 1, endb - startb - 1 )
       END as valueb
FROM   split_data
ORDER BY id, starta, startb;

Which for your test data:
CREATE TABLE test_data ( ID, NAME, ColumnA, ColumnB ) AS
SELECT 1, 'ITEM1', ',2562,2563,2564', ',121,122,123' FROM DUAL UNION ALL
SELECT 2, 'ITEM2', NULL,              ',6455,545' FROM DUAL UNION ALL
SELECT 3, 'ITEM3', ',1221,1546',      NULL FROM DUAL UNION ALL
SELECT 4, 'ITEM4', NULL,              NULL FROM DUAL;

Outputs:

ID | NAME  | VALUEA | VALUEB
-: | :---- | :----- | :-----
 1 | ITEM1 | 2562   | 121
 1 | ITEM1 | 2563   | 122
 1 | ITEM1 | 2564   | 123
 2 | ITEM2 | null   | 6455
 2 | ITEM2 | null   | 545
 3 | ITEM3 | 1221   | null
 3 | ITEM3 | 1546   | null
 4 | ITEM4 | null   | null

db<>fiddle here


text:
Q: using sharepoint site from another Domain I have sharepoint site  named sp working on x.local Domain.
x.local now trust with y.local.
users of x.local can using sharepoint whit sp address.
and y.local users , using sharepoint site with address :
sp.x.local
but webpart and list refer address sp without x.local and not shown.

A: There's quite a bit of info missing from this post, but here are some things you need to check:

*

*DNS - can users in y.local resolve sp.x.local?

*Network path - can you get HTTP or HTTPS traffic from x.local to
y.local (ports 80, 443)?

*Authentication - Is your SP configured to allow users from
y.local?
My first port of call would be to use Fiddler from a machine on y.local and try to browse to x.local.   What happens?


text:
Q: Displaying a CSV file using react frontend and flask backend I'm trying to read a csv file using flask and then display it through react (The display part should be compulsorily done through react). I'm stuck at the return part of js file.
This is the flask(.py)code:
from flask import Flask,render_template,request
import os
import pandas as pd

app=Flask(__name__)
app.secret_key="123"

app.config["UPLOAD_FOLDER1"]="static/csv"

@app.route("/upload",methods=['GET','POST'])
def upload():
    return render_template("UploadCsv.html")

@app.route("/display",methods=["GET","POST"])
def display():
    upload_file = request.files['upload_csv']
    if upload_file.filename != '':
            file_path = os.path.join(app.config["UPLOAD_FOLDER1"], upload_file.filename)
            upload_file.save(file_path)
            data=pd.read_csv(file_path,sep=",")
            return render_template("CsvContent.html",data=data.to_html(index=False))

if __name__=='__main__':
    app.run(debug=True)

And here are the two HTMLs used in the .py file above:
UploadCsv.html

        <title>Upload CSV File</title>

            <form method="POST" action="http://127.0.0.1:5000/display" enctype="multipart/form-data">

Upload CSV File

                    Browse CSV File
                    <input type="file" class="form-control" name="upload_csv">

                    <button type="submit" class="btn btn-success btn-block">Upload CSV</button>

            </form>

CsvContent.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>CSV File</title>

Here's your uploaded CSV file :

    {{data|safe}}

This successfully reads and displays the CSV file completely through Flask. Now, here's the catch, I have to integrate react too. And this is where I'm messing up. Here's my React code, if it helps.
 const[csvupload,setCsvUpload] = useState()

useEffect(()=> {

  fetch('http://127.0.0.0:5000/display',{

    'method':'POST',

    headers: {

      'Content-Type' : 'application/json'

    }

  })

  .then(resp => resp.json())

  .then(resp => setCsvUpload(resp))

  .catch(error => console.log(error))

},[])

  return (

    <Fragment>

          Upload Your CSV File

            <Row md={12}>

                <Col md={6} className="body-upload">

                <input type="file" accept=".csv" onChange={handleFileUpload} multiple />

                <button onClick={modalOpen}> UPLOAD </button>

                </Col>
            </Row>

            {csvupload.map(csv =>{

              return(
(**What should be here?**)

              )

            })}

    </Fragment>

  );

};

export default UploadFile;

How can I return the CSV file through react? I am using fetch here, is it even the right method? What should I put inside the return method so that when I upload the csv, it should read the file, store in "static/csv" (as given in the flask code) and display the file below before clicking Upload. I know its a long question, but please help. Any kinda help would be appreciated and I'm willing to provide information required.

A: Few things you can do:

*

*The call you make to /display has no payload being sent. If that is the case, you can change to a GET call

*Parsing the csv directly on the frontend can be resource intensive depending on the content. It would be better for you to parse it on the backend itself and then send the JSON to react that looks like the following (or any other structure based on your needs):

// option1
{
  row1: [col1, col2],
  row2: [col1, col2]
}

// or send an array of rows

// option2
[[col1, col2], [col1, col2]]

*Once you have the parsed csv content you can use it like this on react:

// option 2
{
  csvupload.map((row) => {
    // you can format as per your requirement
    // col1=row[0] and col2=row[1]
    return
{row}
;
  })
}

// option 1
{
  Object.keys(csvupload).map((rowIndex) => {
    // you can format as per your requirement
    // col1=csvupload[rowIndex][0] and col2=csvupload[rowIndex][1]
    return
{csvupload[rowIndex]}
;
  })
}

Personally, I feel option 1 would be better. But you can change this structure based on whatever best fits your requirements.
Edit: based on comment

*

*This answer might help for parsing what to do,

*and the docs for the function used further info in docs

*In option1, Object.keys(csvupload) returns an array of keys. rowIndex is an index of this array. When passed into the csvupload JSON, it returns the column array [col1, col2]

*In option2, row is the array of columns in that specific row [col1, col2] (same as option1)

*Both options give the same result. It's just a difference of how you are accessing the value


text:
Q: How do you get a value between "," in JS (comma) I'm trying to get a value that's between, next or before of a comma.
For example, my string is: "value1,value2,value3,value4", sent to JS through PHP (ajax)
How do I just get value2 and value4 inside the .js file?

A:

    let myString = "value1,value2,value3,value4"
    myString.split(',')
  console.log(myString.split(','))

A:

let szResult = "val1,val2,val3,val4";
let arr = szResult.split(',');
console.log(arr[1]); // val2
console.log(arr[3]); // val4

A: Use split() function like that:
var arr = yourString.split(",")
// value2
return arr[1]
// value 3
return arr[3]

It's pretty simple, I don't think it is really issue for the question here, sorry.


text:
Q: How to add AdMob to the endscreen? How can I ad Admob to the GameOver Screen?
I searched a lot but I didn`t found very much!
My MainActivity:
 public class MainActivity extends Activity {

    private GameView gView;

        @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    gView = new GameView(this);
    setContentView(gView);
    }
  }

and my GameView:
public class GameView extends SurfaceView {

      private boolean gameOver;

    public GameView(Context context) {
        super(context);
        gameOver = false;
      }

       @Override
    protected void onDraw(Canvas canvas) {
      if(!gameOver)
        {
          drawGame(canvas);
        }
        else
        {
          //add Admob Banner here to the Screen
          drawGameOver(canvas);
        }

      }

     public void drawGame(Canvas can){
       }

      public void drawGameOver(Canvas can){
        }

    }

My whole game is drawn on the canvas. But I want only schow AdMob at the GameOver screen.
How can I show it there?
I found something here:
Interstitial ad with admob at gameOverScene
but I don't think its  a solution for me. Or how can I implement this to my code?
thanks a lot for your help!

A: You'll need to create an AdView into your main_activity.xml like:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

</RelativeLayout>

Then try this following code:
public class MainActivity extends Activity {

    private GameView gView;
    private AdView mAdView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View _view = getLayoutInflater().inflate(R.layout.main_activity, null);

        mAdView = (AdView) _view.findViewById(R.id.adView);

        gView = new GameView(this);

        setContentView(gView);

    }

    public void showBanner(){

        AdRequest _adRequest = new AdRequest.Builder().build();

        mAdView.loadAd(_adRequest);

    }

}

public class GameView extends SurfaceView {

    private boolean gameOver;
    private Activity mActivity;

    public GameView(Activity activity) {
        super(activity);

        gameOver = false;

    }

    @Override
    protected void onDraw(Canvas canvas) {

        if(!gameOver){

            drawGame(canvas);

        }
        else
        {

            //add Admob here to the Screen
            drawGameOver(canvas);

        }

    }

    public void drawGame(Canvas can){

    }

    public void drawGameOver(Canvas can){

        mActivity.showBanner();

    }

}

For more information, take a look this link: https://developers.google.com/mobile-ads-sdk/docs/admob/android/quick-start

A: You can add banner ads programmatically and show or hide them in your game's screens via a listener. Modify your code as follows, make sure you replace "yourAdUnitId" with your real adUnit Id
public class MainActivity extends Activity implements MyAdListener{
private GameView gView;
AdView adView;
    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
 gView = new GameView(this);

AdSize adSize = AdSize.SMART_BANNER;

    DisplayMetrics dm = getResources().getDisplayMetrics();

    double density = dm.density * 160;
    double x = Math.pow(dm.widthPixels / density, 2);
    double y = Math.pow(dm.heightPixels / density, 2);
    double screenInches = Math.sqrt(x + y);

    if (screenInches > 8) { // > 728 X 90
        adSize = AdSize.LEADERBOARD;
    } else if (screenInches > 6) { // > 468 X 60
        adSize = AdSize.MEDIUM_RECTANGLE;
    } else { // > 320 X 50
        adSize = AdSize.BANNER;
    }
    adView = new AdView(this);
     adView.setAdUnitId("yourAdUnitId");
     adView.setAdSize(adSize);
     adView.setVisibility(View.INVISIBLE);
     adView.setBackgroundColor(Color.TRANSPARENT)
    AdRequest adRequest = new AdRequest.Builder().build();
     adView.loadAd(adRequest);
    RelativeLayout.LayoutParams adViewParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    adViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL | RelativeLayout.ALIGN_PARENT_TOP);
    RelativeLayout layout = new RelativeLayout(this);
    layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT));
    layout.addView(gView);
    layout.addView(adView, adViewParams);
    setContentView(layout);
}

@Override
  public void showBannerAd() {
   runOnUiThread(new Runnable() {
   @Override
   public void run(){
    adView.setVisibility(View.VISIBLE);
    }
  });
}
  }

public class GameView extends SurfaceView {

private boolean gameOver;
private Activity mActivity;

public GameView(Activity activity) {
    super(activity);
    myAdListener = (MyAdListener)activity;
    gameOver = false;

}

@Override
protected void onDraw(Canvas canvas) {

    if(!gameOver){

        drawGame(canvas);

    }
    else
    {

        //show admob
       myAdListener.showBannerAd();
        drawGameOver(canvas);

    }

}

public void drawGame(Canvas can){

}

public void drawGameOver(Canvas can){

}

public interface MyAdListener{
public void showBannerAd();
}

}


text:
Q: How can we find out the deleted record in After delete trigger? I am writing a trigger to handle after insert,after update and after delete events.
I am using trigger.old for after delete.But, how to differentiate the deleted record from the rest of the records of the object?
What I have done so far is :
List<Object__c) lstTriggerOld = trigger.old;
List<Object__c> lstAllRecords = [SELECT Id FROM Object__c WHERE ID != NULL];
List<Object__c> deletedRecords = [SELECT Id FROM Object__c WHERE ID IN :lstTriggerOld AND ID NOT IN : lstAllRecords ];

But the last list is not fetching any rows.
Can someone help?

A: To get or Query deleted records you need to use ALL ROWS So your query will be
List<Object__c> deletedRecords = [SELECT Id FROM Object__c WHERE ID IN :lstTriggerOld AND ID NOT IN : lstAllRecords  ALL ROWS];
All Rows Keyword


text:
Q: GraphQL query works in Gatsby page but not inside class component There have been a couple of similar questions, but none helped me really understand using a GraphQL inside a (class) component other than the ones in the pages folder.
My project structure looks like that:
-src
--components
---aboutBody
----index.js
--pages
---about.js

I have a page component called about (Prismic single page type) and set up some components to "fill" this page (cleaned up for better readability).
class AboutPage extends Component {

  render() {
    return (
        <LayoutDefault>
          <AboutBody
            introHeadline={this.props.data.prismicAbout.data.intro_headline.text}
            introParagraph={this.props.data.prismicAbout.data.intro_paragraph.text}
          />
        </LayoutDefault>
    )
  }

}

export default AboutPage

This is what my query looks like (had it like this in both files):
export const aboutQuery = graphql`
  query About {
    prismicAbout {
      data {

        # Intro Block
        intro_headline {
          text
        }
        intro_paragraph {
          text
        }
      }
    }
  }
`

(In case I am missing a bracket at the bottom, it's due to cleaning up the query example for SO — as mentioned earlier, it's working in my page component).
My graphql query is at the bottom of the AboutPage page component. It works like a charm and as intended.
But to clean this page up a bit I wanted to create appropriate components and put my query inside each component (e.g. aboutBody, aboutCarousel), again cleaned up a bit:
class AboutBody extends Component {

  render() {

    return (

    )
  }

}

export default AboutBody

And I deleted the query from my about page component and put it inside my AboutBody component (exactly the way as shown above).
But with this it always returns the error Cannot read property 'prismicAbout' of undefined (I can't even console log the data, it always returns the same error).
I used import { graphql } from "gatsby" in both files.
Long story short, how can I achieve putting a query inside my class component and render only the component without clarifying the props in my page component like this:
class AboutPage extends Component {

  render() {
    return (
        <LayoutDefault>
          <AboutBody />
        </LayoutDefault>
    )
  }

}

Some blogs posts mention GraphQL Query Fragments, but not sure if this is the correct use case or if it's simply a stupid beginner mistake...

A: That's because you can't use graphql like this in your component.
To use graphql in a component, you've got two options : useStaticQuery function or StaticQuery component, both from graphql
for useStaticQuery :
import React from "react"
import { useStaticQuery, graphql } from "gatsby"

const MyElement = () => {
  const data = useStaticQuery(graphql`
     query About {
       prismicAbout {
         data {
           intro_headline {
             text
           }
           intro_paragraph {
             text
           }
         }
       }
     }
   `)

   return (

   )
}

export default MyElement

with staticQuery
import React from 'react'
import { StaticQuery, graphql } from 'gatsby';

const MyElement = () => {
   return(
      <StaticQuery
            query About {
              prismicAbout {
                data {
                   intro_headline {
                       text
                       }
                       intro_paragraph {
                          text
                       }
                   }
                }
             }
         `}
         render={data => (

         )}
      />
   )
}

export default MyElement

Hope that helps you!

A: You can only use a query like that in a page component. One option would be to just query it in the page and then pass the data in to your component as a prop. Another is to use a static query in the component.
If your query has variables in it then you can't use a static query. In that case you should either query it all in the page and then pass it in, or you can put the part of the query related to that component in a fragment within that component's file and then use that fragment in the page query.
Example of using fragments in a component and then passing the data into the component:
// MyComponent.js
import React from "react"
import { graphql } from 'gatsby'

const MyComponent = (props) => {

  const { myProp: { someData } }  = props

  return (

        my awesome component

  )
}

export default MyComponent

export const query = graphql`
  fragment MyAwesomeFragment on Site {
     someData {
         item
     }
  }
`

// MyPage.js
import React from "react"
import { graphql } from "gatsby"

import MyComponent from "../components/MyComponent"

export default ({ data }) => {
  return (

      {/*
        You can pass all the data from the fragment
        back to the component that defined it
      */}
      <MyComponent myProp={data.site.someData} />

  )
}
export const query = graphql`
  query {
    site {
      ...MyAwesomeFragment
    }
  }
`

Read more about using fragments in Gatsby docs.

A: If you need to render the query in a class based component. This worked for me:
import React, { Component } from 'react';
import { StaticQuery, graphql } from 'gatsby';

class Layout extends Component {
  render() {
    return (
      <StaticQuery
        query={graphql`
          query SiteTitleQuery {
            site {
              siteMetadata {
                title
              }
            }
          }
        `}
        render={data => {
          return (

              {!data &&
Loading...
}
              {data && data.site.siteMetadata.title}

          )
        }}
      />
    );
  }
}


text:
Q: What is the purpose of empty "remotes" folders in the .git folder? There are empty folders in myrepo/.git/refs/remotes. What is their purpose?
They seem to map to past used remote names. If so, what would be the affect of deleting them?
If I do not delete them, what would be the affect to adding a remote with the same name as one of the folders? Would that cause any problems?

A: The ProGit on "Git Internals" mentions:

If you add a remote and push to it, Git stores the value you last pushed to that remote for each branch in the refs/remotes directory.
For instance, you can add a remote called origin and push your master branch to it:

$ git remote add origin git@github.com:schacon/simplegit-progit.git
$ git push origin master
Counting objects: 11, done.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (7/7), 716 bytes, done.
Total 7 (delta 2), reused 4 (delta 1)
To git@github.com:schacon/simplegit-progit.git
   a11bef0..ca82a6d  master -> master

Then, you can see what the master branch on the origin remote was the last time you communicated with the server, by checking the refs/remotes/origin/master file:

$ cat .git/refs/remotes/origin/master
ca82a6dff817ec66f44342007202690a93763949

Remote references differ from branches (refs/heads references) mainly in that they can't be checked out.
Git moves them around as bookmarks to the last known state of where those branches were on those servers.

I wouldn't recommend adding any subfolder in what is the internal structure of the git database, but removing its content should be safe (it would only means the next git fetch would refetch everything from the declared remotes).
As the Pro-Git chapter on the refspecs mentions:

In the default case that is automatically written by a git remote add command, Git fetches all the references under refs/heads/ on the server and writes them to refs/remotes/origin/ locally.
So, if there is a master branch on the server, you can access the log of that branch locally via:

$ git log origin/master
$ git log remotes/origin/master
$ git log refs/remotes/origin/master

They're all equivalent, because Git expands each of them to refs/remotes/origin/master.


text:
Q: Calling an API with a websocket I have a very simple application that consists of a frontend written in AngularJS and a API written using the Django Rest Framework. My application polls every x seconds an API endpoint to see if there have been new changes.
This codes gets run every 5 seconds
var resource = TokenRestangular.one("jobs", job_id);
resource.then(function (objects) {
    //if we have job completed = true then do something else.
},

I understand this is a very old school way. So my question is, can I use websockets to lookup the API resource in AngularJS if so how?
I don't want to have to rewrite a new API so can the API support both REST connections and websockets over HTTP?

A: 1. Client side
Write a service in your angular code that will create a connection to a websocket server. Using a promise, you will then update the $scope of you application each time a websocket packet is received. Something like this:
    myApp.service( 'WSService', function() {
        this.promise = function ($q) {
            // Create a deferred object
            var deferred = $q.defer();
            // Create the WebSocket client pointing to the correct API
            var ws = new WebSocket("ws://myIP:myPort/myAPI");
            // Map the messages to action
            ws.onopen = function()  { console.log( "WSService opened"); };
            ws.onmessage = function (evt) {
                console.log("onmessage:" + evt);
                deferred.notify(evt);
            };
            ws.onclose = function() { console.log("WSService closed"); };
            // Return the promise
            return deferred.promise;
        }
    });

then in your controller:
    myApp.controller('MyController', ['$scope','$q','WSService', function($scope, $q, WSService) {
        var promise = WSService.promise($q);

        promise.then(function(evt) { console.log('resolve : ' + evt); },
                     function(evt) { console.log('reject : ' + evt); },
                     function(evt) {
                         console.log('notify: ' + evt);
                         //Update the scope
                         $scope.myData = evt;
                     }
        );
    }]);

2. Server side
In front of the API, write a websocket server which will push JSON data with the appropriate format. For example, you can hook to your model signals (save, update) a function that will push the JSON serialization of you model to the client. This way, all updates to your back-end DB will immediately reflect to the client side.
For this, you can use a pre-made package like django-socketio which seems to be quite popular.
If the data sent by your websocket server match the data in your model and scope, it can qualify to the REST label I guess.


text:
Q: Ideas about how to create a splash screen using PyGObject? Any ideas about how to create a splash screen for my application using Python3 and PyGObject ?
For example : Like the GIMP's slpash screen.
In my case, i used time.sleep(...) and it makes my application start very slowly. I'm wondering if should i thread the slpash screen Gui.
I've searched in websites and i didn't find any solution.
Thanks for your answers. And sorry for my bad english.

A: *

*create a window

*will it with your content

*open it

*force it to show

*set a timeout to close said window at a later time

*proceed with initialisation

There are examples out there, e.g. http://code.activestate.com/recipes/577919-splash-screen-gtk/


text:
Q: How to convert an HTML table to an array in python I have an html document, and I want to pull the tables out of this document and return them as arrays.  I'm picturing 2 functions, one that finds all the html tables in a document, and a second one that turns html tables into 2-dimensional arrays.
Something like this:
htmltables = get_tables(htmldocument)
for table in htmltables:
    array=make_array(table)

There's 2 catches:
1.  The number tables varies day to day
2. The tables have all kinds of weird extra formatting, like bold and blink tags, randomly thrown in.
Thanks!

A: Use BeautifulSoup (I recommend 3.0.8).  Finding all tables is trivial:
import BeautifulSoup

def get_tables(htmldoc):
    soup = BeautifulSoup.BeautifulSoup(htmldoc)
    return soup.findAll('table')

However, in Python, an array is 1-dimensional and constrained to pretty elementary types as items (integers, floats, that elementary).  So there's no way to squeeze an HTML table in a Python array.
Maybe you mean a Python list instead?  That's also 1-dimensional, but anything can be an item, so you could have a list of lists (one sublist per tr tag, I imagine, containing one item per td tag).
That would give:
def makelist(table):
  result = []
  allrows = table.findAll('tr')
  for row in allrows:
    result.append([])
    allcols = row.findAll('td')
    for col in allcols:
      thestrings = [unicode(s) for s in col.findAll(text=True)]
      thetext = ''.join(thestrings)
      result[-1].append(thetext)
  return result

This may not yet be quite what you want (doesn't skip HTML comments, the items of the sublists are unicode strings and not byte strings, etc) but it should be easy to adjust.

A: Pandas can extract all of the tables in your html to a list of dataframes right out of the box, saving you from having to parse the page yourself (reinventing the wheel). A DataFrame is a powerful type of 2-dimensional array.
I recommend continuing to work with the data via Pandas since it's a great tool, but you can also convert to other formats if you prefer (list, dictionary, csv file, etc.).
Example
"""Extract all tables from an html file, printing and saving each to csv file."""

import pandas as pd

df_list = pd.read_html('my_file.html')

for i, df in enumerate(df_list):
    print df
    df.to_csv('table {}.csv'.format(i))

Getting the html content directly from the web instead of from a file would only require a slight modification:
import requests

html = requests.get('my_url').content
df_list = pd.read_html(html)

A: A +1 to the question-asker and another to the god of Python.
Wanted to try this example using lxml and CSS selectors.
Yes, this is mostly the same as Alex's example:
import lxml.html
markup = lxml.html.fromstring('''\

        0,0,0
        0,0,1

        0,1,0
        0,1,1

        1,0,0
        1,<blink>0,</blink>1
        1,0,2
        <bold>1</bold>,0,3

''')

tbl = []
rows = markup.cssselect("tr")
for row in rows:
  tbl.append(list())
  for td in row.cssselect("td"):
    tbl[-1].append(unicode(td.text_content()))

pprint(tbl)
#[[u'0,0,0', u'0,0,1'],
# [u'0,1,0', u'0,1,1'],
# [u'1,0,0', u'1,0,1', u'1,0,2', u'1,0,3']]


text:
Q: Jackson 2.x single-quote handling I need to use the Jackson parser to handle json that contains non-standard single quotes instead of double quotes. This question has been asked before:
Configure Jackson to deserialize single quoted (invalid) JSON
but the "JsonParser" class no longer exists in Jackson 2.0+. It looks like the newer way to configure the ObjectMapper is like this:
mapper.enable(DeserializationFeature.FEATURE_NAME_HERE);

but I can't find an ALLOW_SINGLE_QUOTES feature. Maybe I'm just not seeing it.
How do I deserialize single quotes in Jackson 2.x?
EDIT
OOPS, never mind. JsonParser does exist. In my project it was being shadowed by the Json Smart class with the same name.

A: Try mapper.getFactory().enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)


text:
Q: which is the best practice using joi or express-validtor as validation or using validtion on the Schema level like in mongodb? i am confused between using validation on the server-side or on the schema level in mongodb,
i tried validation using mongodb and it worked well and tried the server-side validation but my question which is better from preformance side and as a best practice.


text:
Q: Change size of standard resize handle (CSS)? The resize handle/icon on Chrome for Android (at least on my device) is too small. I can't resize without extreme zoom.
The suggested duplicates addresses the styling and one answer succussefully styles the bottom right corner but the resizing still need me to target the original resizer, which is still too small.
[missing image]
Problem is present in this example as well: https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_resize
Is there a way to change the size of it? On my laptop it's a little bit too intrusive/big instead
I tried using ::-webkit-resizer but it doesn't seem to work.
<!DOCTYPE html>

The resize Property

Let the user resize both the height and the width of this div element.

To resize: Click and drag the bottom right corner of this div element.


text:
Q: How to get month name for a given year and week in Javascript I have 2 form fields in HTML namely Year and Week.
Once the user selects a Year and a week from the dropdowns, I want to display the month Name for the selected year and week.
Can anyone help me to get month name based on year and iso week numbers.
For example: If I selected year as 2022 and week no as 16, then the expected output is April as a month name.
This shoud be a function that returns the month name for a given year and week.
Below is my sampke code.
getMonthName() {
    const year  =  2022;
    const week  = 16;
    console.log(month);
  }

A: Example: https://codesandbox.io/s/damp-wood-nynj7f?file=/src/app/app.component.ts

*

*Create mapper for your months:

*4 weeks = 1 month, then get input value of week covert to number and divide 4. (Example: 16 / 4 === 4)

*The result is a key of your mapper: months[divided result]

The best is a using Date libraries such as: dayjs, date-fns, moment, luxon or other.
const months = {
    1: "January",
    2: "February"
}

changeWeekHandler(e) {
   const week = parseInt(e.target.value)
   const month = Math.ceil(week / 4) // for round number to the upper (example: Math.ceil(0.25) -> 1)
   this[your input field] = months[month]
}

A: Really interesting form. I came up with a solution like this;
I do not suggest you divide by 4 weeks per month because not all months have 4 weeks.
But from your input, you always can know the day of year from a number of weeks
numberOfWeek * 7 = numberOfDay
create a method :
const dateFromDay = (year, day = 1) => {
  const date = new Date(year, 0);
  return new Date(date.setDate(day));
}

// call the method with your inputs

const myDate = edateFromDay(2022,16*7);
// here you will have the full date

// if you want just the month then
myDate.getMonth();

For exact your need :
//Declare months
  const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
// Declare method for receiving your month name
const dateFromWeek = (year, week = 1) => {

  const date = new Date(year, 0);
  return monthNames[new Date(date.setDate(week*7)).getMonth()];
}
//When you use
dateFromWekk(2020,3); //just write year and week, you will get the name of month

A: The following will display the month name (short form) for the given ISO week number and year.

function getMonthName(week, year) {
let d =new Date(year,0,1+(week-1)*7);
d.getUTCDay()<5?d.setUTCDate(d.getUTCDate()-d.getUTCDay()+1):d.setUTCDate(d.getUTCDate()+8-d.getUTCDay());
return (""+d).split(" ")[1];
}

console.log(getMonthName(1,2022));
console.log(getMonthName(11,2022));
console.log(getMonthName(16,2022));


text:
Q: sql как обновить таблицу а именно убрать пробел между словами в этом поле Допустим есть такой столбец = '76 ОСКИ'
и необходимо обновить таблицу чтобы исчез пробел между 76 и ОСКИ явно не указывая номер 76 !
Номера в таблице меняются и необходимо автоматизировать удаление пробельного символа.
update temp_table_xxx
set "Склад_1С" = '96ОСКИ'
where "Склад_1С" like '96 ОСКИ';


text:
Q: How to create a python decorator programatically I am writing an app that creates/provides various Python decorators.  I'd like this app to be localized, including the names of the decorators.  The decorators would ultimately be used by other developers who are using my app as a framework (think of my app as a test framework).
Ideally, I'd like to have the ability to create the decorators dynamically based on the localization settings.
For instance, if the language selected is English, I'd like my decorator to be named "apple", and if it's French, I'd like it to be named "pomme".
In the Python code, it would either look like:
@apple
def my_func():
    pass

or
@pomme
def my_func():
    pass

I ultimately want to have the flexibility to add many more languages without having to modify or duplicate a bunch of code.  Ideally, I would only have one decorator function that would handle "apple" or "pomme" depending on the settings.
What's the best way to achieve this?

A: First, don't do this. This will bring many problems upon you and make life much harder for you and your users. Anyway, python is very dynamic so you can do that.
Setup your package like that:
yourpackage/
    __init__.py
    decorators.py

In decorators.py:
# List all decorators you want to publish. Use english names here.
__all__ = ['apple', 'orange', ...]

# Here come implementations named in english
def apple(...):
    ...

...

In __init__.py:
# Whatever over submodules export or just []
__all__ = [...]

from . import decorators

# Get locale somehow
LOCALE = ...

# This translation function could be as complex as you wish
# I use a lookup in hard-coded dict
TRANSLATIONS = {
    'fr': {'apple': u'pomme', ...},
    ...
}
def _translate_name(name):
    # If something is not translated we use default english name,
    # could be easily changed to raise error
    return TRANSLATIONS.get(LOCALE, {}).get(name, name)

# Generate dynamic attributes to current module and add them to __all__
import sys
this_module = sys.modules[__name__]

for name in decorators.__all__:
    translated = _translate_name(name)
    setattr(this_module, translated, getattr(decorators, name))
    __all__.append(translated)

Managing __all__ in __init__.py is optional. This is to allow from yourmodule import *.


text:
Q: If WPF binding path value is not valid, XAML code does not generate error I have the following XAML and code-behind:
<TextBlock Text="{Binding _word}"
...

public class Word
{
    public string _word { get; set; }
    ...
}

Above works fine.  But when I change _word to another name in the code-behind file, but do not make the corresponding change in the XAML file, I do not get a compile or runtime error.  The only clue is that the value in the TextBlock is not populated.
Is there something in WPF that will catch such errors?
Using Windows 7, Visual Studio 2010 Ultimate Edition.


text:
Q: How to pass a escaped string variable in Jinja 2 Templates Its a simple task
i want to pass on the color eg: "rgb(255,255,0)" to the html file so that the text color can be changed.
I used this snippet in the html file
``{% for i in range(0,len) %}
new mapboxgl.Marker({
    color: {{ colors[i]|safe }}
    }).setLngLat([
        {{ lang[i] }},
        {{ lat[i] }}])
    .addTo(map);

    {%endfor%}

i am passing the colors list by:
colors=[]
maxValue = max(totalConfimedList)
for item in totalConfimedList:
    print(item)
    # colors.append(code_map(int(item),0,int(maxValue),0,255))
    if int(item) >255:
        colors.append("\'rgb(255,0,0)")
        continue
    colors.append("\"rgb("+item+"0,0)\"")

In HTML IN CHROME it is coming as color: "rgb(200,0)"
The color is not coming. Please help me

A: colors = []
totalConfimedList = ['123', '255', '256', '375', '367']
maxValue = max(totalConfimedList)
for item in totalConfimedList:
    print(item)
    # colors.append(code_map(int(item),0,int(maxValue),0,255))
    if int(item) > 255:
        colors.append('rgb(255,0,0)')
        continue
    colors.append('rgb('+item+',0,0)')

jinja 2 template:-
{% for i in colors %}
color: [{{ i|safe }}]
{%endfor%}


text:
Q: Using prototype to add method giving error undefined method I'm trying to add a method via prototype but getting an error. Any idea what is going wrong?
function Graph() {
  // Code
}

Graph.prototype.render = function() {
  // Code
}

var test_graph = new Graph;
test_graph.render(); // Returns error that function Graph.render isn't defined.


text:
Q: Ubuntu VirtualBox SSH between two machines Permission Denied (Public key, Password) I have 2 Ubuntu virtual machines on same network with Internal network cards. Both machines can ping each other. both have port TCP/22 open for ssh. I can't SSH either one from each other. Error I get is permission denied (Public key, Password). When I turn password authentication off and even when I turn PasswordProtection, PubKeyAuthentication, RSA Authentication to 'NO', I get permission denied () error.
Transferring keys get the same error.


text:
Q: Eclipse - compile and run with different Java version I want to build my code with Java 6, but use compile time checks of Java 5.
For example, I want the compiler to complain about @Override annotation for interfaces (introduced in Java 6).
Do you know how to do this?

A: go with right mouse button on your project->properties->java compiler
ther you can enable "Enable project specific settings" and choose an own compiler java version

A: The JRE preference seems to be at the workspace not project level. To change the JRE, Window...Preferences. Open up the tree under 'Java'. Choose "Installed JREs". If there's only one there, you can't remove it. Click 'Add...'. Browse to the base directory of the Java installation, e.g. /usr/java/jdk1.6.0. Give the JRE a name and click OK. This adds the new JRE to the list of JREs available. To select it as the default JRE, it must be checked in the Installed JREs window.

A: If you are using Maven (or Ant) for building your project, then you can specify Java 6 in Maven and keep eclipse using Java 5.


text:
Q: mathematics beamer problem I removed slides that worked, checked that they compiled properly and include here all the slides that didn't work (checked individually as well).
\documentclass[17pt]{beamer}
\usepackage{amsmath}
\usepackage{verbatim}
\usepackage[utf8]{inputenc}
\usepackage[OT1]{fontenc}
\usepackage{graphicx}
\usebackgroundtemplate

\begin{document}
\sffamily \bfseries

\begin{frame}
\frametitle{Limit of a Rational Polynomial Function}\pause
begin{itemize}
\item Let us find $\lim_{x \to \2} \frac {3x^{2}-x-10} {x^{2}-4}$
\end{itemize}
\end{frame}

\begin{frame}
\frametitle{Limit of a Rational Polynomial Function}\pause
begin{itemize}
\item To understand limits of functions
\end{itemize}
$\lim_{x \to \2} \frac {3x^{2}-x-10} {x^{2}-4} = 2.75$
\end{frame}

\begin{frame}
\frametitle{Limit of a Discontinuous Function}\pause
Let us find $\lim_{x \to \0} f(x) = \[   \left\{
\begin{array}{11}
          $(2x+3) & x \leq 0$ \\
          $3(x+1) & x $>$ 0$ \\
          \end{array}
          \right. \]
and $\lim_{x \to \1} f(x) = \[   \left\{
\begin{array}{11}
          $(2x+3) & x \leq 0$ \\
          $3(x+1) & x $>$ 0$ \\
          \end{array}
          \right. \]
\end{frame}

\begin{frame}
\frametitle{Limit of a Discontinuous Function}\pause
Let us find $\lim_{x \to \0} f(x) = \[   \left\{
\begin{array}{11}
          $(2x+3) & x \leq 0$ = 3 \\
          $3(x+1) & x $>$ 0$ \\
          \end{array}
          \right. \]
and $\lim_{x \to \1} f(x) = \[   \left\{
\begin{array}{11}
          $(2x+3) & x \leq 0$ = 6 \\
          $3(x+1) & x $>$ 0$ \\
          \end{array}
          \right. \]
\end{frame}

\begin{frame}
\frametitle{Assignment}\pause
\begin{itemize} [<+-|alert@+>]
\item Find $\lim_{x \to \2} (x^{3}-2x^{2})/(x^{2}-5x+6)$
\item Evaluate $\lim_{x \to \0} \frac {sin 4x} {sin 2x}$
\end{itemize}
\end{frame}

\end{document}

A: Some of the errors:

*

*begin{itemize} -> \begin{itemize}

*\2 -> 2, same for \1 and \0

*as David Carlisle already said in his comment, array is already in math mode, you don't need to use $...$.

*the alignment of the array should be ll not 11

*don't nest display math environments (\[...\]) inside math mode

*sin should be \sin

*\usepackage{graphicx} and \usebackgroundtemplate are superfluous

*not a tex error as such, but (2x+3) x≤0=6 looks misleading. Also cases may be better suited as an array

\documentclass[17pt]{beamer}
\usepackage{amsmath}
\usepackage{verbatim}
\usepackage[utf8]{inputenc}
\usepackage[OT1]{fontenc}
\usepackage{graphicx}
\usebackgroundtemplate

\begin{document}
\sffamily \bfseries

\begin{frame}
\frametitle{Limit of a Rational Polynomial Function}\pause
\begin{itemize}
\item Let us find $\lim_{x \to 2} \frac {3x^{2}-x-10} {x^{2}-4}$
\end{itemize}
\end{frame}

\begin{frame}
\frametitle{Limit of a Rational Polynomial Function}\pause
\begin{itemize}
\item To understand limits of functions
\end{itemize}
$\lim_{x \to 2} \frac {3x^{2}-x-10} {x^{2}-4} = 2.75$
\end{frame}

\begin{frame}
\frametitle{Limit of a Discontinuous Function}\pause
Let us find \[\lim_{x \to 0} f(x) = \left\{
\begin{array}{ll}
          (2x+3) & x \leq 0 \\
          3(x+1) & x > 0 \\
          \end{array}
          \right. \]
and \[\lim_{x \to 1} f(x) = \left\{
\begin{array}{ll}
          (2x+3) & x \leq 0 \\
          3(x+1) & x > 0 \\
          \end{array}
          \right. \]
\end{frame}

\begin{frame}
\frametitle{Limit of a Discontinuous Function}\pause
Let us find \[\lim_{x \to 0} f(x) = \left\{
\begin{array}{ll}
          (2x+3) & x \leq 0 = 3 \\
          3(x+1) & x > 0 \\
          \end{array}
          \right. \]
and \[\lim_{x \to 1} f(x) = \left\{
\begin{array}{ll}
          (2x+3) & x \leq 0 = 6 \\
          3(x+1) & x > 0 \\
          \end{array}
          \right. \]
\end{frame}

\begin{frame}
\frametitle{Assignment}\pause
\begin{itemize} [<+-|alert@+>]
\item Find $\lim_{x \to 2} (x^{3}-2x^{2})/(x^{2}-5x+6)$
\item Evaluate $\lim_{x \to 0} \frac {\sin 4x} {\sin 2x}$
\end{itemize}
\end{frame}

\end{document}


text:
Q: Move domain name of Heroku to another Heroku app Right now I have configured an APP to use a domain name that I own.  However, I have created another app in Heroku and I would like that one to use that domain name.
What would be the correct way to do that change? Do I have to remove it from the old Heroku and create it for the new one, or there is a way to "move" it?
Thanks

A: You can ask heroku support to transfer for you, but removing and adding is the fastest way.


text:
Q: Strapi v3 deep sort Let's say I have modelA with a ForeignKey on modelB.
In api/modelA/services/modelA.js, I can define:
// [...]
module.exports = {
  /**
   * Promise to fetch all records
   *
   * @return {Promise}
   */
  find (params, populate) {
    params = {
      ...params,

      _sort: 'field_from_model_a:DESC,other_field_model_a:ASC'
    }
    populate = [
      'modelB'
    ]
    return strapi.query('post').find(params, populate)
  },
// [...]

This allows me to sort my query and I can also filter deep relations when using
curl -X GET "http://localhost:1337/modelA?modelB.field_from_model_b=example_value
But I can't find how to sort on modelB.some_field.
If I write _sort: 'modelB.field_model_b:ASC', I get an error saying: missing FROM-clause entry for table "modelB"

A: deep sorting is available from Strapi v3.4.2 onwards have a look
Strapi release v3.4.2

A: Indeed, since Strapi release v3.4.2, it appears you can deep sort your queries. Yay !
You can find an example in the tests here of the strapi project.
Here is the syntax (as expected in my initial question):
{
  // ...
  _sort: 'modelB.field_model_b:ASC'
}


text:
Q: Insert unix timestamp to postgres timestamp column (node-postgres) I'm using node-postgres module and node 13.5. I'm trying to insert a unix timestamp to postgres timestmap column and it seems to work in dbeaver but when I run the code it doesn't work.
CREATE TABLE public.test (
    column1 timestamp NULL
);

In dbeaver when I run my insert:
insert into test (column1 ) values ( $1 )

It opens up a dialog I type in my param as: to_timestamp(1) I hit ok and it inserts to my table without problem.
But when I use this code:
pool.query("INSERT INTO test (column1) VALUES ($1)", ["to_timestamp(1)"]);

I get an error:
error: invalid input syntax for type timestamp: "to_timestamp(1)"

the query method is the one from the module.
Also if I run like this:
pool.query("INSERT INTO test (column1) VALUES (to_timestamp(1))", []);

It works.
It seems like the nodejs driver doing something different from the dbeaver driver. Am I doing this wrong? Is there a way to to approach this problem? I'd like to use prepared statement if possible.
The things I can't change:

*

*my data is in unix timestamp

*the column must have timestamp type

Any help appreciated.

A: My college helped me:
pool.query("INSERT INTO test (column1) VALUES to_timestamp($1)", ["1"]);

This is the working solution!


text:
Q: How to select/delete until end of file in vim/gvim? Accidentally I managed to copy-paste a paragraph in vim a zillion times.
How do I select and then delete the text from my current position to the end of file?
In Windows, this would be Ctrl-Shift-End, followed by Delete.

A: d is delete and G moves to the end of the file, so dG will delete to the end of the file. It includes the entire current line though; if you're mid-line and want to preserve everything before the current position you need to use Mark's method

A: You could also just type u to undo the changes that resulted in the errant copy-paste.

A: VGx

Enter Visual Mode, go to End of File, delete.
Alternatively, you can do:
Vggx

To delete from the current position to the beginning of the file.

A: vGx

works fine for multi line selection(in this case paragraph), but if you want to select within one single line it acts mysteriously(selects from cursor till beginning of the line).
In case of selection within Single line you have to use:
v$x

Which enters to Visual mode("v") and goes to end of line("$") and deletes("x") from current position until end of line.

A: Yet another method: :.,$d
That means in ex mode, address current line to end, and delete.

A: Vggx didn't work for me, but vG$d did. vG$ selects to EOF (last character of last line), then whatever command you want to executed.
=This approach (command after selection) seems to work better.  Of course, I'm using Vim 8.1 on Windows 10, and a few years later.


text:
Q: AccessDeniedHttpException when visiting Drupal 8 website after a disaster recovery I have got this error message when visiting Drupal 8 website after a disaster recovery:

The website encountered an unexpected error. Please try again
  later.Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException:
  in Drupal\Core\Routing\AccessAwareRouter->checkAccess()
  (line 114 of core/lib/Drupal/Core/Routing/AccessAwareRouter.php).

  Drupal\Core\Routing\AccessAwareRouter->matchRequest(Object)
  (Line: 101)
      Symfony\Component\HttpKernel\EventListener\RouterListener->onKernelRequest(Object,
  'kernel.request', Object) (Line: 108)
      Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.request',
  Object) (Line: 129)
      Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
      Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
      Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
      Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 184)
      Drupal\page_cache\StackMiddleware\PageCache->fetch(Object, 1, 1) (Line: 121)
      Drupal\page_cache\StackMiddleware\PageCache->lookup(Object, 1, 1) (Line: 75)
      Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
      Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object,
  1, 1) (Line: 50)
      Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object,
  1, 1) (Line: 23)
      Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 664)
      Drupal\Core\DrupalKernel->handle(Object) (Line: 18)

By looking at the core/lib/Drupal/Core/Routing/AccessAwareRouter.php, and reading up Drupal's and Symfony's documentation, it's pointing to the direction where it might be something wrong with the current user's authentification. What are the next steps I should do to find the root cause of the problem?


text:
Q: How to change "." to \cdot automatically By the David Carlisle's answer, Automatically use \cdot
We can input *, TeX turns * into \cdot command.
How can I change * by ".".
\documentclass{article}
\mathcode`\*="8000
{\catcode`\*\active\gdef*{\cdot}}
\begin{document}
$e=m*c*c$ is equiliant to $e=m\cdot c\cdot c$.

I want to type $e=m.c.c$.
\end{document}

Please help me!

A: Replacing the stars (*) with dots (.) in the second and third lines of your example seems to do the trick.

\documentclass{article}
\mathcode`\.="8000
{\catcode`\.\active\gdef.{\cdot}}
\begin{document}
$e=m*c*c$ is equiliant to $e=m\cdot c\cdot c$.

I want type $e=m.c.c$.
\end{document}

However, I guess this could have side effects I'm not knowledgeable enough to warn you about.

A: Since \cdot is a \mathchardef token, you can just use it to set the mathcode of ..
\documentclass{article}
\usepackage{amsmath}

\mathchardef\mathperiod=\mathcode`.
\mathcode`.=\cdot

\begin{document}

I want to type $e=m.c.c$.

$a\mathperiod b$

\end{document}

Saving the original meaning of the period is recommended, in my opinion.


text:
Q: How to get array in php while using post method through android http In android code like this
for(int i=0;i<myArraListSize;i++)
            {
              ItemId[i]=myArrayList.get(i).get("iid");
            params.add(new BasicNameValuePair("email[i]", ItemId[i]));
            }

In php how to get the array value of email[i]
if (isset($_POST['email']) )
{
$email=$_Post['email'];

how to get the array values in php


text:
Q: Suitability of app with long running tasks for AWS Lambda or AWS Step Functions I have an application on an AWS EC2 instance that runs once daily. The application fetches some files from a web service, parses the files line by line, updates a database, updates S3 files based on changes in the database, sends notification emails to customers as well as a few other tasks.
This is a series of logical tasks that must take place in sequence, although some of the tasks can be thought of as sub-tasks that can be executed in parallel. All tasks are a combination of Perl scripts and Java programs, with a single Perl script acting as the manager that executes each in turn. Some tasks can take as long as 45 minutes to complete, and the whole process can take up to 3 hours in total.
I'd like to make this whole process serverless. My initial idea was to use AWS Lambda, whereby each task would execute as a Lambda function, until I discovered Lambda functions impose a 5 minute execution timeout. It seems like the AWS Step Functions service is actually a better fit for my use case, but my understanding is that this service is backed by Lambda, so the tasks will still have the 5 min execution limitation.
(I'm also aware that I would have to re-write my Perl scripts to a language supported by Lambda).
I assume that I can work around the execution time limit by refactoring my code into smaller functions that will guarantee to complete in under 5 minutes. In my particular situation though, this seems inefficient.
Currently the database update task processes lines from a file one at a time. For this to work with Lambda, a Lambda function would need to handle only a single line from the file (or a very small number of lines) in order to guarantee not spilling over 5 minutes execution time. This would involve opening and closing a connection with the database on every invocation of the Lambda function. Also, each line processed should result in an entry written to a file, to be stored in S3. Right now, I just keep a file handle in memory and write the file to S3 when all lines are processed, but with Lambda I would need to keep reading the file, updating it and writing it back to S3.
What I'm asking is:

*

*Is my use case a bad fit for AWS Lambda and/or AWS Step Functions?

*Have I misunderstood how these services work?

*Is there another AWS service that would be a better fit for my use case?

After further research, I think AWS Batch might be a good idea.

A: So to answer your questions:
1) Yeah, if you've got something that'll run for around 45 minutes, whilst you could engineer it with Lambda/Step functions you're probably better off getting a EC2 micro instance.
2)Nope you've pretty much got it.
3) As above you want to go with EC2 for this, there's a good article on using Data Pipelines to start / stop an EC2 instance here that way by starting instance only when you need it the cost(if any) is negligible.
I have jobs that run in this fashion normally you can get away with with a t2.micro instance which is free tier eligible.
You can also run your perl scripts on an EC2 instance so no need to rewrite them!

A: What you want are called Activity Workers.  Tl;dr: You register "activities" and each gets an ARN.  Then you can put that ARN in the resource field of Task states and then you run some code (the "worker") somewhere (in a Lambda, on EC2, in your basement, wherever) that polls for tasks identified by that ARN, then calls back to report success or failure.  Activity Workers can run for up to a year.
Step-by-step details at the AWS docs
In response to RTF's comment, here's a deeper dive: Suppose you have code to color turtles in color_turtles.pl. So what you do is call the CreateActivity API - see http://docs.aws.amazon.com/step-functions/latest/apireference/API_CreateActivity.html - giving the name "ColorTurtles" and it'll give you back an ARN, a string beginning arn:aws...  Then in your state machine you make a Task state with that ARN as the value of the resource field.  Then you add code to color_turtles.pl to poll the service with http://docs.aws.amazon.com/step-functions/latest/apireference/API_GetActivityTask.html - whenever a machine you're running gets to that task, it'll go look for activity workers polling.  It'll give your polling worker the input for the task, then you process the input and generate some output, and call SendTaskSuccess or SendTaskFailure. All these are just REST HTTP calls, so you can run them anywhere and I mean anywhere; in a Lambda, on an EC2 instance, or on some computer anywhere on the Internet.

A: I will start with that it seems you are looking for workflow solutions on AWS. SWF and Step functions are the two most popular ones. Steps function is more recent offering and encouraged by AWS more than SWF.
SWF has native capability to handle long-running tasks,  the downside is that you have to provide your own execution environment for deciders (can't use lambda).
With step functions, you can do this in two different ways. One of the approaches is suggested by Tim in his answer. There is an alternative way to achieve the same which is using job poller in step functions. Job pollers have the ability to call (poll) your resource and find out if the task is done and if not you can send execution in wait mode for the specified time. As mentioned above maximum execution time allowed currently for any workflow is 1 year. In case you have tasks which may take longer than 1 year, you can't use step functions in its current form.


text:
Q: Not able use superscript in C# I want to display the String with superscript like Shibu® using C#.
Unicode of ®:- U+000AE
Here is the code:-
String s = "Shibu";
Console.write(s.join("\xBU+000AE", s));

I am not getting proper output like Shibu®.

A: You need to concatenate those strings, string.Join is for joining several strings together with a special one repeated in between.
Also, representation of unicode characters is done with \uXXXX where XXXX is the hexadecimal code point value.
string s = "Shibu";
Console.WriteLine(s + "\u00AE");

Or simply
string s = "Shibu\u00AE";
Console.WriteLine(s);

Also, you can directly write unicode characters; C# strings are unicode.
string s = "Shibu®";
Console.WriteLine(s);

This does not, however, set the character as "superscript" in the unicode or font meaning of term. I'm not sure that is possible with native C# strings, you need to cope with the existing basic unicode characters.
For fancier, use a visual rich textbox control, or a WPF control, that allow you to set font options.


text:
Q: How to read a RSA public key in PEM + PKCS#1 format I have a RSA public key in PEM format + PKCS#1(I guess):
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBAJNrHWRFgWLqgzSmLBq2G89exgi/Jk1NWhbFB9gHc9MLORmP3BOCJS9k
onzT/+Dk1hdZf00JGgZeuJGoXK9PX3CIKQKRQRHpi5e1vmOCrmHN5VMOxGO4d+zn
JDEbNHODZR4HzsSdpQ9SGMSx7raJJedEIbr0IP6DgnWgiA7R1mUdAgMBAAE=
-----END RSA PUBLIC KEY-----

I want to get the SHA1 digest of its ASN1 encoded version in Python. The first step should be to read this key, but I failed to do it in PyCrypto:
>> from Crypto.PublicKey import RSA
>> RSA.importKey(my_key)
ValueError: RSA key format is not supported

The documentation of PyCrypto says PEM + PKCS#1 is supported, so I'm confused.
I've also tried M2Crypto, but it turns out that M2Crypto does not support PKCS#1 but only X.509.

A: PyCrypto supports PKCS#1 in the sense that it can read in X.509 SubjectPublicKeyInfo objects that contain an RSA public key encoded in PKCS#1.
Instead, the data encoded in your key is a pure RSAPublicKey object (that is, an ASN.1 SEQUENCE with two INTEGERs, modulus and public exponent).
You can still read it in though. Try something like:
from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from base64 import b64decode

key64 = 'MIGJAoGBAJNrHWRFgWLqgzSmLBq2G89exgi/Jk1NWhbFB9gHc9MLORmP3BOCJS9k\
onzT/+Dk1hdZf00JGgZeuJGoXK9PX3CIKQKRQRHpi5e1vmOCrmHN5VMOxGO4d+znJDEbNHOD\
ZR4HzsSdpQ9SGMSx7raJJedEIbr0IP6DgnWgiA7R1mUdAgMBAAE='

keyDER = b64decode(key64)
seq = asn1.DerSequence()
seq.decode(keyDER)
keyPub = RSA.construct( (seq[0], seq[1]) )

Starting from version 2.6, PyCrypto can import also RsaPublicKey ASN.1 objects.
The code is then much simpler:
from Crypto.PublicKey import RSA
from base64 import b64decode

key64 = b'MIGJAoGBAJNrHWRFgWLqgzSmLBq2G89exgi/Jk1NWhbFB9gHc9MLORmP3BOCJS9k\
onzT/+Dk1hdZf00JGgZeuJGoXK9PX3CIKQKRQRHpi5e1vmOCrmHN5VMOxGO4d+znJDEbNHOD\
ZR4HzsSdpQ9SGMSx7raJJedEIbr0IP6DgnWgiA7R1mUdAgMBAAE='

keyDER = b64decode(key64)
keyPub = RSA.importKey(keyDER)


text:
Q: Very interesting program of building pyramid I have came across this very interesting program of printing numbers in pyramid.
If n = 1 then print the following,
1  2
4  3

if n = 2 then print the following,
1  2  3
8  9  4
7  6  5

if n = 3 then print the following,
1   2   3   4
12  13  14  5
11  16  15  6
10   9   8  7

I can print all these using taking quite a few loops and variables but it looks very specific. You might have noticed that all these pyramid filling starts in one direction until it find path filled. As you might have noticed 1,2,3,4,5,6,7,8,9,10,11,12 filed in outer edges till it finds 1 so after it goes in second row after 12 and prints 13,14  and so on. It prints in spiral mode something like snakes game snakes keep on going until it hits itself.
I would like to know is there any algorithms behind this pyramid generation or its just tricky time consuming pyramid generation program.
Thanks in advance. This is a very interesting challenging program so I kindly request no need of pipeline of down vote :)

A: I made a small recursive algorithm for your problem.
public int Determine(int n, int x, int y)
{
  if (y == 0) return x + 1;         // Top
  if (x == n) return n + y + 1;     // Right
  if (y == n) return 3 * n - x + 1; // Bottom
  if (x == 0) return 4 * n - y + 1; // Left
  return 4 * n + Determine(n - 2, x - 1, y - 1);
}

You can call it by using a double for loop. x and y start at 0:
for (int y=0; y<=n; y++)
  for (int x=0; x<=n; x++)
    result[x,y] = Determine(n,x,y);

A: Here is some C code implementing the basic algorithm submitted by @C.Zonnerberg my example uses n=6 for a 6x6 array.
I had to make a few changes to get the output the way I expected it to look. I swapped most the the x's and y's and changed several of the n's to n-1 and changed the comparisons in the for loops from <= to <
int main(){
  int x,y,n;
  int result[6][6];
  n=6;
  for (x=0; x<n; x++){
    for (y=0; y<n; y++) {
      result[x][y] = Determine(n,x,y);
      if(y==0)
        printf("\n[%d,%d] = %2d, ", x,y, result[x][y]);
      else
        printf("[%d,%d] = %2d, ", x,y, result[x][y]);
    }
  }
return 0;
}

int Determine(int n, int x, int y)
{
  if (x == 0) return y + 1;         // Top
  if (y == n-1) return n + x;     // Right
  if (x == n-1) return 3 * (n-1) - y + 1; // Bottom
  if (y == 0) return 4 * (n-1) - x + 1; // Left
  return 4 * (n-1) + Determine(n - 2, x - 1, y- 1);
}

Output
[0,0] =  1, [0,1] =  2, [0,2] =  3, [0,3] =  4, [0,4] =  5, [0,5] =  6,
[1,0] = 20, [1,1] = 21, [1,2] = 22, [1,3] = 23, [1,4] = 24, [1,5] =  7,
[2,0] = 19, [2,1] = 32, [2,2] = 33, [2,3] = 34, [2,4] = 25, [2,5] =  8,
[3,0] = 18, [3,1] = 31, [3,2] = 36, [3,3] = 35, [3,4] = 26, [3,5] =  9,
[4,0] = 17, [4,1] = 30, [4,2] = 29, [4,3] = 28, [4,4] = 27, [4,5] = 10,
[5,0] = 16, [5,1] = 15, [5,2] = 14, [5,3] = 13, [5,4] = 12, [5,5] = 11,

A: With an all-zeros array, you could start with [row,col] = [0,0], fill in this space, then add [0,1] to position (one to the right) until it's at the end or runs into a non-zero.
Then go down (add [1,0]), filling in space until it's the end or runs into a non-zero.
Then go left (add [0,-1]), filling in space until it's the end or runs into a non-zero.
Then go up (add [-1,0]), filling in space until it's the end or runs into a non-zero.
and repeat...


text:
Q: Display Author Name (outside of loop) I have an area of my index.php file that I'm customizing in a theme whereby I would like to display the most recent post and some additional meta. I was able to pull the featured image, post title (and link), & the date; but not the author. I've tried various examples from the WP boards with no luck. The latest attempt below:
<?php
        $args = array( 'numberposts' => '1');
        $recent_posts = wp_get_recent_posts( $args );
        $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
        //$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));

        foreach( $recent_posts as $recent ){
            $post_author = get_user_by( 'id', $recent->post_author );
            echo '
';

            echo '

';
            echo '
' .   $recent["post_title"].'
';
            echo '
'. $post_author->display_name .' | '. get_the_time('F jS, Y') .'
';
            echo 'Read the post';
            echo '

';
        }
    ?>

A: Inside your foreach loop:
$post_author = get_user_by( 'id', $recent['post_author'] );

This gets you the user object which looks like what you were trying to do with $curauth.
You could then output $post_author->display_name in place of $curauth.
echo '
'. $post_author->display_name .' ...


text:
Q: Closure of function defined as an argument Disclaimer: This question is purely curiosity driven and has to do a lot with how the javascript works.
I understand why the following code works. Due to closures, foo has access to the scope where a resides. This makes sense.
var a = 10

var foo = function(){
console.log(a);
}

setTimeout(foo,1000)

However, i wonder why the following also works (explained right after).
var a = 10
setTimeout(function(){
console.log(a);
},1000)

The function is defined in the argument of the function receiving it and essentially was never a closure to the scope that contains a. We know that when a function receives an argument, it creates a local variable for that argument so for example
var outerVar="5"

var bar = function(a){
//implicitly, var a = outerVar happens here
console.log(a)
}

bar(something);

So following that logic, the function passed to setTimeout couldnt have access to a and yet it does.
Im suspecting that when a function is defined in the argument space what happens is, it realy is defined before being assigned as an argument but have no proof of that. Any pointers highly appreciated.
Thanks a bunch.

A: It's not exactly closure, but it's close.
Strictly speaking, closure is when a variable's scope ends, but is still enclosed in an inner function that still lives on:
function createTimer() {
  let counter = 0;
  return function() {
    return counter++;
  }
}

const timer = createTimer(); // function() { ... }
console.log(timer(), timer(), timer()); // 0, 1, 2

The function in which counter is defined has returned, the scope ended, and under normal circumstances, counter should have died and garbage collected. But the inner function returned from createTimer() still has a reference to it, from the enclosed scope, that is a closure.

In JavaScript, every function has access to all of the scopes of all of its ancestors, this is what you're seeing here.
The function passed to setTimeout() has access to a because a is defined in the scope around it.

A: When you look at a javascript code and see how it works, the best way according to me is first understand the javascript engine how it works.
First it traverses the code and assigns all the variables to the scope and further more in the second trace it assigns the values based on the scopes.
So in your first code,
The engine first traverses and assigns
var a to global scope,
var foo as global scope,
Then when setTimeout runs it calls foo function and logs the value of a as that of the global a as it doesnt have any local "a" so checks the lexical scoping.
In your second code,
Var a is again global scoped
 and no other declaration this time.
In second traverse it assigns the value 10 to a and interprets the settimeout and prints the value
In your third code,
Same as the second one except the fact that instead what "foo" was giving to the settimeout function, you wrote your callback function then n there itself.
By the time l it executed the setTimeout,
Each of your codes have the value for "a" in the global scope that they are accessing.


text:
Q: How do I style an ASP.NET HTML server control by ID? When I create an HTML server control in ASP.NET 4.5 with an ID and use CSS to style that ID, it fails. When I inspect the source of the ASPX page, it shows that ASP.NET has changed my control's ID. In this instance...

  Current

...becomes...

  Current

Can I then reliably (and with best practices in mind) just create the CSS style for #article_PasswordStatus instead? Or should I create a one-use CSS class for it, something like...

  Current

Preferably, can I still somehow use the original ID I assigned?
Note: I do not want to convert this to a Web server control.

A: Assuming .net 4 and greater, you can use ClientIDMode. Your HTML would be like this

    Current

When using Static the ClientID value is set to the value of the ID property. If the control is a naming container, the control is used as the top of the hierarchy of naming containers for any controls that it contains.

A: Add in the ClientIDMode="Static" option to ensure your client Ids do not change.
Information can be found here.

    Current

This option forces the control's ClientID to use its ID value directly. No naming container naming at all is applied and you end up with clean client ids

A: It's usually a best practice to use classes for css styling instead of IDs. You can avoid problems like this, reuse your css and so on, so that would be the path I'd choose.
ID in asp.net (webforms) can be modified in various ways and I wouldn't rely on that personally.


text:
Q: Is there a way to submit data to google forms, but not redirect to the google form? I'm new to javascript, and I'm working on a project to accept data from a  and then output the data to google forms cuz idk how to host my own server. However, I don't want to be redirected to google forms. Is there a way to do this?

A: While creating the Google Form, go to the Settings bar and enable the "Allow only one response per user" option. When the unique option for a Google Form is enabled, respondents must sign in with their Google account to access the form.
hope this helps.

A: Create a form with same input names as google form and submit the response to google form api.