text:
Q: Proving that a particular matrix exists I found this problem in a programming forum Ohjelmointiputka:

*

*https://www.ohjelmointiputka.net/postit/tehtava.php?tunnus=ahdruu and

*https://www.ohjelmointiputka.net/postit/tehtava.php?tunnus=ahdruu2
Somebody said that there is a solution found by a computer, but I was unable to find a proof.
Prove that there is a matrix with 117 elements containing the digits such that one can read the squares of the numbers 1, 2, ..., 100.
Here read means that you fix the starting position and direction (8 possibilities) and then go in that direction, concatenating the numbers. For example, if you can find for example the digits 1,0,0,0,0,4 consecutively, you have found the integer 100004, which contains the square numbers of 1, 2, 10, 100 and 20, since you can read off 1, 4, 100, 10000, and 400 (reversed) from that sequence.
But there are so many numbers to be found (100 square numbers, to be precise, or 81 if you remove those that are contained in another square number with total 312 digits) and so few integers in a matrix that you have to put all those square numbers so densely that finding such a matrix is difficult, at least for me.
I found that if there is such a matrix mxn, we may assume without loss of generalty that m<=n. Therefore, the matrix must be of the type 1x117, 3x39 or 9x13. But what kind of algorithm will find the matrix?
I have managed to do the program that checks if numbers to be added can be put on the board. But how can I implemented the searching algorithm?
# -*- coding: utf-8 -*-

# Returns -1 if can not put and value how good a solution is if can be put. Bigger value of x is better.
def can_put_on_grid(grid, number, start_x, start_y, direction):
#   Check that the new number lies inside the grid.
    x = 0
    if start_x < 0 or start_x > len(grid[0]) - 1 or start_y < 0 or start_y > len(grid) - 1:
        return -1
    end = end_coordinates(number, start_x, start_y, direction)
    if end[0] < 0 or end[0] > len(grid[0]) - 1 or end[1] < 0 or end[1] > len(grid) - 1:
        return -1
#   Test if new number does not intersect any previous number.
    A = [-1,-1,-1,0,0,1,1,1]
    B = [-1,0,1,-1,1,-1,0,1]
    for i in range(0,len(number)):
        if grid[start_x + A[direction] * i][start_y + B[direction] * i] not in ("X", number[i]):
            return -1
        else:
            if grid[start_x + A[direction] * i][start_y + B[direction] * i] == number[i]:
                x += 1
    return x

def end_coordinates(number, start_x, start_y, direction):
    end_x = None
    end_y = None
    l = len(number)
    if direction in (1, 4, 7):
        end_x = start_x - l + 1
    if direction in (3, 6, 5):
        end_x = start_x + l - 1
    if direction in (2, 0):
        end_x = start_x
    if direction in (1, 2, 3):
        end_y = start_y - l + 1
    if direction in (7, 0, 5):
        end_y = start_y + l - 1
    if direction in (4, 6):
        end_y = start_y
    return (end_x, end_y)

if __name__ == "__main__":
    A = [['X' for x in range(13)] for y in range(9)]
    numbers = [str(i*i) for i in range(1, 101)]
    directions = [0, 1, 2, 3, 4, 5, 6, 7]
    for i in directions:
        C = can_put_on_grid(A, "10000", 3, 5, i)
        if C > -1:
            print("One can put the number to the grid!")
    exit(0)

I also found think that brute force search or best first search is too slow. I think there might be a solution using simulated annealing, genetic algorithm or bin packing algorithm. I also wondered if one can apply Markov chains somehow to find the grid. Unfortunately those seems to be too hard for me to implemented at current skills.

A: There is a program for that in https://github.com/minkkilaukku/square-packing/blob/master/sqPackMB.py . Just change M=9, N=13 from the lines 20 and 21.


text:
Q: Rest service returns "method not allowed" on webpage I'm trying to pass object parameter as JSON format to WCF restful service.
service contract code like this;
 [OperationContract]
 [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "xml/{id}")]
 string XMLData(string ID);

And my web.config file like this;
<system.serviceModel>
<services>
  <service name="RestService.RestServiceImpl" behaviorConfiguration="ServiceBehaviour">
    <endpoint address="" binding="webHttpBinding" contract="RestService.IRestServiceImpl" behaviorConfiguration="web">
    </endpoint>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<protocolMapping>
  <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

When I trying call the service with "http://localhost/serviceurl/xml/123" url, Service returned "Method not allowed" error message.

A: I resolved it. I had to remove the <ProtocolMapping> and <ServiceHostingEnvironment> tag from the web.config file.
Its works fine now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Infer ip subnet using bit operations? I have a bunch of IPV4 IPs, and I want to infer the subnet they belong to.
#...10101 00
#...10101 01
#...10101 10
#...10101 11
#...11111 is the subnet
One way I can think of is to forget about the "."s and treat the IPs as strings of 1s and 0s. Now, the only thing we need is to figure out which left-most block never changes. In my example, only the last two bits ever vary, so we know 11111111.11111111.11111111.111111 is the subnet.
Is there a clever way of determining the subnet this way, using bit operations? XOR's, etc.


text:
Q: Is there a faster Alternative to Do Until loops in VBA? Hello I am wondering if anyone has any suggestions for a replacement for a Do Until loop in VBA??
My Code (see below), basically looks at cell F4, if Cell F4 is 0 then the row is selected and deleted. the cells then shift up, it loops again until the F4 is either greater than zero or it is empty.
The code actually works perfectly well but it takes an age to finish (around 3 mins at a guess). I do make sure that screen updating is turned off etc, I just haven't included that in this example.
I am not to fussed that it takes so long in the first instance but eventually it will doing this search multiple times in one hit, potentially up to 10K cells at a time so I want it to be a bit more snappy...
So my question is is there anything I can do other than Do until loops?
Do Until Raw1.Range("F4") = "" Or Raw1.Range("F4") > 0
    If Raw1.Range("F4").Value = 0 Then
        Raw1.Range("A4:H4").Select
        Selection.Delete Shift:=xlUp
    End If
Loop

A: Delete Data Using AutoFilter

*

*Starting from row 4 (the header row is 3), this will delete all consecutive A:H row ranges, whose cell values in column F are equal to 0 (preserving blank cells).

Option Explicit

Sub DeleteZeros()
' 'Raw1' is the code name of a worksheet in the workbook containing this code.

    Const FirstCellAddress As String = "F3"
    Const ColumnsAddress As String = "A:H"

    If Raw1.FilterMode Then Raw1.ShowAllData

    Dim crg As Range ' Column Range (Has Headers - 'F')
    With Raw1.Range(FirstCellAddress)
        Dim lRow As Long
        lRow = Raw1.Cells(Raw1.Rows.Count, .Column).End(xlUp).Row
        Dim rCount As Long: rCount = lRow - .Row + 1
        If rCount < 2 Then Exit Sub ' to few rows
        Set crg = .Resize(rCount)
    End With

    Dim drg As Range ' Data Range (No Headers - 'A:H')
    With crg
        Set drg = .Resize(rCount - 1).Offset(1) _
            .EntireRow.Columns(ColumnsAddress)
    End With
    Dim FirstDataRow As Long: FirstDataRow = drg.Row

    ' Filter Column Range
    crg.AutoFilter 1, "0"

    Dim vdrg As Range ' Visible Data Range (No Headers - 'A:H')
    On Error Resume Next
        Set vdrg = drg.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    Raw1.AutoFilterMode = False

    ' Delete
    If vdrg Is Nothing Then Exit Sub
    If vdrg.Cells(1).Row <> FirstDataRow Then Exit Sub
    vdrg.Areas(1).Delete xlShiftUp

End Sub

A: It is always a better solution to delete from bottom up then from top down.
Sub deleteRows()

Const checkColumn As Long = 6   'Column F

Dim rg As Range
'!!!!!you will have to adjust this to your needs!!!!
Set rg = ActiveSheet.Cells(checkColumn, 4).CurrentRegion

Dim cntRows As Long
cntRows = rg.Rows.Count

Dim i As Long
For i = cntRows To 1 Step -1
    If rg.Cells(i, checkColumn) = 0 Then
        'rg.Rows(i).EntireRow.Delete xlShiftUp    'removes entire row
         rg.Rows(i).Delete xlShiftUp              'removes only columns A-H
    End If
Next
End Sub

A: It is faster to delete all the cells in 1 operation.  In my example code, I have a runner find the last valid cell.  I use that cell to determine the size of range that needs to be deleted.
Sub RemoveEmptyRowsBasedOnColumnValues()
    Dim CalculationMode As XlCalculation
    CalculationMode = Application.Calculation
    Application.Calculation = xlCalculationManual

    Application.ScreenUpdating = False

    Dim Cell As Range
    With Raw1
        For Each Cell In .Range("F4", .Cells(.Rows.count, "F").End(xlUp))
            If Cell.Value > 0 Then
                If Cell.Row > 3 Then
                    .Range("A4:H4").Resize(Cell.Row - 4).Delete Shift:=xlUp
                End If
                Exit For
            End If
        Next
    End With

    Application.Calculation = CalculationMode
End Sub

Function Raw1() As Worksheet
    Set Raw1 = ThisWorkbook.Worksheets("Raw1")
End Function


text:
Q: Need cron 'type' approach that runs constantly I need a decent approach to helping run a cron type script on my shared hosting server. For now - it will have to stay a share hosting account, so that doesn't change. And I understand that a "cron" can do this and set the intervals to be every minute. But I would like to see if we could get it a little faster than that.
I've created a web based application that loops over directories and files within those directories. When a new file is found, it then executes the rest of the stuff that needs to happen. This all works as it should and nothing is needed there. These files that are being processed are files of 'urgency'. They help local departments and people actually respond to these files when they are processed. So the 'urgency' factor is important in here.
With that being said, it would be interesting to hear the best approach to execute this script on a frequent basis, (like every 30 seconds or so) without:

*

*Having the hosting company step in

*Eating up too many resources (memory/queries, etc. There's minimal queries happening)

*Still allowing this task to be completed regularly without issues.

As a side note: I do have access to multiple accounts on multiple servers and one way I thought about was to creating individual files on those accounts to run as well, and just do something like file_get_contents (even though no output happens) so it would execute the script. Again - the "urgency" is a huge factor in this application so it's important to make this run as fast as possible, but at least allowing for a file to be 'archived' and a couple of queries to run - without overstepping each other in the process (duplications)
I do have access to CLI (shell) if that helps as well.

A: One super simple option - Have the cron run the task every minute:
function task()
{
    doYourThing();
    sleep(30);
    doYourThing();
}

Its not ideal - but it technically runs the doYourThing() every 30seconds.
Edit: why dont you 'trigger' an event when people upload new files to run the task on demand?


text:
Q: Group of guardians who watch for time variants and destroy planets if needed So I remember parts of the plot but can't remember character names. One of the guardians disappeared and it causes distrust between the other guardians. There was a part where people summon a god who is actually from a different time and is destroyed by one of the watchers. A main character is left with knowledge of the event.
I read it within the last year or two (I believe). The guardians were humans once but were chosen to take on mantles of guardians and watch for changes or errors in timelines across a bunch of planets or worlds. There was also a guardian who was betrayed and left a trail of clues that one of the guardians was following.

A: Finally found it. It's the Cradle series by Will Wight.
Goodreads summary of the first book, Unsouled:

Sacred artists follow a thousand Paths to power, using their souls to control the forces of the natural world.
Lindon is Unsouled, forbidden to learn the sacred arts of his clan.
When faced with a looming fate he cannot ignore, he must defy his family's rules...and forge his own Path.


text:
Q: RavenDB map/reduce index performance for bulk insert of 3 million records I am currently using RavenDB in a proof-of-concept for a simple dashboard application that provides an aggregated view over incoming events into a system. Lets say for example the user can see a granularity of by hour (for a day), day, month or year.
I have 3 million existing events to import & index and I'm looking for the best / most performant way to go about doing this after a number of less than successful attempts.
Please note this question isn't about the performance of the application once the data and indexes have been generated, that part is very good.
So I have:

*

*A single class that represents the events, with fields for what happened and when (DateTime + 3 string fields).

*Map/Reduce indexes for Hour, Day, Month and Year based on then event date and event type.

*The app queries the indexes for the hourly, daily, monthly and yearly values

*Historically the hourly aggregates would needed at minimum (not the individual events).

I can import the data without issue provided the indexes don't exist, however if the indexes exist i consistently get OutOfMemoryExceptions after about 45 minutes of index processing.
Can the indexing process be tweaked and what would be the suitable values?
Alternatively happy to have it suggested to approach the problem from a different way.

A: I found that separating the import process into batches (say all data for one month at a time), importing with the indexes existing in raven and then waiting until there were no longer any stale indexes produced the most stable results.
I used the GetStatistics().StaleIndexes combined with a Thread.Sleep to have the process wait between batches. I still had the session batch size left at 1024 documents per session.


text:
Q: How to import SVG's in nextjs I'm migrating my react website to nextjs. I have one assets folder at the root which contains lots of svgs and I have one constants.js file where I'm importing all the SVG's as ReactComponent. I would like to know how to convert this part of code in nextjs.
Error message:
Module not found: Can't resolve '../../../assets/skills/html5.svg'
> 1 | import { ReactComponent as HTML } from "../../../assets/skills/html5.svg";
  2 | import { ReactComponent as CSS } from "../../../assets/skills/css.svg";

constants.js
import { ReactComponent as HTML } from "../../../assets/skills/html5.svg";
import { ReactComponent as CSS } from "../../../assets/skills/css.svg";

export const SKILLS = [
  {
    name: "html",
    image: HTML, // SVG Component
  },
  {
    name: "css",
    image: CSS,
  },
]

Folder Structure:

A: You can setup SVGR into your project and add them as regular react components. Your code could end up looking something like this

export const SKILLS = [
  {
    name: "html",
    image: <Html className="html"/>, // SVG Component
  },
  {
    name: "css",
    image: <Css className="css"/>,
  },


text:
Q: How to get pending view controller from method? How can I get the pending view controller value from this method?
-(void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray *)pendingViewControllers {
}

What is the code I can use to get the pending view controller value from this array? Any help would be greatly appreciated?
I have tried using this code:
 nextIndex = (int)[pendingViewControllers objectAtIndex:0];

But it keeps returning -1 instead of the next or previous value!

A: The method passes in an array of the pending view controllers, not an index, so you can't cast it to an int. If you want to get the first view controller, you can do it like this,
UIViewController *vc = pendingViewController.firstObject;


text:
Q: HTML span tag question I was wondering can I wrap a span tag around multiple a tags and another span tag?
Here is the Html code.

    link
    |
    link
    link
    link
    link

A: Yes you can. That is valid html :) You can check with W3C Validator.

A: Yes it's possible since both span and a are inline elements.

A: yes you are allowed to if you have any doubts you can just validate on w3c input validator
very good tool!


text:
Q: highslide js 404 error zoomin.cur zoomout.cur I use highslide js 5.0.0.0. and use the highslide-full.js.
I always got 2 errors in Chrome:

404 errors on zoomin.cur and zoomout.cur.

in the old forum i found out that there is a conflict with the path to the grafic directory.
once the entry in your own js script, that you use to setup functions
and the entry in highslide-full.js
the path from highslide-full.js was always used, which was wrong.
my solution was the line maybe by me it is 37 in highslide-full.js
which indicates the wrong path should be removed or excluded as a comment line
from
graphicsDir : 'highslide/graphics/',

to
// graphicsDir : 'highslide/graphics/',

so it works, when the correct path is given in your own js script.
I know it is not so strong error, only cosmetic :) bur it works.
I hope so i can help people who have the same problem


text:
Q: Событие при докрутке до блока на странице Существует обычная html страница:
У нее несколько секций,
Нужна функция которая отслеживала бы событие скролла к блоку с id="about".
Когда срабатывает событие выводиться в консоль какой нибудь текст типа: console.log('yes');

A:

var test = document.getElementById('test');

window.addEventListener('scroll', function() {
  if (window.scrollY >= test.offsetTop - test.offsetHeight) console.log('yes');
})
body{
  margin: 0;
}

section{
  width: 100%;
  height: 320px;
  background-color: var(--c);
}


text:
Q: Error: Cannot match any routes. URL Segment in Angular 13 When I click on the Portfolio rubric, the page is not running...

I have an error message in the console which is the following.
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'administration/portfolio'
Error: Cannot match any routes. URL Segment: 'administration/portfolio'

Here is the structure of the project

I suspect it's a problem with the route configuration, but I haven't found the problem for several hours.
app-routing.module.ts
const routes: Routes = [
    { path: '', component: OnlineComponent, canActivate: [AuthGuard] },
    { path: 'signin', component: SigninComponent },

];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts
@NgModule({
    imports: [
        BrowserModule,
        ReactiveFormsModule,
        HttpClientModule,
        AppRoutingModule
    ],
    declarations: [
        AppComponent,
        OnlineComponent,
        SigninComponent
    ],
    providers: [
        { provide: HTTP_INTERCEPTORS, useClass: BasicAuthInterceptor, multi: true },
        { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },

        // provider used to create fake backend
        fakeBackendProvider
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

online-routing.module.ts
const ONLINE_ROUTES: Routes = [
  {
    path: '',
    component: OnlineComponent,
    children: [
      {
        path: 'administration',
        loadChildren: () => import('./views/administration/administration.module').then((m) => m.AdministrationModule),
      },

    ]
  },
];

@NgModule({
  imports: [RouterModule.forChild(ONLINE_ROUTES)],
  exports: [RouterModule],
})
export class OnlineRoutingModule {}

online.module.ts
@NgModule({
  imports: [CommonModule, OnlineRoutingModule],
  declarations: [OnlineComponent],
})
export class OnlineModule {}

administration-routing.module.ts
export const ADMINISTRATION_ROUTES: Routes = [

  {
    path: '',
    component: OnlineComponent,

  },

  {
    path: 'portfolio',
    component: PortfolioComponent,
  },

];

@NgModule({
  imports: [RouterModule.forChild(ADMINISTRATION_ROUTES)],
  exports: [RouterModule],
})
export class AdministrationRoutingModule {}

administration.module.ts
@NgModule({
  imports: [CommonModule, AdministrationRoutingModule],
  declarations: [AdministrationComponent],
})
export class AdministrationModule {}

portfolio.module.ts
@NgModule({
  imports: [CommonModule, RouterModule],
  declarations: [PortfolioComponent],
})
export class PortfolioModule {}

Here is the project here.
Thank you for your help.

A: I think you have to registry your inside module routing in your app-routing.module.ts with loadChildren:
export const appRoutes: Routes = [
    ...
    {
      path: 'auth',
      component: AdministrationComponent,
      canActivate: [AuthGuard],
      children: [
       { path: '', loadChildren: () => import('./modules/auth/administration-module.module').then(m => m.AdministrationModule) }
      ]
    }
    ...
]

A: I think* it's because AdministrationModule doesn't know about PortfolioComponent since this is in a separate module.
So either unmodularise PortfolioModule and import PortfolioComponent or lazy load the PortfolioModule for the portfolio route and add a simple routing for path: "" to PortfolioModule.
*routing is hard!


text:
Q: Send message to specific client with socket.io and node.js I'm working with socket.io and node.js and until now it seems pretty good, but I don't know how to send a message from the server to an specific client, something like this:
client.send(message, receiverSessionId)

But neither the .send() nor the .broadcast() methods seem to supply my need.
What I have found as a possible solution, is that the .broadcast() method accepts as a second parameter an array of SessionIds to which not send the message, so I could pass an array with all the SessionIds connected at that moment to the server, except the one I wish send the message, but I feel there must be a better solution.
Any ideas?

A: Well you have to grab the client for that (surprise), you can either go the simple way:
var io = io.listen(server);
io.clients[sessionID].send()

Which may break, I doubt it, but it's always a possibility that io.clients might get changed, so use the above with caution
Or you keep track of the clients yourself, therefore you add them to your own clients object in the connection listener and remove them in the disconnect listener.
I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}} might do the job.

A: As of version 1.4.5, be sure you provide a properly prefixed socketId in io.to().
I was taking the socketId the Client logged to debug and it was without prefix so I ended up searching forever till I found out! So you might have to do it like this if the Id you have is not prefixed:
io.to('/#' + socketId).emit('myevent', {foo: 'bar'});

A: io.sockets.sockets[socket.id].emit(...) worked for me in v0.9

A: You can use
//send message only to sender-client
socket.emit('message', 'check this');
//or you can send to all listeners including the sender
io.emit('message', 'check this');
//send to all listeners except the sender
socket.broadcast.emit('message', 'this is a message');
//or you can send it to a room
socket.broadcast.to('chatroom').emit('message', 'this is the message to all');

A: In 1.0 you should use:
io.sockets.connected[socketid].emit();

A: Also you can keep clients refferences. But this makes your memmory busy.
Create an empty object and set your clients into it.
const myClientList = {};

  server.on("connection", (socket) => {
    console.info(`Client connected [id=${socket.id}]`);
     myClientList[socket.id] = socket;
  });
  socket.on("disconnect", (socket) => {
    delete myClientList[socket.id];
  });

then call your specific client by id from the object
myClientList[specificId].emit("blabla","somedata");

A: Ivo Wetzel's answer doesn't seem to be valid in Socket.io 0.9 anymore.
In short you must now save the socket.id and use io.sockets.socket(savedSocketId).emit(...)  to send messages to it.
This is how I got this working in clustered Node.js server:
First you need to set Redis store as the store so that messages can go cross processes:
var express = require("express");
var redis = require("redis");
var sio = require("socket.io");

var client = redis.createClient()
var app = express.createServer();
var io = sio.listen(app);

io.set("store", new sio.RedisStore);

// In this example we have one master client socket
// that receives messages from others.

io.sockets.on('connection', function(socket) {

  // Promote this socket as master
  socket.on("I'm the master", function() {

    // Save the socket id to Redis so that all processes can access it.
    client.set("mastersocket", socket.id, function(err) {
      if (err) throw err;
      console.log("Master socket is now" + socket.id);
    });
  });

  socket.on("message to master", function(msg) {

    // Fetch the socket id from Redis
    client.get("mastersocket", function(err, socketId) {
      if (err) throw err;
      io.sockets.socket(socketId).emit(msg);
    });
  });

});

I omitted the clustering code here, because it makes this more cluttered, but it's trivial to add. Just add everything to the worker code. More docs here http://nodejs.org/api/cluster.html

A: Whatever version we are using if we just console.log() the "io" object that we use in our server side nodejs code, [e.g. io.on('connection', function(socket) {...});], we can see that "io" is just an json object and there are many child objects where the socket id and socket objects are stored.
I am using socket.io version 1.3.5, btw.
If we look in the io object, it contains,
 sockets:
  { name: '/',
    server: [Circular],
    sockets: [ [Object], [Object] ],
    connected:
     { B5AC9w0sYmOGWe4fAAAA: [Object],
       'hWzf97fmU-TIwwzWAAAB': [Object] },

here we can see the socketids "B5AC9w0sYmOGWe4fAAAA" etc. So, we can do,
io.sockets.connected[socketid].emit();

Again, on further inspection we can see segments like,
 eio:
  { clients:
     { B5AC9w0sYmOGWe4fAAAA: [Object],
       'hWzf97fmU-TIwwzWAAAB': [Object] },

So, we can retrieve a socket from here by doing
io.eio.clients[socketid].emit();

Also, under engine we have,
engine:
 { clients:
    { B5AC9w0sYmOGWe4fAAAA: [Object],
      'hWzf97fmU-TIwwzWAAAB': [Object] },

So, we can also write,
io.engine.clients[socketid].emit();

So, I guess we can achieve our goal in any of the 3 ways I listed above,

*

*io.sockets.connected[socketid].emit();
OR

*io.eio.clients[socketid].emit();
OR

*io.engine.clients[socketid].emit();

A: each socket joins a room with a socket id for a name, so you can just
io.to('socket#id').emit('hey')

docs: http://socket.io/docs/rooms-and-namespaces/#default-room

A: You can do this
On server.
global.io=require("socket.io")(server);

io.on("connection",function(client){
    console.log("client is ",client.id);
    //This is handle by current connected client
    client.emit('messages',{hello:'world'})
    //This is handle by every client
    io.sockets.emit("data",{data:"This is handle by every client"})
    app1.saveSession(client.id)

    client.on("disconnect",function(){
        app1.deleteSession(client.id)
        console.log("client disconnected",client.id);
    })

})

    //And this is handle by particular client
    var socketId=req.query.id
    if(io.sockets.connected[socketId]!=null) {
        io.sockets.connected[socketId].emit('particular User', {data: "Event response by particular user "});
    }

And on client, it is very easy to handle.
var socket=io.connect("http://localhost:8080/")
    socket.on("messages",function(data){
        console.log("message is ",data);
        //alert(data)
    })
    socket.on("data",function(data){
        console.log("data is ",data);
        //alert(data)
    })

    socket.on("particular User",function(data){
        console.log("data from server ",data);
        //alert(data)
    })

A: The simplest, most elegant way
verified working with socket.io v3.1.1
It's as easy as:
client.emit("your message");

And that's it. Ok, but how does it work?
Minimal working example
Here's an example of a simple client-server interaction where each client regularly receives a message containing a sequence number. There is a unique sequence for each client and that's where the "I need to send a message to a particular client" comes into play.
Server
server.js
const
    {Server} = require("socket.io"),
    server = new Server(8000);

let
    sequenceNumberByClient = new Map();

// event fired every time a new client connects:
server.on("connection", (socket) => {
    console.info(`Client connected [id=${socket.id}]`);
    // initialize this client's sequence number
    sequenceNumberByClient.set(socket, 1);

    // when socket disconnects, remove it from the list:
    socket.on("disconnect", () => {
        sequenceNumberByClient.delete(socket);
        console.info(`Client gone [id=${socket.id}]`);
    });
});

// sends each client its current sequence number
setInterval(() => {
    for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) {
        client.emit("seq-num", sequenceNumber);
        sequenceNumberByClient.set(client, sequenceNumber + 1);
    }
}, 1000);

The server starts listening on port 8000 for incoming connections. As soon as a new connection is established, that client is added to a map that keeps track of its sequence number. The server also listens for the disconnect event to remove the client from the map when it leaves.
Each and every second, a timer is fired. When it does, the server walks through the map and sends a message to every client with their current sequence number, incrementing it right after. That's all that is to it. Easy peasy.
Client
The client part is even simpler. It just connects to the server and listens for the seq-num message, printing it to the console every time it arrives.
client.js
const
    io = require("socket.io-client"),
    ioClient = io.connect("http://localhost:8000");

ioClient.on("seq-num", (msg) => console.info(msg));

Running the example
Install the required libraries:
npm install socket.io@3.1.1 socket.io-client@3.1.1

Run the server:
node server

Open other terminal windows and spawn as many clients as you want by running:
node client

I have also prepared a gist with the full code here.

A: Socket.IO allows you to "namespace" your sockets, which essentially means assigning different endpoints or paths.
This might help:
http://socket.io/docs/rooms-and-namespaces/


text:
Q: Convert schema of a Spark DataFrame to another DataFrame I have a Spark DataFrame on PySpark and I want to store its schema into another Spark DataFrame.
For example:
I have a sample DataFrame df that looks like -
+---+-------------------+
| id|                  v|
+---+-------------------+
|  0| 0.4707538108432022|
|  0|0.39170676690905415|
|  0| 0.8249512619546295|
|  0| 0.3366111661094958|
|  0| 0.8974360488327017|
+---+-------------------+

I can look out at the schema of df by doing -
df.printSchema()

root
 |-- id: integer (nullable = true)
 |-- v: double (nullable = false)

What I require is a DataFrame that displays above information on df in two columns col_name and dtype.
Expected Output:
+---------+-------------------+
| col_name|              dtype|
+---------+-------------------+
|       id|            integer|
|        v|             double|
+---------+-------------------+

How do I achieve this? I cannot find anything regarding this. Thanks.

A: The simplest thing would be create a dataframe from df.dtypes:
spark.createDataFrame(df.dtypes, ["col_name", "dtype"]).show()
#+--------+------+
#|col_name| dtype|
#+--------+------+
#|      id|   int|
#|       v|double|
#+--------+------+

But if you wanted the dtype column to be as shown in printSchema, you could do so through df.schema
spark.createDataFrame(
    [(d['name'], d['type']) for d in df.schema.jsonValue()['fields']],
    ["col_name", "dtype"]
).show()
#+--------+-------+
#|col_name|  dtype|
#+--------+-------+
#|      id|integer|
#|       v| double|
#+--------+-------+


text:
Q: How to add CakePHP LDAP Authentication? I am very new to CakePHP and this is my first attempt using LDAP .
I get the following error message using this CakePHP Ldap Authentication example.

LDAP not configured on this server. The PHP-LDAP extension is probably
  missing!

My database.php code is
class DATABASE_CONFIG {
    public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'root',
        'password' => 'my!password',
        'database' => 'my_db',
        'prefix' => '',
        //'encoding' => 'utf8',
    );
    public $ldap = array(
        'datasource' => 'Idbroker.LdapSource',
        'host' => 'dc1.my_domain.net',
        'port' => 3268,
        'basedn' => 'CN=Users,DC=my_domain,DC=net',
        'login' => 'CN=theadmin,DC=my_domain,DC=net',
        'password' => 'my!password',
        'database' => '',
        'tls'         => false,
        'type' => 'ActiveDirectory',
        'version' => 3,
    );
}

The platform is Windows Server 2012 | Apache HTTP | CollabNet | Subversion | Microsoft Active Directory.
Modules util_ldap mod_authnz_ldap are loaded on the apache2handler according to phpinfo.php and the php.ini on the server contains
extension=php_ldap.dll
[ldap]
; -1 for unlimited.
ldap.max_links = -1

Is there something else that needs to be loaded on the server for php-ldap?
Are there additional CakePHP debug methods I should be using?

A: For php-ldap to work in Win32 environments, you need to have the files libeay32.dll and ssleay32.dll in your system path. Depending on your PHP version, you may also need libsasl.dll.
Check to see if those are accessible on your system. Also, make sure php-ldap.dll is really available. At least that's how i got it to work on my Windows system.


text:
Q: Smart way to check a root Let $\alpha$ be a root of $x^3+3x+5$. Let $\omega:=\frac{1+\alpha+\alpha^2}{3}$. Verify that $\omega$ is a root of $y^3+y^2+2y-1$.
Is there some trick to do this computation quickly?

A: We can write that
$$
1+\alpha+\alpha^2=\frac{1-\alpha^3}{1-\alpha}
$$
But $\alpha^3 = -3\alpha-5$, so we have
$$
\frac{1+\alpha+\alpha^2}3=\frac{2+\alpha}{1-\alpha}
$$
It's easier to calculate from here, since you can factor out the denominator and then ignore it (because the denominator won't be zero at the root).


text:
Q: Angular error: Can't bind to 'x property' since it isn't a known property of 'x element' , even after putting @Input in child component I have used an @Input decorator in a component to receive data from another component.
childComponent.ts-
@Input() isShown: boolean;
parentComponent.html-
<tab [isShown]="form.get('tab').value === View.Account" [label]="Tab Name" ></tab>
I am getting this error on compilation--
error: Can't bind to 'isShown' since it isn't a known property of 'tab'
What can I do to fix this?

A: Looking at the above comments and see that "tab" selector being a selector for a custom library, not your child component, it doesn't make any sense of having an @Input on your child, but you use it to another component.
The isShown should be used with the child selector.


text:
Q: Watch control to determine events being fired? Is there a way to list all fired events for specific WinForms controls without explicitly creating a handler for each possible event?  For example, I might want to see the sequence of events that fire between a DataGridView and the BindingSource during various databinding actions.

A: You could use reflection, but it's going to be slightly tricky because of the various event handler signatures involved. Basically you'd have to get the EventInfo for each event in the type, and use the EventHandlerType property to work out what delegate type to create before calling AddEventHandler. Delegate.CreateDelegate works for everything that follows the normal event handler pattern though...
Here's a sample app. Note that it's not doing any checking - if you give it something with a "non-standard" event it will throw an exception. You could fairly easily use reflection to print out the event args too.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;

namespace ConsoleApp
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Form form = new Form { Size = new Size(400, 200) };
            Button button = new Button { Text = "Click me" };
            form.Controls.Add(button);
            EventSubscriber.SubscribeAll(button);
            Application.Run(form);
        }
    }

    class EventSubscriber
    {
        private static readonly MethodInfo HandleMethod =
            typeof(EventSubscriber)
                .GetMethod("HandleEvent",
                           BindingFlags.Instance |
                           BindingFlags.NonPublic);

        private readonly EventInfo evt;

        private EventSubscriber(EventInfo evt)
        {
            this.evt = evt;
        }

        private void HandleEvent(object sender, EventArgs args)
        {
            Console.WriteLine("Event {0} fired", evt.Name);
        }

        private void Subscribe(object target)
        {
            Delegate handler = Delegate.CreateDelegate(
                evt.EventHandlerType, this, HandleMethod);
            evt.AddEventHandler(target, handler);
        }

        public static void SubscribeAll(object target)
        {
            foreach (EventInfo evt in target.GetType().GetEvents())
            {
                EventSubscriber subscriber = new EventSubscriber(evt);
                subscriber.Subscribe(target);
            }
        }
    }
}

A: I think you could use Reflection to do this.

A: This cannot be done.  If you use Reflector to view a lot of the Framework's classes you'll find a common pattern when firing events:
// fire event
if (EventDelegate != null)
   EventDelegate(eventArgs);

So the event is not even fired if no one is subscribing to it


text:
Q: Setting the linear velocity of a physics object from an external module in Corona SDK I am working on a classic RPG and need some help with joystick based movement.  The player should be able to move the character in any direction with a circular pad that he moves with his thumb.  This should be familiar from FPS games where a pad controls the left/right and forward/backward movement of the character.  My code for constructing the character is this:
    local player = {}
    local player_mt = { __index = player }

    function player.new( --[[ parameters for player instance ]]-- )
      local newPlayer = { --[[ player attributes here ]]-- }

      newPlayer.image = display.newImage("testImage.png")

      physics.addBody( newPlayer.image, "kinematic" )

      return setmetatable( newPlayer, player_mt )
    end

And this is the function for moving the character (still in the same .lua file):
    function player:startMoving( xMotion, yMotion)
      self:setLinearVelocity( xMotion*player.speedModifier, yMotion*player.speedModifier)
    end

Now in my main.lua file where I am testing out all of my functions, I initialize a new player, create a circle for the joystick, add a touch event listener to it, and use that to call my move function:
    local physics = require("physics")
    physics.start()

    local player = require("player")

    local myPlayer = player.new( --[[player params]]-- )

    myControl = display.newCircle( 300, 300, 100 )
    myControl:setFillColor( 100, 100, 100 )
    myControl:addEventListener( "touch", controlCharacter )

    function controlCharacter( event )
      if( event.phase == "began" ) then
        x = myControl.x
        y = myControl.y
      elseif( event.phase == "moved" ) then
        myControl.x = event.x
        myControl.y = event.y
        myPlayer:startMoving( myControl.x - event.x, myControl.y - event.y )
      elseif( event.phase == "ended" ) then
        myControl.x = x
        myControl.y = y
      end
    end

When I run this, I get the following error:  attempt to call method 'setLinearVelocity' (a nil value).  It's like it doesn't recognize the player as a physics object, but if I change the player physics object type in the player.lua file to dynamic,
    physics.addBody( newPlayer.image, "kinematic" )  ___
                                                        |
    physics.addBody( newPlayer.image, "dynamic" )    <--

then the gravity function operates fine, it falls right off the screen.  Can anyone help me with what's going on here?

A: OK, I got the answer to my question.  When I initialized the player's image as a physics object, I initialized it as newPlayer.image, so when I set the linear velocity, I needed to put
    self.image:setLinearVelocity

instead of
    self:setLinearVelocity

since self.image, not self, is the physics object.


text:
Q: Failed to load dartium when running test I'm running dart test using test library.
pub run test -p dartium

When this command is executed I'm getting below error, I have dartium and dart sdk downloaded and in system path.
Failed to start Dartium: No such file or directory
  Command: dartium --user-data-dir=/tmp/dart_test_cwDGGO

A: I was missing symlink. After adding symlink tests are working.
ln -s /path/to/chrome /path/to/dartium

where /path/to/chrome is your chrome executable from dartium directory


text:
Q: Sending messages to incoming edges in giraph Is there any way to send messages to incoming edges in giraph?
Or, Is there any way to send messages through any particular edge(type or label etc.,)  instead of sending messages to all outgoing edges?

A: So to first clarify - Edges don't limit you on how you are allowed to send messages. You can send messages in giraph to any node, as long as you know its ID. Edges are there to create a structure of the graph and give the nodes a set of neighbours so you can start up the communication.
You also cannot search for Edges or Nodes. I'm not sure if you can access an edge, from a node which isn't the source, but you for sure cannot simply search for an edge with a label (unless you implement such an algorithm yourself). You also cannot search for nodes (unless you again implemented the algorithm), but need to know the id of the node.
So if you want to send messages to all incoming nodes which have edges pointing at you and you don't know their IDs, you'll first need to send a message to all nodes at which you have an edge pointing and in the next superstep all nodes should reply to the sources of those messages. To be able to do this, you'll also need to modify your Message Data-Type to hold additionally to the information, the ID of the node sending the message.


text:
Q: LessCss - extending css on the fly I am aware of that you can declare a class :
.someclass { ... }

And then extend it
.otherclass { &:extend(.someclass all) }

But does the .someclass really has to be declared ?
In my case only callers will apply the logic and there is no need for someclass to have the logic declared as well, as it is only a placeholder for similar css.
It would be nice if there was a &:extend(groupingFunction all) .
But maybe there is already?

A: Currently Less don't support this "placeholder-equivalent".
Checkout this issue: :extend mixins.
You can use the "@import (reference)" feature to somewhat "simulate" this behavior but it can cause unexpected problems in some cases (there are quite a few issues about the import reference feature).


text:
Q: ASP.Net MVC 5 – Cookie not stored I'm trying to implement a global exception handling in my MVC 5 application.
To  achieve that I've added a handler to the Application_Error event in Global.asax.cs.
In my handler, I read the error details from the Server GetLastError.
I store the error details in a cookie and do a redirect to an error controller which reads the cookie and displays the error details to the user.
The cookie gets set correctly, but when I try to read it in my error controller, the cookie does not exist.
This is my code:
protected void Application_Error( Object sender, EventArgs e )
{
    const String route = "Default";
    const String controller = "Errors";
    const String area = "";
    var action = "InternalServerError";
    var errorCode = 500;

    try
    {
        // Get the previous exception.
        var exception = Server.GetLastError() ?? new HttpException( (Int32) HttpStatusCode.InternalServerError, "Unknown internal server error occurred." );
        // Clear the exception
        Server.ClearError();
        // Bypass IIS custom errors
        Response.TrySkipIisCustomErrors = true;

        // Check for HTTP code
        var httpException = exception as HttpException;
        if ( httpException != null )
            errorCode = httpException.GetHttpCode();

        // ReSharper disable once SwitchStatementMissingSomeCases
        switch ( errorCode )
        {
            case 401:
            case 403:
                action = "Forbidden";
                break;
            case 404:
                action = "NotFound";
                break;
        }

        // Try to collect some error details
        try
        {
            var details = new WebErrorDetails
            {
                Exception = exception,
                ErrorSource = HttpContext.Current.Request.Url.ToString()
            };

            HttpContext.Current.Response.Cookies.Set(new HttpCookie(CommonConstants.ErrorDetails, JsonConvert.SerializeObject(details))
            {
                Expires = DateTime.Now.Add(2.ToMinutes()),
                HttpOnly = true
            });
        }
        catch
        {
            // ignore
        }

        Response.RedirectToRoute( route, new RouteValueDictionary( new { area, controller, action } ) );
    }
    catch
    {
        Response.RedirectToRoute( route, new RouteValueDictionary( new { area, controller, action = "InternalServerError" } ) );
    }
}

public class ErrorsController : ControllerBase
{
    #region Ctor

    /// <summary>
    ///     Initialize a new instance of the <see cref="ErrorsController" /> class.
    /// </summary>
    /// <param name="loggerFactory">A <see cref="ILoggerFactory" />.</param>
    public ErrorsController( ILoggerFactory loggerFactory )
        : base( loggerFactory.CreateLogger( typeof(ErrorsController) ) )
    {
        Logger.Trace( "Enter." );
    }

    #endregion

    #region Private Members

    [NotNull]
    private WebErrorDetails PopErrorDetails()
    {
        try
        {
            // GetRequestCookie looks like this => HttpContext.Current.Request.Cookies[cookieName];
            var cookie = HttpContextService.GetRequestCookie( CommonConstants.ErrorDetails );
            if ( cookie != null )
            {
                var errorDetails = JsonConvert.DeserializeObject<WebErrorDetails>( cookie.Value );
                if ( errorDetails != null )
                    return errorDetails;
            }
        }
        catch ( Exception ex )
        {
            Logger.Warn( ex, "Failed to pop error details." );
        }

        // Fall-back value
        return new WebErrorDetails
        {
            Exception = new Exception( "Exception details missing." ),
            ErrorSource = "-"
        };
    }

    private void StoreErrorDetails( WebErrorDetails errorDetails )
    {
        try
        {
            HttpContextService.AddCookieToResponse( new HttpCookie( CommonConstants.ErrorDetails, JsonConvert.SerializeObject( errorDetails ) )
                                                    {
                                                        Expires = DateTime.Now.Add( 2.ToMinutes() ),
                                                        HttpOnly = true
                                                    } );
        }
        catch ( Exception ex )
        {
            Logger.Warn( ex, "Failed to store error details." );
        }
    }

    #endregion

    #region Action Methods

    /// <summary>
    ///     Returns a error view for 500 internal server errors.
    /// </summary>
    /// <returns>Returns a error view for 500 internal server errors.</returns>
    public async Task<ActionResult> InternalServerError()
    {
        Logger.Info( "Enter error action method." );
        WebErrorDetails errorDetails = null;
        try
        {
            errorDetails = PopErrorDetails();

            // Get the layout view model
            var layoutVm = await PrepareLayoutViewModel();

            // Build the view model
            var vm = new LayoutApplicationErrorViewModel
            {
                Exception = errorDetails.Exception,
                ErrorSource = errorDetails.ErrorSource,
                ViewTitle = CommonResources.Common_Static_InternalServerError
            };
            HttpContextService.StatusCode = (Int32) HttpStatusCode.InternalServerError;

            // Set the layout view model
            SetLayoutData( layoutVm, vm );

            return View( "Error", vm );
        }
        catch ( Exception ex )
        {
            try
            {
                Logger.Error( ex, "Unexpected exception occurred." );
                if ( errorDetails != null )
                    StoreErrorDetails( errorDetails );
                else
                    StoreErrorDetails( new WebErrorDetails
                                       {
                                           ErrorSource = HttpContextService.RequestUrl.ToString(),
                                           Exception = ex
                                       } );
            }
            catch
            {
                // ignore
            }
            return RedirectToAction( "GeneralError", "Errors" );
        }
    }

    /// <summary>
    ///     Returns a general error view without any layout.
    /// </summary>
    /// <returns>Returns a general error view without any layout.</returns>
    public ActionResult GeneralError()
    {
        Logger.Info( "Enter general error action method." );

        try
        {
            // Build the view model
            var errorDetails = PopErrorDetails();
            var vm = new LayoutApplicationErrorViewModel
            {
                Exception = errorDetails.Exception,
                ErrorSource = errorDetails.ErrorSource,
                ViewTitle = "Error"
            };
            HttpContextService.StatusCode = (Int32) HttpStatusCode.InternalServerError;

            return View( vm );
        }
        catch ( Exception ex )
        {
            Logger.Fatal( ex, "Could not display basic error view." );
        }
    }

    #endregion
}

Note: Setting and Reading cookies works everywhere else.
I assume the problem is related to the redirect?

A: //Clear the response.
Response.Clear();


text:
Q: Find out deployment type of existing ECS service The AWS doc describes three potential deployment types for a service: "ECS", "CODE_DEPLOY", and "EXTERNAL". When creating a new service you can choose between "ECS" or "CODE_DEPLOY".
I have an existing service. I checked the following places to find out its deployment type:

*

*Its definition in Terraform

*Its page in the AWS web console

*Its entry in aws ecs describe-services --cluster=my-cluster --services=my-service
Not one of them mentions anything about a deployment type, nor any of the three enum values above. I'm guessing my service has the default deployment type, and that the default deployment type is "ECS", but I haven't found anything in the docs validating this.
How can I figure out my service's deployment type?

A: I understand it is bit confusing , well deployment type is called deployment controller , so you can pass the parameter to aws cli as deploymentController , if you do not pass anything then by default it takes 'ECS' , you can find more details for aws cli in the link below and we can use same parameter in terraform as well, I have provided you an example for terraform link.
https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html#API_CreateService_RequestSyntax
resource "aws_ecs_service" "example" {
  name    = "example"
  cluster = aws_ecs_cluster.example.id

  deployment_controller {
    type = "EXTERNAL"
  }
}

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_service


text:
Q: git trying to push non-existent file ... after clearing cache I have a number of shapefiles in my repo that were too large, thereby causing my push to GitHub to fail.  I initially tried to create a .gitignore file that excludes most of the extensions in shapefile bundles.  It still tried to push the shapefiles.  After some searching, I found I had to clear the cache:
git rm -rf --cached .
git add .

However, once I tried to commit and then push again, I found that this did not fix the problem.  The same shapefile was hanging things up.  After much messing around, I abandoned the idea and decided to move all the shapefiles out of the repo.  I cleared the cache again, added back, committed, and attempted to push to GitHub.
The push failed.  The shapefile (which is no longer in the repo) was too large for a push.  How can that happen?  I feel like files that are not in the commit, because they aren't in the repo, should not be able to hang up the push.  Any thoughts on what is happening here would be most appreciated.
UPDATE: Current status of rebase options...
noop

# Rebase 133c6ec..133c6ec onto 133c6ec
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

UPDATE: Reflog >> it all starts with 'Adding many images'
133c6ec HEAD@{0}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{1}: rebase -i (start): checkout refs/remotes/origin/master
133c6ec HEAD@{2}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{3}: rebase -i (start): checkout refs/remotes/origin/master
133c6ec HEAD@{4}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{5}: rebase -i (start): checkout refs/remotes/origin/master
133c6ec HEAD@{6}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{7}: rebase -i (pick): still dealing with shp bs
0f81c71 HEAD@{8}: rebase -i (pick): Removing shapefiles
91cb472 HEAD@{9}: rebase -i (pick): Adding comments from Mullins consult - throu
83c1269 HEAD@{10}: rebase -i (pick): Adding comments from Mullins consult - thro
7677b3f HEAD@{11}: rebase -i (pick): Hopefully .gitignore is now working
97aa005 HEAD@{12}: rebase -i (pick): Adjusting gitignore
9e912cb HEAD@{13}: rebase -i (pick): Adjusting gitignore
06647c0 HEAD@{14}: rebase -i (squash): Adding many images
259d73b HEAD@{15}: rebase -i (squash): # This is a combination of 2 commits.
3b2d5e8 HEAD@{16}: rebase -i (start): checkout refs/remotes/origin/master
a585f1d HEAD@{17}: rebase: aborting
7bc98a4 HEAD@{18}: rebase -i (start): checkout refs/remotes/origin/master
a585f1d HEAD@{19}: rebase -i (finish): returning to refs/heads/master
a585f1d HEAD@{20}: rebase -i (start): checkout 9f28970
a585f1d HEAD@{21}: rebase -i (finish): returning to refs/heads/master
a585f1d HEAD@{22}: rebase -i (start): checkout refs/remotes/origin/master
:...skipping...
133c6ec HEAD@{0}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{1}: rebase -i (start): checkout refs/remotes/origin/master
133c6ec HEAD@{2}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{3}: rebase -i (start): checkout refs/remotes/origin/master
133c6ec HEAD@{4}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{5}: rebase -i (start): checkout refs/remotes/origin/master
133c6ec HEAD@{6}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{7}: rebase -i (pick): still dealing with shp bs
0f81c71 HEAD@{8}: rebase -i (pick): Removing shapefiles
91cb472 HEAD@{9}: rebase -i (pick): Adding comments from Mullins consult - throu
83c1269 HEAD@{10}: rebase -i (pick): Adding comments from Mullins consult - thro
7677b3f HEAD@{11}: rebase -i (pick): Hopefully .gitignore is now working
97aa005 HEAD@{12}: rebase -i (pick): Adjusting gitignore
9e912cb HEAD@{13}: rebase -i (pick): Adjusting gitignore
06647c0 HEAD@{14}: rebase -i (squash): Adding many images
259d73b HEAD@{15}: rebase -i (squash): # This is a combination of 2 commits.
3b2d5e8 HEAD@{16}: rebase -i (start): checkout refs/remotes/origin/master
a585f1d HEAD@{17}: rebase: aborting
7bc98a4 HEAD@{18}: rebase -i (start): checkout refs/remotes/origin/master
a585f1d HEAD@{19}: rebase -i (finish): returning to refs/heads/master
a585f1d HEAD@{20}: rebase -i (start): checkout 9f28970
a585f1d HEAD@{21}: rebase -i (finish): returning to refs/heads/master
a585f1d HEAD@{22}: rebase -i (start): checkout refs/remotes/origin/master
a585f1d HEAD@{23}: rebase: aborting
:...skipping...
133c6ec HEAD@{0}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{1}: rebase -i (start): checkout refs/remotes/origin/master
133c6ec HEAD@{2}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{3}: rebase -i (start): checkout refs/remotes/origin/master
133c6ec HEAD@{4}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{5}: rebase -i (start): checkout refs/remotes/origin/master
133c6ec HEAD@{6}: rebase -i (finish): returning to refs/heads/master
133c6ec HEAD@{7}: rebase -i (pick): still dealing with shp bs
0f81c71 HEAD@{8}: rebase -i (pick): Removing shapefiles
91cb472 HEAD@{9}: rebase -i (pick): Adding comments from Mullins consult - through rev chapter
83c1269 HEAD@{10}: rebase -i (pick): Adding comments from Mullins consult - through rev chapter
7677b3f HEAD@{11}: rebase -i (pick): Hopefully .gitignore is now working
97aa005 HEAD@{12}: rebase -i (pick): Adjusting gitignore
9e912cb HEAD@{13}: rebase -i (pick): Adjusting gitignore
06647c0 HEAD@{14}: rebase -i (squash): Adding many images
259d73b HEAD@{15}: rebase -i (squash): # This is a combination of 2 commits.
3b2d5e8 HEAD@{16}: rebase -i (start): checkout refs/remotes/origin/master
a585f1d HEAD@{17}: rebase: aborting
7bc98a4 HEAD@{18}: rebase -i (start): checkout refs/remotes/origin/master
a585f1d HEAD@{19}: rebase -i (finish): returning to refs/heads/master
a585f1d HEAD@{20}: rebase -i (start): checkout 9f28970
a585f1d HEAD@{21}: rebase -i (finish): returning to refs/heads/master
a585f1d HEAD@{22}: rebase -i (start): checkout refs/remotes/origin/master
a585f1d HEAD@{23}: rebase: aborting
eaadebf HEAD@{24}: rebase -i (pick): Adding comments from Mullins consult - through rev chapter
7bc98a4 HEAD@{25}: rebase -i (start): checkout refs/remotes/origin/master
a585f1d HEAD@{26}: commit: still dealing with shp bs
4bef02c HEAD@{27}: commit: Removing shapefiles
cc061ac HEAD@{28}: commit: Adding comments from Mullins consult - through rev chapter
21c5ab7 HEAD@{29}: commit: Adding comments from Mullins consult - through rev chapter
9f28970 HEAD@{30}: commit: Hopefully .gitignore is now working
a2bdbae HEAD@{31}: commit: Adjusting gitignore
c3e5128 HEAD@{32}: commit: Adjusting gitignore
8f8b96e HEAD@{33}: commit: Adding gitignore to avoid tracking shapefiles
0c14e14 HEAD@{34}: commit: Adding gitignore to avoid tracking shapefiles
3b2d5e8 HEAD@{35}: commit: Adding many images

A: The first thing to remember here is that git push pushes commits.  If any files happen to be included, that's purely a matter of being needed for the commits that are being pushed.
The second thing to remember is that when you do git push, your git and "their" git (a git command running on github, in this case) generally have a little talk with each other, of the form:

*

*"I have commit <SHA-1> I'd like to give you, and then I'd like you to set your branch master (or whatever other branch) to point to that SHA-1."

*"Well, I have <different SHA-1> for that branch.  Tell me what SHA-1s I need to fill in any holes between what I have and what you have."  (There's more to it than this, and it goes in a different order, but the essence is an exchange of who-has-what commit and other object IDs.)
Once they know what IDs each other has, the sender packages up "whatever is needed": this is a series of commits (possibly empty) and any entities—mainly (but not quite limited to) files—that go with those commits, that the receiver also does not already have.  In this case the sender is your git, the receiver is their git, and the package includes some large file(s).
You decided you wanted not to send the large files.  This means you must replace the commit(s) you're asking your git to send, with some new commit(s) you will ask your git to send.  If the new commit(s) do not refer to the large files, then when your git goes to send the commits, their git will not ask for the files either, and your git won't send them.
The Pro Git book has a section on "rewriting history" that covers this fairly well.  What's missing (at least if you just read the one section, there are other sections that cover this) is a diagram of what a rebase really does.
(Incidentally, your git repo will still contain the large files, and will continue to do so until all references to those files are gone, including the sort of ghost references that linger in git's "reflogs" after history-rewrite operations.  It's these lingering ghosts that allow you to resurrect files if you make a mistake during the history rewrite.  Reflog entries persist for 30 days by default, for these entries at least—"more active" reflog entries persist for 90 days by default—but unless you're doing something unusual you can normally just let them expire on their own.)

The git rebase documentation has some diagrams, such as this one:
                 A---B---C topic
                /
           D---E---F---G master

[becoming]

                         A'--B'--C' topic
                        /
           D---E---F---G master

The individual letters stand for commits, and the reason this has A' instead of A, and so on, after the rebase, is that rebase doesn't—can't—actually move a commit, it can only make a copy.  The original commits are still in there, they just don't have a label like topic keeping them visible.  If the copies are different—and they are—then they have a new, different SHA-1.  It's the SHA-1s that really matter, at least during push (and fetch).
In your case, what you want to do when rebasing is to make "deliberately flawed copies", where the originals have the large files, and the "flawed" copies don't.  (In fact, of course, it's "having the large file" that is the flaw, so the not-quite-perfect-copy copies are the right ones, it's the originals that are wrong!)
Interactive rebase has the additional ability to "squash" a new commit into an existing commit, i.e., to take the copy it's going to make and modify it based on the next commit in the sequence.
The other big difference between what you want to do, and what is in the diagram above, is that you want the new commit(s) to start from the same point as the originals:
        H - I   <-- master [in your repo]
       /
... - G     <-- origin/master [i.e., what's on github as master]

Here commit H might be the flawed one with the extra file(s), and I might be the commit that removes the extra files.  If you ask to push your master to github and have github set that as its master, your git and their git will chat and decide that github needs H and I and some files—including, because of H, the big ones.
If you rewrite your own history so that in place of H and I you have one single new H'I' commit—let's just call this J for simplicity—then you'll have this diagram instead:
        H - I   [abandoned ghosts]
       /
... - G     <-- origin/master [i.e., what's on github as master]
       \
        J   <-- master

Now you can have your git call up github's git and propose sending just J, which does not have the big files in it.
Note that there are two keys to all of this:

*

*Commit G (as pointed-to by origin/master) does not have the big files, but is in both your repository and the repository on github.  It's the shared starting point for the push: it's the first commit your side leaves out when pushing, because their side already has it.

*Commit J (and/or any other commits you will push) must also not have the big files.  That way, when your git talks with their git, your git will decide that what it needs to send does not include the big files.
In the end, it doesn't matter how many commits your side will send over in the push, what matters is what's in those specific commits.  You can rewrite stuff that "only you have" as often (or rarely) as you like, to however you like it.  Once you've successfully given those commits over to another repository, if you "rewrite" them to new slightly-different copies, the other repo still has the originals and other users may have gotten them as well (if that other repository is generally accessible).
(You can still "rewrite history" and use a --force push to ask the other repo to discard some commit(s), including originals that you've decided are bad.  There's nothing inherently wrong with this either, it's just that anyone collaborating with you may have picked up those "wrong originals" and they may be using them, so you're making more work for those people too.)

One last note, on the fact that git rebase -i is showing an empty list: this suggests you've actually removed all the commits you had that they didn't.  That is, instead of going from:
        H - I  <-- master
       /
... - G      <-- origin/master

to:
        J    <-- master
       /
... - G      <-- origin/master

you've somehow simply discarded H and I entirely, so that your master points to commit G too.
This could happen if you did a rebase -i and told git to squash I into H, and it did, and the result was exactly the same files as are in commit G.  (For instance, if the only difference from G to H is "add big-file" and the only difference from H to I is "remove big-file", the combination of the two has no difference from G.)  Git does allow an "empty" commit—a commit with author, message, etc., as usual, but with the same tree as the previous commit—but by default, rebase assumes you don't want that: it just strips out the canceled-out commits entirely.
If you did have other commits that have vanished, those "ghost commits" I mentioned earlier are just what you need.  To find them, look in the "reflogs":
$ git reflog

and:
$ git reflog master

These reflogs keep a history of where HEAD and master (or any other branch) have pointed over the last up-to-90-days: the raw SHA-1 IDs of both commits, whether they're regular commits that will stick around forever, or lingering ghost commits retained only by the reflog entries.


text:
Q: Get file name in a perticular cell Is there any way that using a VBA we can run a window select a file and when we click it the name should get copied without its extension (.txt) and should get copied to sheet "TEXT", cell AZ2.
I started with some code but its not working. Not sure how to do further.
Sub Main_Macro()
Dim fName As String, LastRowim As Long

fName = Application.GetOpenFilename("Text Files (*.txt), *.adt")
If fName = "False" Then Exit Sub

End Sub

A: try GetBaseName() method to get the name of file without extension.

A: How about something like this:
Sub foo()
    Dim fd As FileDialog
    Dim fName As String  ' Includes full path
    Dim fChosen As Integer
    Dim fNameFile As String  'Only the name of the file

    Set fd = Application.FileDialog(msoFileDialogFilePicker) 'open dialog box
            fd.Title = "Please select file" 'dialog Title
            fd.InitialFileName = "C:\Users\" 'Path to initiate Dialog box
            'fd.InitialFileName = ThisWorkbook.Path & "\" 'alternate initial path
            fChosen = fd.Show
                    fd.Filters.Clear
                    'fd.Filters.Add "CSV files", "*.csv" 'add filters to only show this type of file
                    fd.Filters.Add "Text files", "*.txt" 'in this case only txt files will be selectable

         If fChosen <> -1 Then
             MsgBox "You Cancelled, nothing done!", vbInformation
         Else
            fName = Right$(fd.SelectedItems(1), Len(fd.SelectedItems(1)) - InStrRev(fd.SelectedItems(1), "\")) 'get full path of file, then remove anything prior to \ to get filename
            Position = InStr(fName, ".") 'get the position of the extension
            If Position > 0 Then Extension = Right(fName, Len(fName) - Position + 1) 'get the actual extension of the file
            fName = Replace(fName, Extension, "") 'remove that extenstion
            Sheets("TEXT").Range("AZ2").Value = fName 'enter the file name to your chosen range
        End If
End Sub


text:
Q: How to covert alpha Image into 8 bit depth in iOS I want to covert an image into 8 bit when I pick the image from the gallery or camera. Here is the code I have to tried. The below code is working without the alpha channel. If the image has an alpha, it's not working. And when I am picking an image from the camera there is some alpha value present so it throws an exception.
CGImageRef c = [[UIImage imageNamed:@"100_3077"] CGImage];
size_t bitsPerPixel = CGImageGetBitsPerPixel(c);
size_t bitsPerComponent = CGImageGetBitsPerComponent(c);
size_t width = CGImageGetWidth(c);
size_t height = CGImageGetHeight(c);

CGImageAlphaInfo a = CGImageGetAlphaInfo(c);

NSAssert(bitsPerPixel == 32 && bitsPerComponent == 8 && a == kCGImageAlphaNoneSkipLast, @"unsupported image type supplied");

CGContextRef targetImage = CGBitmapContextCreate(NULL, width, height, 8, 1 * CGImageGetWidth(c), CGColorSpaceCreateDeviceGray(), kCGImageAlphaNone);

UInt32 *sourceData = (UInt32*)[((__bridge_transfer NSData*) CGDataProviderCopyData(CGImageGetDataProvider(c))) bytes];
UInt32 *sourceDataPtr;

UInt8 *targetData = CGBitmapContextGetData(targetImage);

UInt8 r,g,b;
uint offset;
for (uint y = 0; y < height; y++)
{
    for (uint x = 0; x < width; x++)
    {
        offset = y * width + x;

        if (offset+2 < width * height)
        {
            sourceDataPtr = &sourceData[y * width + x];

            r = sourceDataPtr[0+0];
            g = sourceDataPtr[0+1];
            b = sourceDataPtr[0+2];

            targetData[y * width + x] = (r+g+b) / 3;
        }
    }
}

CGImageRef newImageRef = CGBitmapContextCreateImage(targetImage);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

I have tried this code. This code only converts an image into 8 bit when image CGImageAlphaInfo property is equal to kCGImageAlphaNoneSkipLast.


text:
Q: How can I create a site in php and have it generate a static version? For a particular project I have, no server side code is allowed. How can I create the web site in php (with includes, conditionals, etc) and then have that converted into a static html site that I can give to the client?
Update: Thanks to everyone who suggested wget. That's what I used. I should have specified that I was on a PC, so I grabbed the windows version from here: http://gnuwin32.sourceforge.net/packages/wget.htm.

A: If you have a Linux system available to you use wget:
wget -k -K  -E -r -l 10 -p -N -F -nH http://website.com/

Options

*

*-k : convert links to relative

*-K : keep an original versions of files without the conversions made by wget

*-E : rename html files to .html (if they don't already have an htm(l) extension)

*-r : recursive… of course we want to make a recursive copy

*-l 10 : the maximum level of recursion. if you have a really big website you may need to put a higher number, but 10 levels should be enough.

*-p : download all necessary files for each page (css, js, images)

*-N : Turn on time-stamping.

*-F : When input is read from a file, force it to be treated as an HTML file.

*-nH : By default, wget put files in a directory named after the site's hostname. This will disabled creating of those hostname directories and put everything in the current directory.

Source: Jean-Pascal Houde's weblog

A: build your site, then use a mirroring tool like wget or lwp-mirror to grab a static copy

A: I have done this in the past by adding:
ob_start();

In the top of the pages and then in the footer:
$page_html = ob_get_contents();
ob_end_clean();
file_put_contents($path_where_to_save_files . $_SERVER['PHP_SELF'], $page_html);

You might want to convert .php extensions to .html before baking the HTML into the files.
If you need to generate multiple pages with variables one quite easy option is to append the filename with md5sum of all GET variables, you just need to change them in the HTML too. So you can convert:
somepage.php?var1=hello&var2=hullo

to
somepage_e7537aacdbba8ad3ff309b3de1da69e1.html

ugly but works.
Sometimes you can use PHP to generate javascript to emulate some features, but that cannot be automated very easily.

A: Create the site as normal, then use spidering software to generate a HTML copy.
HTTrack is software I have used before.

A: One way to do this is to create the site in PHP as normal, and have a script actually grab the webpages (through HTTP - you can use wget or write another php script that just uses file() with URLs) and save them to the public website locations when you are "done".  Then you can just run the script again when you decide to change the pages again.  This method is quite useful when you have a slowly changing database and lots of traffic, as you can eliminate all SQL queries on the live site.

A: If you use modx it has a built in function to export static files.

A: If you have a number of pages, with all sorts of request variables and whatnot, probably one of the spidering tools the other commenters have mentioned (wget, lwp-mirror, etc) would be the easiest and most robust solution.
However, if the number of pages you need to get is low, or at least manageable, you've got a few options which don't require any third party tools (not that you should discount them JUSt because they are third party).

*

*You can use php on the command line to get it to output directly into a file.
php myFile.php > myFile.html
Using this method could get painful (though you could put it all into a shell script), and it doesn't allow you to pass variables in the same way (eg: php myFile.php?abc=1 won't work).

*You could use another PHP file as a "build" script which contains a list of all the URLs you want and then grabs them via file_get_contents() or file() and writes them to a local file. Using this method, you can also get it to check if the file has changed (md5_file() should work for that), so you'll know what to give your client, should they only want updates.

*Further to #2, before you write the output to file, scan it for local urls and then add those to your list of files to download. While you're there, change those urls to link to what you'll eventually name your output so you have a functioning web at the end. Note of caution here - if this is sounding good, you could probably use one of the tools which already exist and do this for you.

A: Alternatively to wget you could use (Win|Web)HTTrack (Website) to grab the static page. HTTrack even corrects links to files and documents to match the static output.

A: You can use python or visual basic (or your choice) to create your static files all at once then upload them.
For a project with 11 million business listings in excel files I used VBA to extract the spreadsheet data into 11 mil small .php files, then zipped, ftp'd, unzipped.
https://contactlookup.us
Voila - a super fast business directory
I started with Jekyll, but after about half million entries the generator got bogged down. For 11 million it looked like it would finalize the build in about 2 months!

A: I do it on my own web site for certain pages that are guaranteed not to change -- I simply run a shell script that could be boiled to (warning: bash pseudocode):
find site_folder -name \*.static.php -print -exec Staticize {} \;

with Staticize being:
# This replaces .static.php with .html
TARGET_NAME="`dirname "$1"`/"`basename "$1" .static.php`".html
php "$1" > "$TARGET_NAME"

A: wget is probably the most complete method. If you don't have access to that, and you have a template based layout, you may want to look into using Savant 3. I recommend Savant 3 highly over other template systems like Smarty.
Savant is very light weight and uses PHP as the template language, not some proprietary sublanguage. The command you would want to look up is fetch(), which will "compile" your template and place it in a variable that you can output.
http://www.phpsavant.com/


text:
Q: YouTube API - Historical Video Views on Channel I need to extract the activity on a company YouTube channel going back 5+ years.  I ran into an issue with the YouTube Analytics API as it is limiting me to the last 30 days of activity.  I am thinking of trying the YouTube Data API V3 next, but want to first ask here if anyone knows how to pull the deep historical data from a YouTube channel.   I am interested primarily in the number of views per video per day.  I am using Google Cloud Platform and need to store the data in BigQuery.
https://developers.google.com/youtube/analytics/reference
https://developers.google.com/youtube/v3/docs
Thanks,
Steve

A: As YouTube APIs don't provide this basic feature, I would recommend you to try on your own to get the data your are looking for:
By requesting the YouTube studio Video analytics webpage of a video interesting you:
https://studio.youtube.com/video/VIDEO_ID/analytics
Below the Views chart, click on SEE MORE.
Then open your web browser Network tab (using Ctrl + Shift + E). Make sure to filter XHR requests.
Then select Since uploaded (lifetime) for the time range.
You should be able to see a request to join endpoint, copy it as cURL by right-clicking it.
To use this request for another given video, think about modifying the video id of the JSON --data-raw argument at /nodes/1/value/query/restricts/0/inValues and to also modify /nodes/1/value/query/timeRange/dateIdRange/inclusiveStart to the upload date of the video (retrievable with YouTube Data API v3) in the format yyyymmdd.

A: Youtube Data API will only give you the current numbers from the channel/videos, not the historical data. For that you will need to use the Analytics API.
In order to get the full data for each video you will need to hit the analytics reports query and use filters and parameters to get the data you need. Specifically for what you mentioned in the question, take a look in the startDate and endDate parameters and use the day dimension to aggregate the data. You will also need to use the videoId to filter the data (and to get a list of video_ids you can use the data API).
I am currently getting data for the last 5+ years. Just an example here by getting 2017 information:


text:
Q: Update not wrapped in act(...) and the mock function not firing. react-testing-library, jest I would love some help on this.  I've been working on it for too long to deem not asking a question.
Thank you in advance for your time and attention,
I have scoured the internet and tried many things but I am still having no luck - here's the issue.
All in all - I am following along with
https://kentcdodds.com/blog/fix-the-not-wrapped-in-act-warning
Using react-testing-library in tandem with jest - and running into two issues

*

*Warning: An update to Login inside a test was not wrapped in
act(...).

*Jest isn't picking up that the mock is being called

I really think I have everything wired up correctly - unsure what I am missing.
Inside the mock I can put a console.log and can confirm that the mock is indeed being called.
/*
  Test
*/
it('should call props.fetchSignIn with the username and password', async () => {
  const promise = Promise.resolve({
    email: 'test@circulate.social',
    firstName: 'Mike',
    lastName: 'A',
  });
  const fetchSignIn = jest.fn(() => promise);
  const { queryByTestId, queryByPlaceholderText } = renderLogin({
    fetchSignIn,
  });
  const emailInput = queryByPlaceholderText('joedoe@gmail.com');
  const passwordInput = queryByPlaceholderText('password');
  const submitButton = queryByTestId('submitButton');

  fireEvent.change(emailInput, {
    target: { value: 'mike@circulate.social' },
  });
  fireEvent.change(passwordInput, { target: { value: 'Password1!' } });

  fireEvent.click(submitButton);

  // I expected this to fail from the parameters being wrong
  expect(fetchSignIn).toHaveBeenCalledWith('asf');

  await act(() => promise);
});

/*
  Functional Component using the `useState(...)` hooks
  onFormFinished is the form `onSubmit` handler
*/
  const handleSignIn = async (
    email: string,
    password: string
  ): Promise<UserContextType['user']> => {
    setIsLoginInFlight(true);
    try {
      const result = await props.fetchSignIn(email, password);
      setIsLoginInFlight(false);
      return result;
    } catch (error) {
      // Other logic removed
  };

  const onFormFinish = async (values: FormValues): Promise<void> => {
    const { email, password } = values;
    const signInResult = await handleSignIn(email, password);

    // Other logic removed
  };

Two things are happening
1 - That warning
2 - Test is failing because fetchSignIn was never called
What is expected
The test to fail due to fetchSignIn being called, but the parameters being wrong
Any input or ask for clarification is welcome.
Thank you

A: Let's address your second problem first.

Jest isn't picking up that the mock is being called

I find it is tricky as well to get test running with ant design forms. After some digging and experiments, it seems simulating 'click' doesn't trigger the onFinish, but instead, simulating 'submit' does. Imaging the following example using Jest and Enzyme:
export default MyForm = () => {
    <Form onFinish={onFinish}>
       <Form.Item>
         <Button htmlType='submit'>Submit</Button>
       </Form.Item>
    </Form>
}

it('should trigger onFinish if submit', () => {
   const onFinish = jest.fn();
   const wrapper = mount(<MyForm onFinish={onFinish}/>);
   wrapper.find('button').simulate('submit');
   await sleep(200)
   expect(onFinish).toHaveBeenCalled();
})

Myself is also struggling with the first issue:

Warning: An update to Login inside a test was not wrapped in act(...)

Note that this will only happen if there is validation error because there is internal state change in their implementation of the Form.
First of all, this is a warning meaning that you can ignore it if you don't mind the log to be polluted.
Secondly, this is a warning only when it is 'development' but not 'production'.
If you indeed want to make it disappear, this is the "hacky" way (I don't know if there is better way) I am taking:
it('should trigger onFinish if submit', () => {
   const onFinish = jest.fn();
   const wrapper = mount(<MyForm onFinish={onFinish}/>);
   await act(async () => {
     wrapper.find('button').simulate('submit');
   })
   await sleep(200)
   wrapper.update()
   // check errors here
   expect(onFinish).not.toHaveBeenCalled();
})

This is officially documented here: https://github.com/enzymejs/enzyme

A: I had some trouble too submitting forms with Ant Design 4 + react-testing-library. After some experimentation I ended with always using data-testid to submit forms :
<Button data-testid="submit" htmlType="submit">Submit</>

// Form element has onFinish attribute

// in test
fireEvent.click(rtl.getByTestId("submit"));
expect(...);

This is not what RTL promotes (datat-testid should be avoided, test as a real user would) but I can live with that.
But according to https://github.com/ant-design/ant-design/issues/21272 firing a submit event should work too, I will definitely give a try.

A: Bordering on comedic, and definitely NOT the proper way to solve the problem.  But A way to solve the problem - the only one that worked for me besides avoiding using onFinish entirely and relying on onClick on the button.
So what did the trick is actually wrapping the expect(...) in a setTimeout(...)
      // click || submit - both seemed to work for me
      fireEvent.submit(submitButton);
      setTimeout(() => {
        expect(fetchSignIn).toHaveBeenCalledWith('asf');
      });

    it('should call props.fetchSignIn with the username and password', async () => {
      const promise = Promise.resolve({
        email: 'test@circulate.social',
        firstName: 'Mike',
        lastName: 'A',
      });
      const fetchSignIn = jest.fn(() => promise);
      const { queryByTestId, queryByPlaceholderText } = renderLogin({
        seedEmail: 'aasdf',
        seedPassword: 'asdf',
        fetchSignIn,
      });
      const emailInput = queryByPlaceholderText('joedoe@gmail.com');
      const passwordInput = queryByPlaceholderText('password');
      const submitButton = queryByTestId('submitButton');

      fireEvent.change(emailInput, {
        target: { value: 'mike@circulate.social' },
      });
      fireEvent.change(passwordInput, { target: { value: 'Password1!' } });

      // click || submit - both seemed to work for me
      fireEvent.submit(submitButton);
      setTimeout(() => {
        expect(fetchSignIn).toHaveBeenCalledWith('asf');
      });

      await act(() => promise);
    });

This was brought up to me by someone on the GitHub issue
https://github.com/ant-design/ant-design/issues/21272#issuecomment-628607141 so shoutout to @ildarnm on GH


text:
Q: R Indexing, Matrix multiplication I seem to have a misunderstanding about memory usage when using a subset of a matrix in R.  I came across when I tried to program a cross validation function, but I think the problem is more general.  I have cooked up a small example below.
# parameters
n <- 1e6 # the real data are much bigger, but this will do
m <- 50
nfolds <- 10
X <- matrix(rnorm(n*m,0,1),nrow=n,ncol=m)
y <- rnorm(n,0,1)
mse <- rep(0,nfolds)
foldid <- sample(rep(seq(nfolds), length = n))

# produces big spikes in memory
for (i in (1:nfolds)) {
  which <- foldid == i
  xpx <- crossprod(X[!which,])
  xpy <- crossprod(X[!which,],y[!which])
  b <- solve(xpx,xpy)
  mse[i] <- mean((y[which] - X[which,] %*% b)**2)
}

# does not produce spikes in memory usage
for (i in (1:nfolds)) {
  xpx <- crossprod(X)
  xpy <- crossprod(X,y)
  b <- solve(xpx,xpy)
  mse[i] <- mean((y - X %*% b)**2)
}

I don't understand why the first loop produces big upward spikes in memory usage, whereas the second loop doesn't although a strictly larger matrix is multiplied.

A: Let's compare the first lines withing the loops.
First, the simple crossprod:
xpx <- crossprod(X)

Without subsetting, you work with matrices X (already existing 400 MB) and xpx (small).
Second, with subsetting:
xpx <- crossprod(X[!which,])

Here you work with X, temporary matrix X[!which,], and xpx. The additional matrix X[!which,] requires additional 360 MB of memory.
object.size(X[!which,])
# 360000200 bytes

R has relatively poor memory managment, so the temporary matrix may not be discarded for some time.


text:
Q: Capture previous value of the columns I have a table called Application which has information about applications.
 AppID      AppName     AppGroup     AppLocation     TeamSize    GrpSize
  1         Nestle        Food           UK             6            12
  2         RedBull       Drink          USA            5            15
  3          Ford        Vehicle         USA            9            25

Now when I update any rows in this Application table I want to capture the values to another table called AuditTable. Also I need to capture the previous values of TeamSize and GroupSize to that table too.
For ex: When I update the first row then the below Audit Table values should be populted as shown below.
Audit Table:
But Audit table doesn't have OldTeamSize and OldGroupSize columns.
AppID   AppName   AppGroup  AppLocation OldTeamSize NewTeamSize OldGrpSize NewGrpSize
  1      Nestle    Food       UK            6            3          12          8

I am trying to achive this in asp.net c#. Really appreciate any suggestions or thoughts.

A: You can do this in two ways. You can insert into you AuditTable first before updating or use an update trigger.
Example 1: Insert then update
INSERT INTO dbo.AuditTable(Column1, Column2,...)
SELECT Column1, Column2, ... FROM dbo.Application WHERE (A filter you'll use when updating)

UPDATE dbo.Application
SET Column1 = NewColumn1Value,
    Column2 = NewColumn2Value
WHERE (Your filter)

Example 2: Trigger
//Google how to write the update trigger
Note: It always best to provide a code snippet of what you've tried.

A: It's unclear which DBMS you are using, but I'd definitely consider triggers.
For MSSQL Server, you can create trigger, something like:
CREATE TRIGGER TriggerName
ON Table_Name
AFTER UPDATE
AS
BEGIN
...
..
END

Inside the trigger body, use "inserted" dataset to get new values and "deleted" to get old values. For example, you can store OldGrpSize into variable using:
declare @OldGrpSize int = (select OldGrpSize from deleted)

Once you get old and new values, you just need one INSERT statement to store data into Log table.
Sure, you can use .NET and C#, but I believe it's much easier to do that with DB triggers. In this case, if you use triggers it's more safe, it's faster (less client-server communication) and it's easier for maintenance.


text:
Q: python3 greek letters not showing properly I develope a small python program in my rasp zero with lcd touch screen.
Short story:my rasp has attached with a lcd touch screen and a barcode scanner. When someone pass the card from the scanner the programm send the barcode to my mssql server and ask the info. The result are words (lastname and firstname) with greek characters.
BUT the data I get from cursor are not showing properly
#!/usr/bin/python3
# -*- coding: utf-8 -*-
....some code........
print("Barcode found")
for row in result:
    last_name = row[1].encode('utf-8')
    print('Last Name: ' + str(last_name))
    first_name = row[2]
    print('First Name: ' + str(first_name))

as result in print function I get
Last Name: b'\xff\xfe\xcd\x00\xd4\x00\xc1\x00\xcd\x00\xcf\x00\xd3\x00'
First Name: ÄÁÕÉÄ-ÂÁÓÉËÅÉÏÓ

and the desire output is:
Last Name: ΝΤΑΝΟΣ
First Name: ΔΑΥΙΔ-ΒΑΣΙΛΕΙΟΣ

Any ideas? I can't understant exactly the principle of decoding or encoding.
Thnx in advance.


text:
Q: Javascript: Access function within deep object on parse I have an object

var object1 = {
  object2: {
    function1: function(a, b, c, d, e) {
      //do some stuff with those parameters
      console.log('values are ' + a + ' ' + b + ' ' + c + ' ' + d);
    },
    function2: object1.object2.function1(2, 3, 4, 5)
  }
}

Why the line function2: object1.object2.function1(2, 3, 4, 5) line throws Uncaught TypeError: Cannot read property 'object2' of undefined and how can I make that work?
UPDATE: the answer is marked.
Thank you

A: Because scope in which function2 is defined does not contain definition of object1. Then when you try to access object1.object2 it throws error because object1 is not defined

A: Following would work:

var object1 = {
  object2: {
    function1: function(a, b, c, d, e) {
      //do some stuff with those parameters
      console.log('values are ' + a + ' ' + b + ' ' + c + ' ' + d);
    },
    function2: function(a, b, c, d, e) {
        object1.object2.function1(2, 3, 4, 5);
    }
  }
}
object1.object2.function2();

Basically at the time that you want to call object1 it does not yet exist. This is the reason you get this error. I just delayed this, by inserting it to a function and explicitly calling it later.
Note that javascript does no parameter checks, just fails if they mismatch.

A: var object1 = {
    object2: {
        function1: function (a, b, c, d, e) {
            //do some stuff with those parameters
            console.log('values are ' + a + ' ' + b + ' ' + c + ' ' + d);
        },
        function2: function () { this.function1(2, 3, 4, 5); return this; }
    }.function2()
}
object1.object2.function1(9, 8, 7, 6, 5);

A: If you want function2 as shorthand for function1 called with predefined arguments, you might use bind:
object1.object2.function2 = object1.object2.function1.bind(null, 2, 3, 4, 5)

if you need context, replace the null for object1.object2


text:
Q: Find screen position of a form embedded in a form, embedded in a form, I find myself in a tricky situation here, I have an application that has a form embedded in a form, embedded in a form, embedded in a form... (you got the picture).
I'm trying to find the middle of one of the forms (that was easy (Self.Width div 2) and (Self.Height div 2), right). Then the position relative to the screen (that was easy as well (Self.Width div 2) + Self.Left and (Self.Height div 2) + Self.Top).
The problem is that this form is embedded in another form so I got
(Self.Width div 2) + Self.Left + Self.Parent.Left
and
(Self.Height div 2) + Self.Top + Self.Parent.Top
The problem is that I have 6 to 8 forms embedded in one another. I'm thinking a recursive call; the problem is that not all objects are forms, they are a mix of forms, tabs, panel, etc.
What would be an elegant way to solve it?

A: How about this one:
FUNCTION CenterOfFormAsScreenCoords(F : TForm) : TPoint;
  BEGIN
    Result:=F.ClientToScreen(Point(0,0));
    Result:=Point(Result.Left+F.Width DIV 2,Result.Top+F.Height DIV 2)
  END;

or a combined version, as suggested by  Remy Lebeau:
FUNCTION CenterOfFormAsScreenCoords(F : TForm) : TPoint;
  BEGIN
    Result:=F.ClientToScreen(Point(F.Width DIV 2,F.Height DIV 2))
  END;

and a more general version (as suggested by Craig Young):
FUNCTION GetCenterOfControlAsScreenCoords(C : TControl) : TPoint;
  BEGIN
    Result:=C.ClientToScreen(Point(C.Width DIV 2,C.Height DIV 2))
  END;

or as a CLASS HELPER:
TYPE
  TControlHelper = CLASS HELPER FOR TControl
                     FUNCTION CenterAsScreenCoords : TPoint;
                   END;

FUNCTION TControlHelper.CenterAsScreenCoords : TPoint;
  BEGIN
    Result:=ClientToScreen(Point(Width DIV 2,Height DIV 2))
  END;


text:
Q: to determine the controller, action , route name in zend framework3 in module.php I trying to get the matched route name and controller - action name, in ZF3
I want this in Module.php,
as i have tried-
public function onBootstrap(MvcEvent $e)
{
   $app = $e->getApplication();
    $em  = $app->getEventManager()->getSharedManager();
    $sm  = $app->getServiceManager();

    $routeMatch = $sm->get('Application')->getMvcEvent()->getRouteMatch();
   }

but it returns null,
Thanks in advance

A: try this-
public function onBootstrap(MvcEvent $e)
        {

            $app = $e->getApplication();
            $em  = $app->getEventManager()->getSharedManager();
            $sm  = $app->getServiceManager();
    $app->getEventManager()->attach( MvcEvent::EVENT_DISPATCH, function ($e) use ($sm){
                $routeMatch = $sm->get('Application')->getMvcEvent()->getRouteMatch();
                var_dump($routeMatch->getParams());
                var_dump($routeMatch->getMatchedRouteName());exit;
            }, 200);
    }

On bootstrap (function onBootstrap), the route is not yet prepared, so you need to get route on some events,
for Ex:(EVENT_DISPATCH, EVENT_RENDER, EVENT_ROUTE)


text:
Q: Image path inside an eclipse plugin I'm trying to refer to images inside an eclipse plugin (e.g. for icons) in the following way (from a tutorial on the eclipse FAQ website):
Bundle bundle = Platform.getBundle(PLUGIN_ID);
Path path = new Path("icons/doodledebug-icon.png");
URL fileURL = FileLocator.find(bundle, path, null);
URL resolved = null;
try {
    resolved = FileLocator.resolve(fileURL);
} catch (IOException e) {
    throw new RuntimeException(e);
}
ImageDescriptor imageDescriptor = ImageDescriptor.createFromURL(resolved);

This works fine when testing, i.e. in the runtime eclipse application. But it leads to errors when creating an update site and using this one. The path seems to be not syntactically correct:
C:\Program Files\eclipse EE indigo\file:\C:\Users\Me\.eclipse\org.eclipse.platform_3.7.0_1202875443\plugins\DoodleDebugServer-Plugin_1.0.0.201208241809.jar!\icons\doodledebug-icon.png
Why is this breaking when executed in a jar, or how should I do this correctly?

A: Assuming the icons directory is at the root level of the project, I believe you can just add a slash to the front of the path:
Path path = new Path("/icons/doodledebug-icon.png");