text:
Q: Simply disassemler with ptrace request I am trying to learn how breakpoints software works with pctrace (inserting INT3) in the code.
For this I have followed a series of examples from different sites to create a simple disassembler, and I have been doing a kind of merge with them according to what interested me.
The main code is here: https://eli.thegreenplace.net/2011/01/27/how-debuggers-work-part-2-breakpoints/
The code requires that you pass the address where you want to insert the breakpoint manually.
I am using the example: http://www.alexonlinux.com/wp-content/uploads/2008/03/sleeper.c
Then, using objdump -d, I get the address between the two prints and pass it to the disassembler.
The result I get is this:
debugger started
In debugger process 15819
In debuggie process 15820
Child started. EIP = 0xb7f41000
Original data at 0x08048429: 0xffffffff
After trap, data at 0x08048429: 0xffffffff
Time before debugger falling asleep: 1593599313

As seen, Original and After data are the same but this is wrong, After trap should be 0xffffffcc.
The prints are not printed either:
printf ("~~~~~~~~~~~~> Before breakpoint \ n");
// The breakpoint
printf ("~~~~~~~~~~~~> After breakpoint \ n")

I cannot understand why it is not replacing well, the insertion I am doing:
    / * Write the trap instruction 'int 3' into the address * /
    unsigned data_with_trap = (data & 0xFFFFFF00) | 0xCC;
    ptrace (PTRACE_POKETEXT, child_pid, (void *) addr, (void *) data_with_trap);
    // Finish Placing breakpoint ...

Does anyone see any problem whit this code?
Part of the whole code:
 void run_debugger(pid_t child_pid)
    {
        int wait_status;
        struct user_regs_struct regs;
            printf("debugger started\n");
            printf( "In debugger process %ld\n", (long)getpid() );

        wait(&wait_status);

        ptrace(PTRACE_GETREGS, child_pid, 0, &regs);
        printf("Child started. EIP = 0x%08x\n", regs.eip);

            // Placing breakpoint...
            unsigned addr = 0x8048429;
            unsigned data = ptrace(PTRACE_PEEKTEXT, child_pid, (void*)addr, 0);
            printf("Original data at 0x%08x: 0x%08x\n", addr, data);

            /* Write the trap instruction 'int 3' into the address */
            unsigned data_with_trap = (data & 0xFFFFFF00) | 0xCC;
            ptrace(PTRACE_POKETEXT, child_pid, (void*)addr, (void*)data_with_trap);
            // Finish Placing breakpoint...

        unsigned readback_data = ptrace(PTRACE_PEEKTEXT, child_pid, (void*)addr, 0);
        printf("After trap, data at 0x%08x: 0x%08x\n", addr, readback_data);

        printf( "Time before debugger falling asleep: %ld\n", (long)time( NULL ) );
        sleep( 5 );
        printf( "Time after debugger falling asleep: %ld. Resuming debuggie...\n", (long)time( NULL ) );

        ptrace(PTRACE_CONT, child_pid, 0, 0);

        wait(&wait_status);
        if (WIFSTOPPED(wait_status)) {
            printf("Child got a signal: %s\n", strsignal(WSTOPSIG(wait_status)));
        }
        else {
            perror("wait");
            return;
        }

        ptrace(PTRACE_GETREGS, child_pid, 0, &regs);
        printf("Child stopped at EIP = 0x%08x\n", regs.eip);

        /* Remove the breakpoint by restoring the previous data
        ** at the target address, and unwind the EIP back by 1 to
        ** let the CPU execute the original instruction that was
        ** there.
        */
        ptrace(PTRACE_POKETEXT, child_pid, (void*)addr, (void*)data);
        regs.eip -= 1;
        ptrace(PTRACE_SETREGS, child_pid, 0, &regs);

        /* The child can continue running now */
        ptrace(PTRACE_CONT, child_pid, 0, 0);

        wait(&wait_status);

        if (WIFEXITED(wait_status)) {
            printf("Child exited\n");
        }
        else {
            printf("Unexpected signal\n");
        }
    }

    void do_debuggie( void )
    {
            char* argv[] = { NULL };
            char* envp[] = { NULL };

            printf( "In debuggie process %ld\n", (long)getpid() );

            if (ptrace( PTRACE_TRACEME, 0, NULL, NULL ))
            {
                    perror( "ptrace" );
                    return;
            }

            execve( "sleeper", argv, envp );
    }

    int main(int argc, char** argv)
    {

        pid_t child_pid;

        if (argc < 2) {
            fprintf(stderr, "Expected a program name as argument\n");
            return -1;
        }

        child_pid = fork();
        if (child_pid == 0)
             do_debuggie();
            // argv[1];
        else if (child_pid > 0)
            run_debugger(child_pid);
        else {
            perror("fork");
            return -1;
        }

        return 0;
    }

Thank you!


text:
Q: Kubernetes - services without selector I'm struggling with Kubernetes' service without a selector. The cluster is installed on AWS with the kops. I have a deployment with 3 nginx pods exposing port 80:
apiVersion: apps/v1
kind: Deployment
metadata:
 name: ngix-dpl                 # Name of the deployment object
 labels:
   app: nginx
spec:
 replicas: 3                    # Number of instances in the deployment
 selector:                      # Selector identifies pods to be
     matchLabels:               #     part of the deployment
        app: nginx              #     by matching of the label "app"
 template:                      # Templates describes pods of the deployment
   metadata:
     labels:                    # Defines key-value map
       app: nginx               # Label to be recognized by other objects
   spec:                        #     as deployment or service
     containers:                # Lists all containers in the pod
     - name: nginx-pod          # container name
       image: nginx:1.17.4      # container docker image
       ports:
       - containerPort: 80      # port exposed by container

After creation of the deployment, I noted the IP addresses:
$ kubectl get pods -o wide | awk {'print $1" " $3" " $6'} | column -t
                                                                           NAME                       STATUS   IP
curl                       Running  100.96.6.40
ngix-dpl-7d6b8c8944-8zsgk  Running  100.96.8.53
ngix-dpl-7d6b8c8944-l4gwk  Running  100.96.6.43
ngix-dpl-7d6b8c8944-pffsg  Running  100.96.8.54

and created a service that should serve the IP addresses:
apiVersion: v1
kind: Service
metadata:
  name: dummy-svc
  labels:
    app: nginx
spec:
 ports:
    - protocol: TCP
      port: 80
      targetPort: 80
---
apiVersion: v1
kind: Endpoints
metadata:
  name: dummy-svc
subsets:
  - addresses:
    - ip: 100.96.8.53
    - ip: 100.96.6.43
    - ip: 100.96.8.54
    ports:
    - port: 80
      name: http

The service is successfully created:
$ kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
dummy-svc    ClusterIP   100.64.222.220   <none>        80/TCP    32m
kubernetes   ClusterIP   100.64.0.1       <none>        443/TCP   5d14h

Unfortunately, my attempt to connect to the nginx through the service from another pod of the same namespace  fails:
$ curl 100.64.222.220
curl: (7) Failed to connect to 100.64.222.220 port 80: Connection refused

I can successfully connect to the nginx pods directly:
$ curl 100.96.8.53
<!DOCTYPE html>
<html>
<head>
....

I noticed that my service does not have any endpoints. But I'm not sure that the manual endpoints should be shown there:
$ kubectl get svc/dummy-svc -o yaml
apiVersion: v1
kind: Service
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
       {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"nginx"},"name":"dummy-svc","namespace":"default"},"spec":{"ports":[{"port":80,"protocol":"TCP","targetPort":80}]}}
  creationTimestamp: "2019-11-22T08:41:29Z"
  labels:
    app: nginx
  name: dummy-svc
  namespace: default
  resourceVersion: "4406151"
  selfLink: /api/v1/namespaces/default/services/dummy-svc
  uid: e0aa9d01-0d03-11ea-a19c-0a7942f17bf8
spec:
  clusterIP: 100.64.222.220
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}

I understand that it is not a proper use case for services and using of a pod selector will bring it to work. But I want to understend why this configuration does not work. I don't know where to look for the solution. Any hint will be appreciated.

A: it works if you remove the "name" field from the endpoints configuration. it should look like this:
apiVersion: v1
kind: Endpoints
metadata:
  name: dummy-svc
subsets:
  - addresses:
    - ip: 172.17.0.4
    - ip: 172.17.0.5
    - ip: 172.17.0.6
    ports:
    - port: 80

A: As @iliefa mentioned in his comment above, the below part of the definition is treated as labels in this type of cases.
ports:
    - port: 80
      name: http

In your scenario, we need to either remove 'name: http' as mentioned by @iliefa or we need to add 'name: http' under 'ports:' in the service definition as you can spot below.
apiVersion: v1
kind: Service
metadata:
  name: dummy-svc
  labels:
    app: nginx
spec:
 ports:
    - protocol: TCP
      port: 80
      targetPort: 80
      name: http

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Remove a Column Article for Transaction Replication I followed the direction from the following link, How to: Define and Modify a Column Filter (Replication Transact-SQL Programming).  I currently have a setup where I'm replicating at table, Users.  We no longer want to replicate the column, SSN.  For my test, I inserted a new row into the Users table including the SSN.  I executed the following SQL statements with no errors.  After I synced the publication using the Replication Monitor, the new row didn't show up in my replicated database.  I decided to do another insert and resync.  The other row didn't show up the new one did with the missing SSN as I expected.  Is there something I did wrong?
exec  sp_articlecolumn       @publication = N'Publisher Test 01', @article = N'Users', @column = N'SSN', @operation = N'drop', @force_invalidate_snapshot = 1, @force_reinit_subscription = 1
exec  sp_articleview         @publication = N'Publisher Test 01', @article = N'Users', @change_active = 1
exec  sp_startpublication_snapshot @publication = 'Publisher Test 01'
exec  sp_reinitsubscription  @publication = N'Publisher Test 01', @article = N'Users',  @subscriber = N'TEST', @destination_db = N'Test01_Replication'


text:
Q: Can I make a transition on an SVG attribute that is not CSS? I have an SVG that I would like to transition to extend when the mouse hovers over it, and ease back to its normal size when the mouse is not hovering. Because it is not adjusted through CSS, I can't figure out how to make that transition happen.
https://codepen.io/BrendanOB/pen/LYYepQQ
^ A link to an example of what I've got so far
Im new to javascript, any help is greatly appreciated, thank you.
I have already tried CSS transform scale and matrix, without working results.
<style>
 .st2{fill:#E5CACA;}
 .st3{fill:none;stroke:#FFF;stroke-width:17;stroke-linecap:round;stroke-miterlimit:10;}
</style>

<g id="Layer_2">
   <line class="st3" x1="500" y1="142" x2="500" y2="95"/>
   <line onmouseover="bigLine()" onmouseleave="smallLine()" id="move" class="st3" x1="518.2" y1="142.9" x2="521.8" y2="96.1"/>
   <line id="stretch" class="st3" x1="536" y1="144.7" x2="544" y2="98.3"/>
</g>

<script>
 function bigLine(){
     var lines = document.querySelector('#Layer_2')
     var l = lines.querySelector('#move')
     console.log(l);
     l.transition = "all 2s";
     l.setAttribute("y2", "26");
   }

   function smallLine(){
     var lines = document.querySelector('#Layer_2')
     var l = lines.querySelector('#move')
     console.log(l);
     l.transition = "all 2s";
     l.setAttribute("y2", "96");
   }
</script>

A: As Robert Longson commented you can use SMIL animations: Inside the line #move there are 2 <animate> elements: the first for the mouseover and the second for mouseleave.
The first animation is changing the value of the x2 attribute of the line from="96.1" to="26". The second element has no from attribute but is animating the value of the y2 to="96.1"  The duration of both animations is dur="1s" and fill="freeze" is similar to the animation-fill-mode: forwards from CSS.
I hope it helps.

.st2 {
  fill: #e5caca;
}
.st3 {
  fill: none;
  stroke: #ddd;
  stroke-width: 17;
  stroke-linecap: round;
  stroke-miterlimit: 10;

}
<svg viewBox="0 0 1000 1000" style="enable-background:new 0 0 1000 1000;">
  <g id="Layer_2">
 <line class="st3" x1="500" y1="142" x2="500" y2="95"/>
    <line id="move" class="st3" x1="518.2" y1="142.9" x2="521.8" y2="96.1">
       <animate
     attributeType="XML"
        attributeName="y2"
        from="96.1" to="26"
        begin="mouseover"
        dur="1s"
        fill="freeze" />
       <animate
     attributeType="XML"
        attributeName="y2"
        to="96.1"
        begin="mouseleave"
        dur="1s"
        fill="freeze" />
    </line>
 <line id="stretch" class="st3" x1="536" y1="144.7" x2="544" y2="98.3"/>
</g>
</svg>


text:
Q: Should I switch to BrE pronunciation? My English is American, and now I'm trying to switch to BrE. e.g. labour, favour etc. Recently, I learned that the word schedule has an Am.E and a Br.E pronunciation. Should I switch to the Br.E pronunciation?

A: There are many differences in usage of words between BrE and AmE

AmE = BrE
  umbrella = brolly
  elevator = lift
  candy = sweets
  OK = right
  underwear = pants
  like = fancy

It would depend on 1) how "far" want to go with BrE, 2) whether you want to "sound native", and 3) if you can pull off the accent.
One of the things Brits laugh at is that many Yanks sound like Dick van Dyke in Mary Poppins when they try to affect a British accent.

A: Speaking as a Brit, there is nothing wrong with American English. Learn to speak (and write) English well, and forget about accent, regional spelling, etc.
If you want to be taken seriously, learn to avoid contractions such as wanna. In BrE, it would be words such as innit (isn't it).
By all means learn some BrE idioms if you like. Used judiciously, they can be very effective, don't you know? [mild sarcasm] (And they can also come in handy if you visit the UK.)


text:
Q: Android message "Cannot generate texture from bitmap" I'm working with Gallery-widget and a lot of bitmaps.
For erasing bitmaps I use Bitmap.recycle(). As result I see on logcat next messsage:
08-18 17:49:26.020: INFO/dalvikvm-heap(13847): Grow heap (frag case) to 22.373MB for 2457616-byte allocation
08-18 17:49:26.060: DEBUG/dalvikvm(13847): GC_FOR_ALLOC freed 1K, 36% free 22835K/35143K, paused 27ms
08-18 17:49:26.230: DEBUG/dalvikvm(13847): GC_CONCURRENT freed <1K, 36% free 22835K/35143K, paused 2ms+3ms
08-18 17:49:28.070: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.080: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.110: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.120: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.140: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.160: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.180: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.190: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.210: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.230: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.240: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.260: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.280: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.290: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.310: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.330: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.350: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.360: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.380: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.400: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.410: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.430: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.450: ERROR/OpenGLRenderer(13847): Cannot generate texture from bitmap
08-18 17:49:28.500: INFO/System.out(13847): Image width: 144; height: 108
08-18 17:49:28.570: DEBUG/dalvikvm(13847): GC_FOR_ALLOC freed 4094K, 42% free 20449K/35143K, paused 27ms
08-18 17:49:28.620: INFO/dalvikvm-heap(13847): Grow heap (frag case) to 22.385MB for 2457616-byte allocation

And item on Gallery-widget is black.
But application works.
Have you any idea for this question?

A: I just had the same problem. The thing is that by calling recycle() you destroy native object referencing to the pixel data of the image and the object itself (bitmap) is marked "dead". If there is no other object referencing to those data they will be freed by GC. So two possible thing are happening to you:

*

*the bitmaps are simply collected by GC so renderer has no data to use.

*as bitmap itself is marked dead you cannot read/write pixels from/to it

So if you're using/referencing this bitmap and you recycle it, you simply deny access to it for everybody. At least I understand it this way. Read this carefully:
http://developer.android.com/reference/android/graphics/Bitmap.html#recycle%28%29
So you should use recycle only if you're sure that no one is using/referencing the bitmap object. I hope it helps.

A: As speedy said, you are probably trying to access bitmaps that have been marked for Garbage Collection.
A simple solution for this is to do an isRecycled() check before returning a bitmap:
// ...

/**
 *  Will return a usable Bitmap or null if the Bitmap was not found.
 */
public Bitmap getBitmapForGallery(int uniqueImageId)
{
    Bitmap bitmap;

    // The code to fetch bitmap from cache is here.
    // ...

    return bitmap.isRecycled() ? null : bitmap;
}

// ...

A: This also happens when we reuse a bitmap
Eg.bitmap=getResizedBitmap(bitmap,500);
Here I have used bitmap again to resize it, which caused an issue.


text:
Q: The first postulate in special relativity In Einstein's special relativity, there are two postulates:
1. the laws of physics are invariant in all inertial frames of references; and
2. the speed of light in a vacuum is the same for all observers, regardless of the motion of the light source or observer.
What did Einstein mean by the first postulate?
My confusion mainly comes from the terminology "the laws of physics". I know there is a similar question recently and anna v gave an excellent answer there. But my question is a little bit different. I am asking about what Einstein had in mind when he proposed the postulate for the first time in history. By "the laws of physics", did he mean the differential equations governing the motions of moving objects?

A: AFAIK Einstein was motivated for special relativity from the framework of electromagnetism. It is in Maxwell's theory of electromagnetism that the Lorenz transformations appear naturally.
If you look at Maxwell's equations, for example in this form here,  it is based on four "laws" , there are four "laws" . These are an example of the laws that Einstein must be talking about, to start with . These laws are a distillate of experimental observations. By using them as axioms Maxwell picks those solutions of his differential equations which fit the experimental observations by intent. His theory has to fit the "axioms" he is using to pick up the valid solutions. Since his theory is well validated, i.e. is predictive of data, the domain where the laws hold  is the inertial frame domain, as defined by " an inertial frame of reference is a reference frame in which a body at rest remains at rest and a body in motion moves at a constant speed in a straight line unless acted on by an outside force."
So what Einstein did with his special relativity is to extend the electromagnetic behavior to the behavior of massive particles. He chose such postulates, so that the electromagnetic theory would remain intact, and there would be new predictions for the behavior of matter. These predictions have been validated and the special theory of relativity holds.
Inertial frames are necessary in the definition because special relativity deals with the concept of energy. Momentum , energy, angular momentum are conserved in inertial systems, there are conservation laws. BUT these laws hold only within inertial systems. When accelerated systems are introduced these laws do not hold without corrections.

A: He means that there is no test you can do, in your inertial frame, that will show whether you are moving in relationship to the Universe, or whether you are sitting still and the Universe is moving past you. All physical laws are the same in either case, therefore there is no absolute frame of reference.

A: In the context of classical mechanics there is no difference if a body is "at rest" or have constant velocity. Any passenger inside an airplane at constant 900 km/h can move and move things as in the airport.
It was well established at least for more than a century in the dawn of 20 century, even while the examples involved ships or trains and not airplanes, with its more dramatic speed.
The problem is that the notion of fields was at the heart of the electromagnetism, and that is more naturally linked to the idea of an absolute reference frame. A static field in the airport frame, would change with time to someone at 900 km/h, leading to different measurements results. Maxwell equations give different outcomes for static or time changing fields. It is not easy to deal with it.
Einstein managed to fit the EM theory in the framework of the principle of relativity, already used for mechanics. Of course it was necessary to change it to use Lorentz transformations.
The effects on mechanics, even for airplane velocities is negligible. But it solved the fields conundrum joining the magnetic and electric field in a way that can explain why different frames can measure the same EM force, and see the same movement of charged bodies.


text:
Q: Asyncronous, two awaitable methods. Only one returns Im having some problem with asyncronous programming.
If you look at this example:
public async void SaveUsersThings(List<User> Users )
{
    await SaveUsersCars(Users);
    await SaveUsersHouses(Users);
}

So I expect SaveUsersThings to perform the two following methods:
public async Task SaveUsersCars(List<User> Users)
{
    var listofCars = new List<Car>();
    foreach (var item in Users)
    {
        var cars = await _sqlrepo.GetAllCars(item.UserId);
        foreach (var car in cars)
        {
            listofCars.Add(car);
        }
    }

    _sqlrepo.SaveListOfCars(listofCars);
}

And then this (identical  as the above except for the obj)
public async Task SaveUsersHouses(List<User> Users)
{
    var listofHouses = new List<House>();
    foreach (var item in Users)
    {
        var houses = await _sqlrepo.GetAllHouses(item.UserId);
        foreach (var house in houses)
        {
            listofHouses.Add(house);
        }
    }
    _sqlrepo.SaveListOfHouses(listofHouses);
}

The problem is that only the first method completes what it is supposed to do (save some things to the db). I guess It has to do with me not fully understanding this kind of programming. Can someone explain how I can get both methods to "work"?
Thank you

A: public async void SaveUsersThings(List<User> Users )

How can you know if there's an error?  async void effectively ignores any errors.  (I suspect that the C# team really didn't want to support async void at all, but needed to for backward compatibility with some existing paradigms.  Something about event handlers, I don't know.)  Basically the void prevents any consuming code from actually awaiting the result or examining that result.  So there could very well be an AggregateException which simply has nowhere to go.
async should be "async all the way down".  Make the top-level method awaitable:
public async Task SaveUsersThings(List<User> Users )

This way whatever invokes SaveUsersThings() can await it and examine the result.  It may not guarantee that "both methods will work", but it does at least expose the reason that something isn't working.  Instead of guessing.


text:
Q: Sum with non-existing object in R I want to make a simple script where I'll sum some variables according to a fixed naming scheme. But the problem is, not all variables will be used every time. But if I try something like this:
result <- sum(variable1, variable2, variable3, na.rm = TRUE)

I get an error saying there's no variable1. Is there a way to sum only the existing variables and ignore the non-existing ones without declaring all possible variables as NA beforehand?

A: You can get the variables which are available in the global environment and sum them.
#Dummy variables
variable2 <- 12
variable3 <- 3

sum(unlist(mget(ls(pattern = 'variable\\d+'))), na.rm = TRUE)
#[1] 15

A: duplicate of this
Add this before:
sapply(c("variable1", "variable2", "variable3"), function(x)
  if(!exists(x)) { assign(x, NA, envir=.GlobalEnv) }
)

A: We could do
 Reduce(`+`, mget(ls(pattern = '^variable\\d+$')))
[1] 15

data
variable2 <- 12
variable3 <- 3


text:
Q: Download Adfm.jar for oracle 11 I"m looking for adfm.jar Oracle Containers for Java oracle 11?  Where can I download it?

A: Oracle Containers For Java (or OC4J) is a proprietary framework, and part of Oracle Application Development Framework (or Oracle ADF).
You need to buy Oracle ADF. You can do it separately, or you can get it packed with Weblogic Server (Standard Edition will do).
Edit: If you need it just for development, then it is packed with JDeveloper 11g, too. However if you want to sell your software, you (your client) must buy a license from Oracle.


text:
Q: Point wise Steps Should be Documented for Using Teams Cloud Communication Call API We are trying to develop CTI Connector for CRM and Microsoft Teams. We understand rights required to implement calling API but failed to initiate sample call from Postman. We registered application and given required permission (Application Permission) but always getting "Application Not Registered".
One thing which is not clear from Microsoft Documentation for Cloud Communication API is do we need to register our application as Bot.
It will be better if point-wise steps required to implement calling API documented on Microsoft Site.
If anyone have successfully tried Calling API for Teams then it will be great if you can suggestv the steps.
Thanks & Regards,
Umesh


text:
Q: Not able to trigger WebAPI get method from Angular controller public class FileUploadController : ApiController
{
    [HttpGet]
    public IHttpActionResult GetSomeTypes()
    {
        try
        {
            //logic implementation
        }
        catch (Exception ex)
        {
            throw ex;
        }
    return Ok(listofSomeType);
}

In my angularJS controller, I am trying to call this using
var serviceResult = $http.get("/api/FileUpload/GetSomeTypes");
serviceResult.success(function (data) {
    vm.someTypes = data;
})

I get a http://localhost:90/api/FileUpload/GetSomeTypes 500 (Internal Server Error) on the call.
I see the error An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: Strange, i do not find any other action method with same name, infact i renamed the method and tried
Thanks


text:
Q: SQL SERVER C# - performing data operations off of a custom audit table I'm a little stuck with finding an approach to perform DML operations off of a custom audit table.
I have a custom audit table on server A. I have a trigger setup to write any DML changes to a custom Audit table:
    [dbo].[data_forwarder_audit_table]
    [table_name] [varchar](100) NULL,
    [row_id] [bigint] NULL,
    [operation] [varchar](1) NULL,
    [time_stamp] [datetime] NULL,
    [primary_key] [varchar](255) NULL

So far so good, the triggers are working and I am getting the values expected in the audit table.
My thought process is:

*

*Perform a SELECT query on the Audit Table.

*Dynamically Query the changed row from the table_name by row_id

*Based on the operation Insert,Update,Delete the changes to another SQL Database on another server

I need to consider performance (imagine that) and I need to dynamically get column names for the CRUD functions because there are quite a few tables that write changes to the audit table.
How should I approach this?
Thank you,
Ron


text:
Q: How to have row without particular field as function param What I want is following, I have a row type:
type FooBarBaz =
  ( foo :: Int
  , bar :: String
  , baz :: Boolean
  )

Then a need a function that takes this row type record but without "foo": and adds default "foo" field:
withoutFoo { bar: "bar", baz: true} -- > { foo: 1, bar: "bar", baz: true}

I tried to do something like this, but can not get it around:
withoutFoo :: ∀ r.
  Lacks "foo" r =>
  Cons "foo" Int r FooBarBaz =>
  { | r } -> { | FooBarBaz }
withoutFoo props = Record.union { foo: 1 } props

UPD:
managed to solve it with Union constraint:
withoutFoo :: ∀ r.
  Union r ( foo :: Int ) FooBarBaz =>
  { | r } -> { | FooBarBaz }
withoutFoo props =
  Record.merge props { foo: 1 }

A: The problem is that your function isn't actually generic. There is only one possible choice for r: it should always be (bar :: String, baz :: Boolean)
So just make that the type of your function:
withoutFoo :: { bar :: String, baz :: Boolean } -> { | FooBarBaz }
withoutFoo props = Record.union { foo: 1 } props


text:
Q: Possible ways to display real time sensor data on web page using python I am trying to make web application which takes temperature and (motor)RPM from sensors coming through my computer which connected serially to a mechanical machine and display it on web page.
I am using Python Flask with AJAX. What I've tried so far now is took jsonify data from back-end and displayed on html page. But I am not getting or seeing any real time data changing on web page without reloading the page. I need to reload the page every time to see data changing.
How can I and what are the possible ways to get this data displayed on web page.
This is my python script for flask app:
from flask import Flask, render_template, request, jsonify
import random
import time
import serial

app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template("index.html")

@app.route('/ret_num', methods = ['POST', 'GET'])
def ret_num():
    s = serial.Serial('COM7')
    res = s.read()
    time.sleep(1)
    return jsonify(res)

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

And HTML code:

Output

A: There are two good ways of doing this:

*

*Polling
Essentially, you'll have to call your API on a loop at a small interval, say 30 seconds.
This can be achieved by using something like (code may not work as is, but the principle remains the same):

    setInterval($.ajax({
        url: '/ret_num',
        type: 'POST',
        success: function(response) {
            console.log(response);
            $("#num").html(response);
        },
        error: function(error) {
            console.log(error);
        }
    }), 30000);

*Using WebSockets instead of plain AJAX calls. Read docs here.

*(Bonus) You can reload your page at an interval. For example, to reload every 30 seconds:

    setInterval( location.reload(), 30000);


text:
Q: How to write a vfprintf wrapper that adds a prefix to format specifier and passes the new format specifier to vfprintf in C89? I am trying to write a wrapper around vfprintf function but with the requirement that I want to add a prefix to the format specifier and then pass the new format specifier to vfprintf.
Now I don't know how to do this, but I have captured my intention in the following code.
#include <stdio.h>
#include <stdarg.h>

void err(const char *format, ...)
{
    va_list args;
    va_start(args, format);
    vfprintf(stderr, "foo: error:" format, args);
    va_end(args);
}

int main()
{
    err("%s: %d\n", "Transaction failed with error code", 42);
    return 0;
}

You can see in the above code, that I want to prefix "foo: error" to the format specifier and then pass it to vprintf. This code, of course, would lead to compile time error because this code is not valid. It only captures my intention of what I am trying to achieve.
lone@debian:~/lab/c$ gcc -std=c89 -Wall -Wextra -pedantic vfprintf-wrapper.c
vfprintf-wrapper.c: In function 'err':
vfprintf-wrapper.c:8:36: error: expected ')' before 'format'
     vfprintf(stderr, "foo: error:" format, args);
                                    ^
vfprintf-wrapper.c:8:5: error: too few arguments to function 'vfprintf'
     vfprintf(stderr, "foo: error:" format, args);
     ^

Can you help me to write this code correctly?

A: Your pseudocode vfprintf(stderr, "foo: error:" format, args); should be:
fprintf(stderr, "foo: error:");
vfprintf(stderr, format, args);

You seem to be indicating that you want to avoid the "extra" fprintf call. If so then you could do this:
char *fail = malloc(sizeof "foo: error:" + strlen(format));
if ( !fail )
    exit(EXIT_FAILURE);
strcpy(fail, "foo: error:");
strcat(fail, format);

vfprintf(stderr, fail, args);

free(fail);

although that would be a waste of time and resource.


text:
Q: Having trouble removing white bar at bottom of hero image I'm trying to create a hero image for a website, and I'm receiving a random white bar the bottom of my website.
This is the HTML

* {
  margin: 0;
  padding: 0;
  box-sizing: padding-box;
}

img {
  width: 100%;
  overflow: hidden;
}

body {
  margin: 0px 0px;
}

A: img element is by default display:inline-block; vertical-align:baseline;
That baseline alignment is what you see.
So either display:block; or vertical-align:top;:

<!DOCTYPE html>

  <meta charset="utf-8"/>
  <link rel='stylesheet' type="text/css" href="styles.css"/>
  <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">

</html

Another option - to set your image to background:

    body {
      background: no-repeat url(https://static.pexels.com/photos/158607/cairn-fog-mystical-background-158607.jpeg);
      background-size:cover;
    }
    test


text:
Q: blueimp jQuery-File-Upload : store file outside webroot I don't use to upload image, but all possible files.
Is it possible to store files outside the webroot ? (PHP)
Thanks
Hugh

A: Ok, sorry, I see now. It already can work with outside webroot folder.
    $upload_handler = new UploadHandler(array(
      "upload_dir" => '/host/app/files',
      "download_via_php" => 1,
    )) ;

:)


text:
Q: How to insert text into a string at a point of a specific character(s) I have searched the whole internet, and the only things I can find is IndexOf. The issue with that is I need a way to put the insert at a specific one of those chars.
I am currently using this
    RichTextBox1.Text = RichTextBox1.Text.Insert(RichTextBox1.Text.Substring(0,RichTextBox1.Text.Split("^")(CurrentSlide).Length), "^")

Which of course is completely incorrect after thinking about it, because the length of the index is not the real length of the text to the index.

A: I think you have the right idea. It seems like you have a "^" delimited string, and you want to insert an empty at some point. Since a collection is easier to work with than a string, your Split is a good start.
Dim parts = RichTextBox1.Text.Split("^")

Let's make that a list, so we can insert into it:
Dim parts = RichTextBox1.Text.Split("^").ToList()

Now, just insert an empty string where you want the new element:
Dim parts = RichTextBox1.Text.Split("^").ToList()
parts.Insert(CurrentSlide, "")

And combine them back for editing in your textbox:
Dim parts = RichTextBox1.Text.Split("^").ToList()
parts.Insert(CurrentSlide, "")
RichTextBox1.Text = String.Join("^", parts)


text:
Q: In Markdown, how do you put a table inside an ordered list? Should it be possible to put a table inside an ordered list in markdown? If not, whats a recommended alternative way to do it?

A: I can't find a way to get it only with markdown.
but you can use Inline HTML to replace ordered list, like
<ol>
<li> 1st

|xx|yyy|
|-|-|
|aa|bb|

<li>.
.
.
.

you can refer to https://stackoverflow.com/questions/19950648/how-to-write-lists-inside-a-markdown-table

A: Another way to do this is by adding two or more spaces (according to the level of nesting) at the beginning of the rows. Therefore this:
1. Some item
2. Item with table

  | xx|yyy|
  |---|---|
  |aa|bb|
  * Nested item with table

     | xx|yyy|
     |---|---|
     |aa|bb|
3. Another item.

It should look like this:


text:
Q: `ember install emberfire` failed, is ember-cli-emberfire a better route with Node 6.2.2? Cannot find module 'q' and more…
When I run ember install emberfire in an existing Ember app, I get Cannot find module 'q'.
I searched the issue, tried npm cache clean and npm install q.
Now, ember install emberfire throws Cannot find module '../function/makeIterator_' and I'm reluctant to go further.
However, at npm-embercli-emberfire the advice is to install via Bower with npm install --save-dev ember-cli-emberfire - to quote:

*

*This repo lists emberFire as a bower dependency

*It runs bower install as the npm postinstall script

*it exports a tree containing both the firebase and emberFire libraries

Do node 6.2.2 and ember-cli play nicely yet?
Since the machinations of npm and Node become an irritating mystery when I'm trying to focus on an Ember (tutorial) app, I'd like to know:

*

*how running ember install emberfire differs, and if running it before running the npm-recommended command is an issue?

*If it's okay to run ember-cli with node 6.2.2 - if not, suggestions?

My setup

*

*OS X 10.11.6 (and just had to chown -R usr/local after an OS X update).

*node 6.2.2 (which apparently "has currently not been tested against Ember CLI and may result in unexpected behaviour.")

*Ember: 1.13.15

*ember-cli: 1.13.15

*ember-data: 2.7.0

*node: 6.2.2

*npm: 2.14.10

*emberfire: 2.0.1

*ember-cli-emberfire: 0.0.1

The full error readout:
$ ember install emberfire
version: 1.13.15
Installed packages for tooling via npm.
installing emberfire
  identical app/adapters/application.js
Cannot find module 'q'
Error: Cannot find module 'q'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/admin/projects/solutions-log/node_modules/ember-cli/node_modules/bower/lib/commands/index.js:1:71)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
$ npm cache clean
$ npm install q
solutions-log@0.0.0 /Users/admin/projects/solutions-log
└── q@1.4.1

$ ember install emberfire
version: 1.13.15
Installed packages for tooling via npm.
installing emberfire
  identical app/adapters/application.js
Cannot find module '../function/makeIterator_'
Error: Cannot find module '../function/makeIterator_'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/admin/projects/solutions-log/node_modules/ember-cli/node_modules/bower/lib/node_modules/mout/array/collect.js:2:20)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)


text:
Q: Flutter Dismissible in AnimatedList make animation twice I've an app with two rows in a AnimatedList and each row has a dismissible for remove item by swipe.
I'd noticed when you swipe a row for remove it then animation run twice.
This is code:
  Widget _buildItem(BuildContext context, int index, Animation<double> animation) {
    Key k = new Key(_list[index]['item1'].toString());
    return Dismissible(
      key: k,
      background: Container(color: Colors.red),
      child:
      buildList(
        animation: animation,
        selected: _selectedItem == _list[index],
        item: _list[index],
      ),
      onDismissed: (direction) {
        _remove(index);
      },);
  }

  void _remove(int index) {
    _list.removeAt(index);
  }

How to fix that?


text:
Q: Java error: can't find symbol? I have the following code snippet where some strings are initialized in the if block:
String serialmask = request.getParameter( "serialmask");
String serialincrement = request.getParameter( "serialincrement");
if (serialmask == "1") {
  String tserialmask = "aaa########";
}
else {
  String tserialmask = "";
}
if (serialincrement == "1") {
  String tserialincrement = "aaa^^^^^^^^";
}
else {
  String tserialincrement = "";
}
out.println(
  itemimport(
    partnumber,
    itemcost,
    itemlistprice,
    itemdescription,
    PurchProdLineKey,
    UnitMeasKey,
    itemclasskey,
    trackmethod,
    tserialmask,
    tserialincrement
  )
);

The error I'm getting is "cannot find symbol"
symbol : variable tserialmask in the out.println(itemimport(....tserialmask,tserialincrement)); statement.
I tried declaring the variables outside of the if block and this seems to bring on even more errors saying it's already been declared.

A: You need to declare the variable first, but then just assign it. Here's the version for tserialincrement (the same is true for tserialmask)
String tserialincrement;
if (serialincrement == "1")
{
   tserialincrement = "aaa^^^^^^^^";
}
else
{
   tserialincrement = "";
}

However, there are two things wrong with this:

*

*You're using == on a string, which is a bad idea in almost all situations; use equals

*You can do it in one statement (per variable) with the conditional operator:
String tserialmask = "1".equals(serialmask) ? "aaa########" : "";
String tserialincrement = "1".equals(serialincrement) ? "aaa^^^^^^^^" : "";

In addition, I'd suggest nicer variable names, using Pascal casing (e.g. serialMask) and something more useful than just "t" as a prefix. (What does that mean?)

A: You need to declare tserialmask and tserialincrement outside of the if/else blocks.  Otherwise, they go out of scope when that block ends.
String serialmask = request.getParameter( "serialmask");
String serialincrement = request.getParameter( "serialincrement");
String tserialmask;
String tserialincrement;

if (serialmask == "1")
{
  tserialmask = "aaa########";
}
else
{
  tserialmask = "";
}
if (serialincrement == "1")
{
  tserialincrement = "aaa^^^^^^^^";
}
else
{
  tserialincrement = "";
}
out.println(itemimport(partnumber,itemcost,itemlistprice,itemdescription,PurchProdLineKey,UnitMeasKey,itemclasskey,trackmethod,tserialmask,tserialincrement));

A: You are declaring String variables within the if else statements then trying to access them outside the statements. You need to declare the variables before your if statements and then only assign them within the if/else statements.

A: You need to declare the variables tserialmask and tserialincrement outside the if branches and not try to redeclare them inside, like this:
String tserialmask;
if (serialmask == "1") {
    tserialmask = "aaa########";
} else {
    tserialmask = "";
}


text:
Q: Badge icon on GreaseMonkey I am using GreaseMonkey on the latest version of Firefox on Windows 10 and was wondering if there is a way when Greasemonkey is enabled and you visit a site to show a badge icon of the active scripts for that tab.
Regards,
George

A: Do you mean the number of scripts running on that tab?
If so, ViolentMonkey, TamperMonkey & FireMonkey have that feature but GreaseMonkey doesn't.
In GreaseMonkey, if you click the icon, the popup shows the User scripts for this tab.


text:
Q: Redis stream command passing message with parsed value I am creating the client using Redis and node js, I want to add a message to stream with the below format. I am facing an issue when trying the parse the message with the request body value.
async function userRegister (request) {
  var userID = request.body.userID
  var username = request.body.userName

  redisClient.xadd(
    'user:create',
    '*',
    'module',
    `userRegister`,
    'request_id',
    '2312432434',
    'message',
    `{"module":"*","user_id":"1","username":"fffff"}`, // this works bcoz its string.

    `{"module":"*","userID":"1","username":"here i need pass the above request body value"}`,

    function (err, resp) {
      if (err) {
        console.log(err)
      } else {
        console.log(resp)
      }
    }
  )

}


text:
Q: Mongodb C# and SELECT nested value I'm trying to do a simple select in mongodb with some C# code :
   "_id" : ObjectId("5aa04a34294f9c8f6c0ead85"),
"Categorie" : "smartphone",
"Plafond" : 1000.0,
"SousCategorie" : [
    {
        "SousCategorieLibelle" : " 100-300 ",
        "ValeurMin" : 100.0,
        "ValeurMax" : 300.0,
        "GarantieTarif" : [
            {
                "GarantieCode" : "VOL",
                "GarantieLibelle" : "Vol",
                "HT" : 0.09,
                "Taxe" : 0.01,
                "TTC" : 0.1,
                "Franchise" : 50.0
            },
            {
                "GarantieCode" : "BOD",
                "GarantieLibelle" : "Casse et Oxydation",
                "HT" : 0.06,
                "Taxe" : 0.01,
                "TTC" : 0.07,
                "Franchise" : 50.0
            },
            {
                "GarantieCode" : "CAT",
                "GarantieLibelle" : "Catastrophes naturelles",
                "HT" : 0.01,
                "Taxe" : 0.01,
                "TTC" : 0.02,
                "Franchise" : 190.0
            },
            {
                "GarantieCode" : "CTEC",
                "GarantieLibelle" : "Catastrophes technologiques",
                "HT" : 0.0,
                "Taxe" : 0.0,
                "TTC" : 0.0,
                "Franchise" : 50.0
            }
        ]
    }
],
"Frais" : 0.02,
"Commission" : 0.02

In C# i m using this code :
 protected async void ddlcategorie_SelectedIndexChanged(object sender, EventArgs e)
    {
        IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("tarifs");

        BsonDocument filter = new BsonDocument();
        filter.Add("Categorie", "smartphone");

        using (var cursor = await collection.FindAsync(filter))
        {
            while (await cursor.MoveNextAsync())
            {
                var batch = cursor.Current;
                foreach (BsonDocument document in batch)
                {
                    txtValeur.Text += document["SousCategorie"]["SousCategorieLibelle"];
                 //   txtValeur.Text += document[1][2];
                }
            }
        }

    }

And i m always get a error :

System.NotSupportedException : 'BsonArray does not support indexing by
  name (only BsonDocument does).'

but if I ask document.GetType().ToString(); I get MongoDB.Bson.BsonDocument.
What I am supposed to do?
thanks!

A: The problem is that property "SousCategorie" is an array (the first char after : is [), so when indexing document["SousCategorie"] is correct but returns BsonArray. As I understand it is one element array so you can take the first element (using index 0 or First()) and then access needed property
Probably the following code will work but I didn't test it:
foreach(var category in document["SousCategorie"])
{
   Console.WriteLine(category["SousCategorieLibelle"));
}

A:   protected async void ddlcategorie_SelectedIndexChanged(object sender, EventArgs e)
{
    IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("tarifs");

    BsonDocument filter = new BsonDocument();
    BsonDocument projection = new BsonDocument();
    projection.Add("Categorie", 1);
    projection.Add("SousCategorie.ValeurMin", 1);
    projection.Add("SousCategorie.SousCategorieLibelle", 1);

    var options = new FindOptions<BsonDocument>()
    {
        Projection = projection
    };

    using (var cursor = await collection.FindAsync(filter, options))
    {
        while (await cursor.MoveNextAsync())
        {
            var batch = cursor.Current;
            foreach (BsonDocument document in batch)
            {
                Console.WriteLine(document.ToJson());
            }
        }
    }
}

I m tring to get "SousCategorie.SousCategorieLibelle" Value
>? document["SousCategorie"][0].ToString()
"{ \"SousCategorieLibelle\" : \" 100-300 \", \"ValeurMin\" : 100.0 }"
>? document["SousCategorie"][0]
{{ "SousCategorieLibelle" : " 100-300 ", "ValeurMin" : 100.0 }}

>? document["SousCategorie.SousCategorieLibelle"].ToString()
'document["SousCategorie.SousCategorieLibelle"].ToString()' a levé une exception de type 'System.Collections.Generic.KeyNotFoundException'

I dont understand how i can get deeper in my database


text:
Q: doctrine ManyToOne relation crashes symfony 3.3.1 We have an old postgres 9.2 database with more than 400 tables. I used the symfony console to generate the entities, I created the repository classes that I need myself.
When I remove all relations from an entity, build a controller and repository to fetch some objects, everything works fine. But when I add a ManyToOne relation again symfony loads for about a minute or two and then I get a chrome error page "ERR_CONNECTION_REFUSED". Maybe someone can help.
AppBundle\Entity\Firma.php (shortened for better visibility)
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Firma
 *
 * @ORM\Table(name="firma", uniqueConstraints={@ORM\UniqueConstraint(name="firma_fid_key", columns={"fid"})}, indexes={@ORM\Index(name="IDX_2BED3563DF1BF902", columns={"ftypid"}), @ORM\Index(name="IDX_2BED35632453407B", columns={"hstraegerid"}), @ORM\Index(name="IDX_2BED356318F71675", columns={"hstypid"}), @ORM\Index(name="IDX_2BED3563950F9D92", columns={"uniid"})})
 * @ORM\Entity(repositoryClass="AppBundle\Repository\FirmaRepository")
 */
class Firma
{
    /**
     * @var integer
     *
     * @ORM\Column(name="fid", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="firma_fid_seq", allocationSize=1, initialValue=1)
     */
    private $fid;

    /**
     * @var \AppBundle\Entity\Ftyp
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Ftyp")
     * @ORM\JoinColumn(name="ftypid", referencedColumnName="ftypid")
     */
    private $ftypid;

AppBundle\Repository\FirmaRepository.php
namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

class FirmaRepository extends EntityRepository
{

}

AppBundle\Entity\Ftyp.php (shortened for visibility)
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Ftyp
 *
 * @ORM\Table(name="ftyp")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\FtypRepository")
 */
class Ftyp
{
    /**
     * @var integer
     *
     * @ORM\Column(name="ftypid", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="ftyp_ftypid_seq", allocationSize=1, initialValue=1)
     */
    private $ftypid;

    /**
     * @var string
     *
     * @ORM\Column(name="ftyp", type="string", length=64, nullable=false)
     */
    private $ftyp;

}


text:
Q: Visual Studio 2017 & 2019 highlight occurrences of selected word in scrollbar When I mark a word (of any kind) I would like all occurrences (in that particular file) of that word to be highlighted in the scrollbar on the right hand side.
This was a feature in VS2015 and VS2013. I cannot imagine that they removed it, I just don't know how to switch it on. None of the apparent possibilities in Tools -> Options (image) helps me.

Ps. I am using Visual Studio 17 Professional.
Thank you.

A: Right now, the only way I know (without installing new extensions) is to select (double click) the word and hit ctrl-f (find). Scroll map should highlight all occurences (mine are orange)

A:
This was a feature in VS15 and VS13.

Actually it was not.
It is a feature of the Productivity Power Tools extension. That extension is now just an installer for separate single feature extensions. I think you'll be wanting Match Margin.
For Visual Studio 2022 Match Margin is also available.

A: There's another extension which does exactly this, with options to customize colors and more. it called Word Highlight With Margin.
The extension created by Trung Kien Phan
Screenshots

VS2017/VS2019/2022 Version
Download link from Visual Studio market place - VS2017, VS2019, VS2022
Previous versions:
VS2015
VS2010, VS2012, VS2013

A: MultiWordHighlight can highlight different words with different color
https://github.com/jendelel/MultiWordHighlight
update

*

*How to install
Install via Visual Studio Marketplace (https://marketplace.visualstudio.com/items?itemName=jendelel.MultiWordHighlight).

*How to use
Right click on any word under the caret and select Toggle highlight of current word in the MultiWordHighlight menu.


text:
Q: Restore %APPDATA% to AppData/Roaming folder After installing Windows, I originally moved the 3 AppData subfolders to my external harddrive, but I quickly changed my mind and restored them (clicking the restore button). Now %APPDATA% is incorrectly pointing to AppData/LocalLow. It should be pointing to AppData/Roaming. I found this by running set in Command Promt. How do I restore it to default settings?
I am specifically on Windows 10, but I assume this is the same for all versions of Windows since 7.

A: Since the issue was user-related, a newly created user did not have the issue. (Thanks Ramhound for the suggestion)
I simply created a new Administrator user and removed the old one. Do keep in mind that this will delete all user specific files for the old user (Documents, Downloads, AppData, etc.), so back them up.


text:
Q: Multiple Mosquitto brokers to exchange data between devices I have 3 devices each of them have Mosquitto broker running on them. Each of this device has subscriber and publisher.
I am using IP of each device to open port at 8883 and exchange messages --> subscribe/publish their messages. If the case happens to be that devices use dynamic IP., How can I publish new IP-PORT address to its clients that are already connected? How to tackle this problem. Is my approach correct? Is there any other way I can create my own private IP-PORT address to the broker?

A: Your broker needs to be reachable at a known location, be that fixed IP address or a DNS entry that points to it's current IP address.
Any clients connected at the time the IP address changes will be disconnected and will need to reconnect.
You've not said if these are all on the same LAN or spread across the internet, but either way you need some sort of dynamic DNS solution.
If the devices are all on the same LAN then you can use Avahi/mDNS/Bonjour to discover the current address of the device in the .local domain. Each broker will need to have a unique name.
If you are in a none lan environment then you will need to use a proper Dynamic DNS solution and have each broker have a unique fully qualified DNS name that the host machine can update when ever it's IP address changes.
Both of these solutions are more network admin solutions than programming questions so I suggest you ask on SuperUser if you have follow up questions.
There is a 3rd option, which is to have a 4th broker on a fixed IP address that acts as a central bridge for all the other brokers.


text:
Q: Puppeteer is blocked by the site https://nationsglory.fr/servers when it redirects to the requested page. How to pass this redirect? Thank you to everyone who will look into my problem.
I was always able to scrape easily with puppetter but not on this page https://nationsglory.fr/servers.
The latest version of puppeteer prevents me from going on the page, I get stuck at the redirection.
This is why I run my script under the version:
         "puppeteer": "7.0.1",
         "puppeteer-extra": "3.1.16",
         "puppeteer-extra-plugin-stealth": "2.7.4"

With these versions, I manage from time to time to pass and I can scrape the data of this site.
But I wish it would work all the time and I don't know how to make it happen.
Here is my code:
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
const { log } = require("npm-colorlog");
puppeteer.use(StealthPlugin());

let countryInfos = "";
//true for hidden Chromium
//ancian ip, dos is useless
puppeteer.launch({
    headless: false,
    timeout: 10 * 60 * 1000,
    args: [
        "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36",
        "--no-sandbox",
        "--disabe-infobars",
        "--disable-setuid-sandbox",
        "--window-position=0,0",
        "--ignore-certificate-errors",
        "--ignore-certificate-errors-spki-list"
    ],

}).then(async browser => {
    console.log('✷ Running browser..')
    const page = await browser.newPage();
    //    await page.setViewport({ width: 800, height: 600 })

    await page.goto('https://nationsglory.fr/server/yellow/countries')
// the code gets stuck here because the redirection fails and the page refreshes in a loop

await page.waitForTimeout(500);
    await page
        .waitForSelector('.lead', { timeout: 10 * 60 * 1000 })
        .then(() => console.log('load page!'));
    await page.screenshot({ path: 'botTester.png' });
    //i screen for show if i pass

    const hrefs = await page.$$eval("tr > td > a", (list) => list.map((elm) => elm.href));
    const links = [];

    hrefs.forEach(hf => {
        if (hf.startsWith('https://nationsglory.fr/country/yellow/') == true) {
            links.push(hf)
        }
    });
    const linkLength = links.length / 2;
    for (let i = 0; i < linkLength; i++) {
        let pay = links[i].substring(37, links[i].length)

        await page.goto(links[i])
        await page
            .waitForSelector('.section-title', { timeout: 5 * 60 * 1000 })
            .then(() => console.log('load country'));
        await page.waitForTimeout(500);
        page.waitForSelector('#bodymembers>tr>.pl-4 > a > div');

        const claims = await page.evaluate(() => Array.from(document.querySelectorAll(".mb-2"), element => element.textContent));
        const powers = await page.evaluate(() => Array.from(document.querySelectorAll(".col-md-3 > .mb-2"), element => element.textContent));
        const members = await page.evaluate(() => Array.from(document.querySelectorAll(" >tr>.pl-4 > a > div"), element => element.textContent));

        let level = claims[2];
        let power = powers[1].split("/");
        let claim = claims[4];
        power = parseInt(power[0], 10)
        claim = parseInt(claim, 10)

        countryInfos += "n°" + i + pay + " → ♝ level: " + level + " → ♚ power: " + power + " → ♛ claim: " + claim + "\n" + "→ ♟Members: " + members ";

    }
    const fs = require('fs');
    fs.writeFile('countryInfos.txt', countryInfos, function(err) {
        if (err) throw err;
        console.log('File created !');
    });
    await browser.close();
    console.log("✨All done, check the console✨");
})

If you have any questions do not hesitate.
Thank you all for your help !


text:
Q: Create random Wallet with connection to a specific provider via ethers.js Problem
I am trying to create random wallets via the function Ethers.Wallet.createRandom with a connection to a specific network (like Ropsten for example). The docs specify that I can pass an optional options object.
What I tried
I tried passing a connection to the network like this:
const networkProvider = await new Ethers.getDefaultProvider(process.env.NETWORK);
const wallet = Ethers.Wallet.createRandom({ provider: networkProvider });

Unfortunately, that did not work.
Question
Is there an option to pass the network when creating the wallet or has this to be done later?

A: The returned Wallet object (docs) contains the private key and the address of the wallet. However, the address generating algorithm is universal across all networks. So if a private key 0x123 generates an address 0x456, you can always use the same 0x123 private key to sign transactions from 0x456 address on all networks - the mainnet, Ropsten, Rinkeby, etc.
The network on which you broadcast the transaction depends on what network is your provider connected to. So if your want to limit on what networks the app can send transactions, you need to validate the provider's getNetwork() returned value (docs).
Ad the options param: In the createRandom() source code, it only uses the param to affect the pseudo-randomness of how the private key is generated. But again, it's not related to the network(s) on which you're going to be using the wallet.

A: import { ethers } from 'ethers';

setWallet(ethers.Wallet.createRandom(['21321']));

Options of createRandom may have the properties:
extraEntropy — additional entropy to stir into the random source


text:
Q: Best way to add logo to a photo: Illustrator vs Photoshop I understand that Adobe Illustrator is better for making logos because they can be re-sized to any size. I also understand that Adobe Photoshop is better for actually cutting/adding effects to photos.
However, what if I want to take a photo, add effects to it and also then add my logo to it that I designed in AI?
Should I create/add effects to my photo in photoshop and then import the logo as a stamp from AI (or something like that)? Or should I do the project in AI by importing the photo I edited from photoshop?
If done in AI, I was thinking to make my logo into a symbol and then just reuse it.
Thanks.

A: Just modify your photo in PS and then drag and drop the logo from AI. It will be a smart object in PS, resize it and place it where you need. PS is better at handling photo size and effects.

A: The first answer is spot on. Create your logo in Illustrator so you can use it anywhere and add it in PS since the photo is a raster image and is not infinitely scalable anyway.


text:
Q: How to replace all values (by a function) in nested list in Python? There are many suggestions but I can't make it stick. The closest solution I have below. The data is like:
my_list = ([1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], 8)

and a function
def convert(G, l, d):
    z = []
    if isinstance(x, list):
        print(x)
        z.append(convert(G, x, d))
    else:
        print(x)
        z.append([v[d] for n,v in G.nodes(data=True) if n == l])
    return z

execution:
print(convert(G, my_list, "name"))

It gives empty array but print(x) gets the source as is. I'm close I guess. The problem is I don't know how to pass l at if n == l as a integer not list.
EDIT
Outpit:
(['a', ['b', 'c'], 'd', ['e', ['f' , [], ['g', 'h']], 'j']], 'g)
in the same format (nested). The custom function just takes each element (int) and returns its attribute from dict (letter).
Another try:
my_list = ([1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], 8)
z = []
def convert(G, l, d):
    z.append([convert(G, x, d) if isinstance(x, list) else [v[d] for n,v in G.nodes(data=True) if n == x]])
    return z

z = convert(G, my_`list, "name")
print(z)

This part is a custom function:
[v[d] for n,v in G.nodes(data=True) if n == l]

so G can be whatever. You can take it as [...]
For example: G.nodes = {0: {'name': 'a'}, 1: {'name': 'b'}, 2: {'name': 'c'}, 3: {'name': 'd'}}

A: It seems like you are looking for a kind of map function that works for nested lists. Try this:
def deepmap(f, lst):
    return [deepmap(f, x) if isinstance(x, list) else f(x) for x in lst]

This will convert the outer tuple to another list, though. If you need that to be a tuple, or if there can be more tuples within, it should not be too hard to extend that function accordingly. Example:
>>> my_list = ([1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], 8)
>>> deepmap(str, my_list)
[['1', ['2', '3'], '4', ['5', ['6', [], ['8', '9']], '10']], '8']

In your case, the mapping function f might be something like this, not entirely sure though. (You might also want to change your G.nodes data structure so you don't have to iterate all the items but can access item x directly.)
f = lambda x: next(v[d] for n,v in G.nodes(data=True) if n == x)

A: A simplified version, following your structure, might look like this:
def v(x):
    return x + 1

def convert(l):
    z = []
    for x in l:
        if isinstance(x, list):
            z.append(convert(x))
        else:
            z.append(v(x))
    return z

This results in the expected nesting:
>>> convert([[1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], 8])
[[2, [3, 4], 5, [6, [7, [], [9, 10]], 11]], 9]

A: Define a custom mapper
import string
def mapper(item):
    if not isinstance(item,list):
        return d[item]
    else:
        return [mapper(i) for i in item]

d=dict(zip(range(1, len(string.ascii_lowercase) + 1), string.ascii_lowercase))

Mapping dict will look like this

{1: 'a',  2: 'b',  3: 'c',  4: 'd',  5: 'e',  6: 'f',  7: 'g',  8:
  'h',  9: 'i',  10: 'j',  11: 'k',  12: 'l',  13: 'm',  14: 'n',  15:
  'o',  16: 'p',  17: 'q',  18: 'r',  19: 's',  20: 't',  21: 'u',  22:
  'v',  23: 'w',  24: 'x',  25: 'y',  26: 'z'}

my_list = ([1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], 8)
tuple([mapper(i) for i in my_list])

You can also use map function with custom mapper
tuple(map(mapper,my_list))

Output
(['a', ['b', 'c'], 'd', ['e', ['f', [], ['h', 'i']], 'j']], 'h')

A: You just need to make a recursive function to do the convert:
my_list = ([1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], 8)
mapping = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j'}

def convert(inlist):
    def transform(x):
        if isinstance(x, list):
            return convert(x)
        else:
            return mapping.get(x)
    return [transform(x) for x in inlist]
print(convert(my_list))


text:
Q: Type because expression of type 'any' can't be used to index type How to get rid of this typescript error (Element implicitly has an 'any' type because expression of type 'any' can't be used to index type ) ? i have tried to add any to both of those even thats not helping. Nullish coalescing operator which makes it more complicated, any advice ?

const bookType:any = books.find(
    (book: any) => book.identifier === props.book?.identifier
  )?.type;

  const bookTypes:any = {
    "Fantasy": ["HarryPotter", "LordOfTheRings"],
    "Horror": ["Scream", "Men"],

  }[bookType] ?? ["Narnia", "Samaritan"];

A: For those who are thinking how i solved it (solved it using Record<Keys, Type>):

const bookType:any = books.find(
    (book: any) => book.identifier === props.book?.identifier
  )?.type;

  const bookTypes:any =( {
    "Fantasy": ["HarryPotter", "LordOfTheRings"],
    "Horror": ["Scream", "Men"],

  }as Record<string, string[]> )[bookType] ?? ["Narnia", "Samaritan"];


text:
Q: Nginx: Rewrite sub-directory to different directory Currently I have a directory that is down a bit in the codebase, I need to move it to a url that I use on the old server that uses Apache.
In Apache I have:
RewriteRule ^ait/(.*) system/ait/$1 [L,QSA]

I'm trying to write it in Nginx but can't seem to figure it out, I've tried the below.
location /ait/ {
    rewrite ^ait/(.*)$ /system/ait/ last;
}

And:
location /ait/(.*) {
    rewrite ^/system/ait/$1?$args permanent;
}

Any help greatly appreciated.

A: Found the answer after much testing.
location /ait {
    rewrite ^/ait/(.*) /system/ait/$1 break;
}

A: You don't need rewrite. Use root:
location /ait/ {
    root /path/to/system/;
}


text:
Q: google analytics content experiment without redirect getting no visitors I have implemented a GA experiment with no redirect
<script type="text/javascript">_udn = 'example.com'; _uhash='off';</script>
<script type="text/javascript" src="//www.google-analytics.com/cx/api.js?experiment=ExperimentID"></script>
<script type="text/javascript">var chosenVariation = cxApi.chooseVariation();</script>

<script type="text/javascript">

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'AccountID']);
_gaq.push(['_setDomainName', 'example.com']);
_gaq.push(['_setAllowHash', false]);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

I don't seem to get any visits.
The instructions I followed are here experiments-client-side
I have followed the accepted answer at this  similar question
Google still does not seem to be receiving my experiment visits.
I am wondering if it has something to do with using stats.g.doubleclick.net/dc.js instead of ga.js

A: Change the ga.src to ga.js experiments don't seem to work with stats.g.doubleclick.net/dc.js
ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';

was changed to
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

This solution is not optimal since it stops me from getting demographic data but I am at least getting experiment data now.


text:
Q: To push tuple values to a excel sheet wise using python I have written a python script to parse through multiple html files using beautifulsoup . My goal is to push the data to excel files iteratively sheet wise . I am able to create worksheets in excel bu executing the program and also able to fill the first row in each of the wrok sheets . I am stuck at how the all the data ( for example 99 rows ) can be moved to excel row wise . I am using openpyxl . Could anyone tell me how can i achieve this .
for tr in trs:
    cells = tr.findAll('td')
    if len(cells) == 5 :
        rsm = cells[0].string
        hostname = cells[1].string`enter code here`
        errormessage = cells[3].string
            #print errormessage`enter code here`
        applicationname = cells[4].string
        ff.append((rsm, hostname, errormessage, applicationname))

        #print row
leng += len(ff)
#print ff
#print leng
filename = "find_acs_errors_"+name[3]+".csv"
print filename
with open(filename, 'wb') as result:
    writer = csv.writer(result, dialect='excel')
    writer.writerow(['RSM','HOSTNAME','ERRORMESSAGE','APPLICATIONNAME'])
    for row in ff:
        writer.writerow(row)

    #mywriter.writerow(row)

result.close()

I tried with CSV , the above code is the same . I am able export all the rows as expected in a csv file . But not able to add one more worksheet in the same csv file created . I came to know that we wouldnt be able to multiple worksheets in a csv file which is already created . So i tried using openpyxl , i unfortunately did not save the code , i will be sharing it soon . Could you please let me know if we can achieve the same using csv module ?


text:
Q: Append to array in swift - has no member append? What am I doing wrong in this code?
and why do I get the error ?

"Value of type 'NSMutableArray' has no member 'append'"

    static func saveUserData()
    {
        let item:NSDictionary = ["TIME":"12:00","LOCATION":"here"]
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentsDirectory = paths[0]
        let filePath = documentsDirectory + "/datafile.dat"
        var readArray:NSMutableArray? = NSMutableArray(contentsOfFile: filePath)

        if var array = readArray {

            print("loaded array - appending..." )

           // PROBLEM IS HERE
             var damnArray:NSMutableArray = array
             damnArray.append(item)
         } else {
           //
         }
    }

A: Because you are using NSMutableArray, you need to use addObject
damnArray.addObject(item)

append is used with swift array like this way
var arr = [Int]()
arr.append(5)

For more detail about swift array check this apple documentation or this tutorial.

A: Your had declared dammArray as NSMutableArray. So there is no method append is available. Append is available in swift array object.
 var damnArray:NSMutableArray
 damnArray.addObject(item)

or
 var damnArray = [NSDictionary]()
 damnArray.append(item)

A: As per your answer and syntax this worked for me thanks, in my code which is:
@IBAction func btnSend(_ sender: UIButton)

{

    //data.append(tfData.text!)

    data.add(tfData.text!)
    tblViewList.reloadData()

    tfData.resignFirstResponder()
}


text:
Q: ScalaTest: BeforeAndAfter not running I am trying to learn how to use fixture setup and teardown in ScalaTest. One example I have been trying is the following:
import org.scalatest._
import scala.collection.mutable

class SampleTest extends FlatSpec with BeforeAndAfter with Matchers{

  before {
     // Setup code
  }

  after {
    // Teardown code
  }

  "A Stack" should "pop values in last-in-first-out order" in {
    val stack = new mutable.Stack[Int]
    stack.push(1)
    stack.push(2)
    stack.pop() should be (2)
    stack.pop() should be (1)
  }

  it should "throw NoSuchElementException if an empty stack is popped" in {
    val emptyStack = new mutable.Stack[Int]
    a [NoSuchElementException] should be thrownBy {
      emptyStack.pop()
    }
  }
}

The trouble with this is that neither of the before or after blocks are being executed at all. I feel I have followed the instructions in the project docs perfectly - what am I doing wrong?

A: I tried your example and it runs fine:
import org.scalatest._
import scala.collection.mutable

class SampleSpec extends FlatSpec with BeforeAndAfter with Matchers{

  before {
    info("Setup code")
  }

  after {
    info("Teardown code")
  }

  "A Stack" should "pop values in last-in-first-out order" in {
    val stack = new mutable.Stack[Int]
    stack.push(1)
    stack.push(2)
    stack.pop() should be (2)
    stack.pop() should be (1)
  }

  it should "throw NoSuchElementException if an empty stack is popped" in {
    val emptyStack = new mutable.Stack[Int]
    a [NoSuchElementException] should be thrownBy {
      emptyStack.pop()
    }
  }
}

Pasting it into the REPL gives you:
scala> new SampleSpec execute
SampleSpec:
A Stack
+ Setup code
- should pop values in last-in-first-out order
+ Teardown code
+ Setup code
- should throw NoSuchElementException if an empty stack is popped
+ Teardown code

However, given you comment about needing to say "override def," I think I know what is going on. I think your IDE may have completed your code to BeforeAndAfterEach, even though you wanted BeforeAndAfter. So you mixed in BeforeAndAfterEach, which indeed requires :override def before..." but were looking at the documentation for BeforeAndAfter. Can you double check and see if that was the problem?

A: It turns out I had to add explicit override modifiers to before and after:
override def before: Any = println("Doing before")

override def after: Any = println("Doing after")

However, it should be noted that there most likely is something wrong with my environment, not TestScala. I have not seen anyone else having this issue.


text:
Q: Passsport authentication using express displays the information of previosly logged in user on a different machine. How to prevent it? I have a react application that uses passport authentication strategy using express server. In my local machine my set up will start a server (app.js) in one port and react app in other port. And I'm able to authenticate successfully using passport. In the hosting environment the server will take care of starting the server and building the react client to public folder.
My issue happens after I push my code to the hosting environment, the hosting environment starts the express server (node app.js) and build the react app to public folder. Even though I'm able to authenticate using passport and able to receive the user information, if someone else was logged in from a different browser of a different machine then that user's profile is available in my browser.
app.js
const express = require('express');
const passport = require('passport');
...
let user = {}; //this is an object to store the profile data
...
passport.serializeUser(function (user, done) {
    done(null, user);
});

passport.deserializeUser(function (obj, done) {
    done(null, obj);
});
var OpenIDConnectStrategy = require('passport-ci-oidc').IDaaSOIDCStrategy;
var Strategy = new OpenIDConnectStrategy({
    clientID: settings.client_id,
    clientSecret: settings.client_secret,
    callbackURL: settings.callback_url,
    function (iss, sub, profile, accessToken, refreshToken, params, done) {
        process.nextTick(function () {
            user = {...profile}
            profile.accessToken = accessToken;
            profile.refreshToken = refreshToken;
            done(null, profile);
        })
    }
);

passport.use(Strategy);
app.use(express.static(__dirname + '/public'));

app.get('/login', passport.authenticate('openidconnect', {}));

app.get('/oidc_callback', function (req, res, next) {
    passport.authenticate('openidconnect', {
        successRedirect: redirect_url,
        failureRedirect: '/failure',
    })(req, res, next);
});

app.get('/user', function (req, res) {  //This is the api i use to access user information in ract page
  res.send(user);
});

app.get('/logout', function (req, res) {
    user = {};                         //empty the user data object
    req.session.destroy();
    req.logout();
    res.end();
});

Here we can see I'm using a user object to store the user data and created a API /user (app.get('/user' ...) to access the user data from my client react application.
React component to access the user
constructor() {
    super()
    this.state = {
      loggedUser: []
    }
  }

  componentDidMount() {
    axios.get('/user')       //If I'm testing with local the API will be https://localhost:5000 - node server
      .then(res => {
        const loggedUser = res.data;
        this.setState({ loggedUser });
      }).catch(err => {
      console.log("Fetch error", err)
    })
  }

A: Edit: completely reviewed answer after question edited with new data.
First of all we need a unique key in profile to uniquely identify a user, in my example I use "oid" but you can use the one better fits your requirements.
You could try to change following pieces of code:
let user = {}; //this is an object to store the profile data

passport.serializeUser(function (user, done) {
    done(null, user);
});

passport.deserializeUser(function (obj, done) {
    done(null, obj);
});

// Later ...
function(iss, sub, profile, accessToken, refreshToken, params, done) {
    process.nextTick(function () {
        user = {...profile}
        profile.accessToken = accessToken;
        profile.refreshToken = refreshToken;
        done(null, profile);
    })
}

with:
let uniqueKey = "oid"; // The field name of profile which uniquely identify a user
let users = {};

passport.serializeUser((user, done) => done(null, (users[user[uniqueKey]] = user)[uniqueKey]));
passport.deserializeUser((key, done) => done(null, users[key]));

// Later ...
(iss, sub, profile, accessToken, refreshToken, params, done) => done(null, { ...profile, accessToken, refreshToken })
// or
(iss, sub, profile, accessToken, refreshToken, params, done) => {
    process.nextTick(() => done(null, { ...profile, accessToken, refreshToken }));
}

All these are async functions, so when I say to return I mean doing it through the done callback function.
The first login function only need to return the user object (actually passport-ci-oidc seems to require it in process.nextTick, you can try with or without it).
serializeUser needs indeed to serialize the user object, which in our case means just to sore it in the memory store users[user[uniqueKey]] = user and then to return the unique key which passport should later use to deserialize the same user done(null, user[uniqueKey]).
As last deserializeUser need to return the user object by a given identification key, in our case just to return it from the memory sore done(null, users[key]).
Hope this helps.


text:
Q: Ruby docker-api to mount volume How do I mount a host volume into docker with the ruby docker-api (https://github.com/swipely/docker-api) on runtime?
Basically, the docker run -v path:path functionality with this gem.

A: The current README missed the part to explain on how to use the volumes with container. You should be fine to run with below command with container's folder  /foo
container = Docker::Container.create('Cmd' => %w[test -d /foo],
    'Image' => 'debian:wheezy',
    'Volumes' => {'/foo' => {}}
  )

If you need mount with local folder, update to Volumes' => {'/foo' => '/local_foo'}
You can refer the test case from:
container_spec.rb

A: Documentation for docker-api gem states this in its README.md:
require 'docker'

# Create a Container.
container = Docker::Container.create('Cmd' => ['ls'], 'Image' => 'base')

# Attach to the Container. Currently, the below options are the only valid ones.
# By default, :stream, :stdout, and :stderr are set.
container.attach(:stream => true, :stdin => nil, :stdout => true, :stderr => true, :logs => true, :tty => false)
# => [["bin\nboot\ndev\netc\nhome\nlib\nlib64\nmedia\nmnt\nopt\nproc\nroot\nrun\nsbin\nselinux\nsrv\nsys\ntmp\nusr\nvar", []]

# If you wish to stream the attach method, a block may be supplied.
container = Docker::Container.create('Image' => 'base', 'Cmd' => ['find / -name *'])
container.tap(&:start).attach { |stream, chunk| puts "#{stream}: #{chunk}" }
stderr: 2013/10/30 17:16:24 Unable to locate find / -name *
# => [[], ["2013/10/30 17:16:24 Unable to locate find / -name *\n"]]

# If you want to attach to stdin of the container, supply an IO-like object:
container = Docker::Container.create('Image' => 'base', 'Cmd' => ['cat'], 'OpenStdin' => true, 'StdinOnce' => true)
container.tap(&:start).attach(stdin: StringIO.new("foo\nbar\n"))
# => [["foo\nbar\n"], []]

Does this help? Can I ask why are you trying to use docker-api? Can't you just use docker volumes (-v)?

A: Use Binds:
'Binds'     => ['/local/folder:/container/folder']

A: You need to use both Marcelo's and BMW's answers together to create a container with a working volume:
container = Docker::Container.create('Cmd' => %w[test -d /foo],
    'Image' => 'debian:wheezy',
    'Volumes' => '/container' => {},
    'Binds'     => ['/local:/container']
)


text:
Q: AWS - Tomcat default page being showed instead of webapp homepage I have a grails web app running on a Tomcat7 server on AWS. Couple of days ago, I run the yum update command, and from that moment, if I access my domain, I can only see the Tomcat homepage!
My webapps folder has a ROOT folder with the grails app, so it should definitely show this webapp's homepage as it was doing until the moment of the update...
Any idea of what configuration may have changed after the update? The ROOT.war on the webapps folder is the same that used to be there, I didn't even change it, so I guess it's gonna be a Tomcat related config. Strange that an update modifies the current behavior of a live system :(. This is an instance I inherited some months ago, so no clue about any specific configuration made before...

A: Okay, based on your added comment, I know what's going on here.
default war on aws-linux (perhaps centos/RH too)
Based on this question and answer, you can simply yum remove tomcat7-webapps. I'm not sure if it'll reinstall on an upgrade, though. Still, yay for package-based management.
default war on Ubuntu
Unfortunately, upgrading tomcat7 on ubuntu causes the default root to get reinstalled. Here are the default_root contents seen in the package: (tips for using apt-file here)
root# apt-file list tomcat7 | grep -i root
tomcat7: /usr/share/tomcat7-root/default_root/META-INF/context.xml
tomcat7: /usr/share/tomcat7-root/default_root/index.html

So, the most straightforward way to do this is, yes, to reinstall your war after upgrading.


text:
Q: `ActiveProfiles` annotation not working on Spock tests I have an application-TEST.yml file under my classpath and a Spock specification that is annotated as follows.
@ActiveProfiles("TEST")
@SpringBootTest(classes = Application.class)
class GenerateBillingFileServiceTest extends Specification {
  @Autowired
  AServiceThatUsesProperties aServiceThatUsesProperties

  def "test" {
    //...
  }
}

I want this injected AServiceThatUsesProperties to use the values in application-TEST.yml. However, this is not the case, and the properties file that is read is the one declared in application.yml as spring.profiles.active: DEVELOPMENT. Doesn't @ActiveProfies override this value? If it doesn't, how do you make a Spock specification use a specific properties file?


text:
Q: React Hooks: useHistory(), useParams(), useLocation() not updating simultanousely if used in multiple components I want to use URL´s to enable some logic in order to show buttons. I am doing this by using the useHistory, useLocation and useParams hooks.
I use this hooks in each of my components (parent + child). I would expect that all of these hooks cause a rerender, when the URL changes.
But it seems to be the case that each component remains at its own URL. Which is quite confusing for me.
Example

Description:  I have a parent and a child component. The parent component receives props, and based on the props it addes a hash to the current URL. Since the URL changed, the child component should be able to show the logic based on the change, as the useLocation should also update there.
However this is not the case. it is not updating.
Even if I pass the useHistory, pathname, or hash as props to the child component it is not working!
Parent
const Parent= (props) => {

    const routeHistory = useHistory();
    const { pathname, hash } = useLocation();

    const updateHashRoute = () => {
        if (props.value == true) {
            routeHistory.push({ hash: '#apple' });
        } else {
            routeHistory.push({ hash: '#banana' });
        }
    }

    return (

            <Child>

            </Child>

    )
}

Child
const Child = () => {

    const routeHistory = useHistory();
    const { pathname, hash } = useLocation();

    const [buttonLogic, setButtonLogic] = useState({ showDecline: false, showAccept: false })

   useEffect(() => {
       decideButtonLogic()
   }, [hash])};

    // tree logic if accept/decline and back to hierarchy if detail logic
    const decideButtonLogic = () => {
        if (hash.includes('apple')) {
            setButtonLogic({ showDecline: false, showAccept: true })
        } else if (hash.includes('banana')) {
            setButtonLogic({ showDecline: true, showAccept: false })
        }
    }

    return (

            { buttonLogic.showDecline &&
            <Button>
                Banana
            </Button>
            }
            { buttonLogic.showAccept &&
            <Button>
                Apple
            </Button>
            }

    )
}


text:
Q: How to implement Salesforce JWT OAuth 2.0 bearer flow in React JS I am working on a react app project that needs to be integrated with Salesforce, for that I found this information where I explain that I need to implement "Salesforce JWT OAuth 2.0 bearer flow":
I also found information to complete this procedure by creating a private key and self-signed digital certificate
After that, I found the panva/jose library. Based on this information and following the steps above, I am trying to implement this feature in React JS app.
After some testing, I got the signed JWT using importPKCS8(serverKey, 'RS256'), but even when getting a token, I checked JWT.io and got "Invalid Signature". What could be the cause of this?
I also found similar questions answered by Filip Skokan, then, Filip or someone else with experience in implementing this kind of future could explain step by step the correct way to implement it.
Thanks in advance.


text:
Q: Interesting representation of elements of $(0, 1]$ as integer sequences The MSE question any real number between $0$ and $1$ is expressible as an (infinite) sum of particular fractions suggests an interesting representation of real numbers in the half-open interval $(0, 1]$ as non-decreasing sequences of integers greater than $1$. Namely for any $x \in (0, 1]$, there is a unique sequence $k_1, k_2, \ldots$ of integers with $1 < k_1 \le k_2 \le \ldots$, such that:
$$
x = {1 \over k_1} + {1 \over k_1k_2} + \cdots {1 \over k_1k_2\ldots k_n} + \ldots
$$
(see the answers to the other question for a proof of existence and uniqueness and a proof that $x$ is rational iff $k_n = k_{n+1}$ for all sufficiently large $n$). This is taken from exercise 44 at the the end of chapter III of Knopp's Theory and Application of Infinite Series.
This seems somewhat reminiscent of the continued fraction representation of a positive real and I was wondering if it had been investigated further. Does this representation have any applications? Or is it just a curiosity? I have computed the first few elements of the representation for $1/\sqrt{2}$, $1/\sqrt{3}$ and $1/\sqrt{5}$ and the resulting sequences don't appear in the OEIS (which may be evidence that the representation is just a curiosity). Any pointers to work on this will be gratefully appreciated.
For the record, for $1/\sqrt{2}$, $1/\sqrt{3}$ and $1/\sqrt{5}$ the representations begin as shown below:
$$
\begin{align*}
1/\sqrt{2}{:} &\quad 2, 3, 5, 5, 16, 18, 78, 102, 120, 144, 251, 363, \ldots\\
1/\sqrt{3}{:} &\quad 2, 7, 13, 13, 94, 108, 966, 1875, 1911, 5898, 16916, 4117323 \ldots \\
1/\sqrt{5}{:} &\quad 3, 3, 41, 46, 281, 316, 316, 2003, 6731, 6966, 7472, 17687 \ldots
\end{align*}
$$

A: Thanks to the comment from mathcounterexamples.net, I can answer my own question. This is the Engel expansion. That Wikipedia link contains several interesting references.


text:
Q: Partially download and serialize big file in C#? As part of an upcoming project at my university, I need to write a client that downloads a media file from a server and writes it to the local disk. Since these files can be very large, I need to implement partial download and serialization in order to avoid excessive memory use.
What I came up with:
namespace PartialDownloadTester
{
    using System;
    using System.Diagnostics.Contracts;
    using System.IO;
    using System.Net;
    using System.Text;

    public class DownloadClient
    {
        public static void Main(string[] args)
        {
            var dlc = new DownloadClient(args[0], args[1], args[2]);
            dlc.DownloadAndSaveToDisk();
            Console.ReadLine();
        }

        private WebRequest request;

        // directory of file
        private string dir;

        // full file identifier
        private string filePath;

        public DownloadClient(string uri, string fileName, string fileType)
        {
            this.request = WebRequest.Create(uri);
            this.request.Method = "GET";
            var sb = new StringBuilder();
            sb.Append("C:\\testdata\\DownloadedData\\");
            this.dir = sb.ToString();
            sb.Append(fileName + "." + fileType);
            this.filePath = sb.ToString();
        }

        public void DownloadAndSaveToDisk()
        {
            // make sure directory exists
            this.CreateDir();

            var response = (HttpWebResponse)request.GetResponse();
            Console.WriteLine("Content length: " + response.ContentLength);
            var rStream = response.GetResponseStream();
            int bytesRead = -1;
            do
            {
                var buf = new byte[2048];
                bytesRead = rStream.Read(buf, 0, buf.Length);
                rStream.Flush();
                this.SerializeFileChunk(buf);
            }
            while (bytesRead != 0);
        }

        private void CreateDir()
        {
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
        }

        private void SerializeFileChunk(byte[] bytes)
        {
            Contract.Requires(!Object.ReferenceEquals(bytes, null));
            FileStream fs = File.Open(filePath, FileMode.Append);
            fs.Write(bytes, 0, bytes.Length);
            fs.Flush();
            fs.Close();
        }
    }
}

For testing purposes, I've used the following parameters:

"http://itu.dk/people/janv/mufc_abc.jpg" "mufc_abc" "jpg"

However, the picture is incomplete (only the first ~10% look right) even though the content length prints 63780 which is the actual size of the image.
So my questions are:

*

*Is this the right way to go for partial download and serialization or is there a better/easier approach?

*Is the full content of the response stream stored in client memory? If this is the case, do I need to use HttpWebRequest.AddRange to partially download data from the server in order to conserve my client's memory?

*How come the serialization fails and I get a broken image?

*Do I introduce a lot of overhead when I use the FileMode.Append? (msdn states that this option "seeks to the end of the file")

Thanks in advance

A: You could definitely simplify your code using a WebClient:
class Program
{
    static void Main()
    {
        DownloadClient("http://itu.dk/people/janv/mufc_abc.jpg", "mufc_abc.jpg");
    }

    public static void DownloadClient(string uri, string fileName)
    {
        using (var client = new WebClient())
        {
            using (var stream = client.OpenRead(uri))
            {
                // work with chunks of 2KB => adjust if necessary
                const int chunkSize = 2048;
                var buffer = new byte[chunkSize];
                using (var output = File.OpenWrite(fileName))
                {
                    int bytesRead;
                    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        output.Write(buffer, 0, bytesRead);
                    }
                }
            }
        }
    }
}

Notice how I am writing only the number of bytes I have actually read from the socket to the output file and not the entire 2KB buffer.

A: I don't know if this is the source of the problem, however I would change the loop like this
const int ChunkSize = 2048;
var buf = new byte[ChunkSize];
var rStream = response.GetResponseStream();
do {
    int bytesRead = rStream.Read(buf, 0, ChunkSize);
    if (bytesRead > 0) {
        this.SerializeFileChunk(buf, bytesRead);
    }
} while (bytesRead == ChunkSize);

The serialize method would get an additional argument
private void SerializeFileChunk(byte[] bytes, int numBytes)

and then write the right number of bytes
fs.Write(bytes, 0, numBytes);

UPDATE:
I do not see the need for closing and reopening the file each time. I also would use the using statement, which closes the resources, even if an exception should occur. The using statement calls the Dispose() method of the resource at the end, which in turn calls Close() in the case of file streams. using can be applied to all types implementing IDisposable.
var buf = new byte[2048];
using (var rStream = response.GetResponseStream()) {
    using (FileStream fs = File.Open(filePath, FileMode.Append)) {
        do {
            bytesRead = rStream.Read(buf, 0, buf.Length);
            fs.Write(bytes, 0, bytesRead);
        } while (...);
    }
}

The using statement does something like this
{
    var rStream = response.GetResponseStream();
    try
    {
        // do some work with rStream here.
    } finally {
        if (rStream != null) {
            rStream.Dispose();
        }
    }
}

A: Here is the solution from Microsoft: http://support.microsoft.com/kb/812406
Updated 2021-03-16: seems the original article is not available now. Here is the archived one: https://mskb.pkisolutions.com/kb/812406


text:
Q: Accessing perticular bits from array in c Extract below Bits from Array[7] bytes and store it in separate data.
Function read 7 byte buffer from Array[7] and extract (2,6,8,10,11,13,24,27,30 ) bit position and store in 0.. to 8th bit of  data .


text:
Q: Permgen space vs Meta space Metaspace introduced in JDK 8 is still part of Runtime data areas in JVM ? How does it is different from Permgen space except auto increase in Size.?

A: Both are almost can increase same, As you pointed out Metaspace can increase dynamically, to take care of dynamically loading and unloading of classes.
More details are available here