Q: Partial View not showing updated model values. Always shows existing values Actually i tried to update the partial view content whenever i do search. So i use ajax call to achieve this. So, the values from the controller to partial view model is correct(new data), but its not binding to the view (shows existing data).
Main View
     <div class="tab-pane active" id="partialviewpage">
          @{
             Html.RenderPartial("_Details", Model);
           }
      </div>

Partial View (_Details)
   foreach (var item in Model.AllAds)
    {
       //div contents
    }

Ajax Call
   var text = 'test';
   $.ajax({
        url: '@Url.Action("Subcategory", "Category")',
        type: 'GET',
        dataType: 'JSON',
        data: { item: text },
        success: function (partialView) {
            $('#partialviewpage').html(partialView);
        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });

Category Controller
    public ActionResult Subcategory(string item)
    {
      //Logic calling Api content goes here

      var SearchresponseData = responseMessage.Content.ReadAsStringAsync().Result;
      JavaScriptSerializer JssSearch = new JavaScriptSerializer();
      List<Result> Jsonresult =       (List<Result>)JssSearch.Deserialize(SearchresponseData, typeof(List<Result>));
      var Model= new ModelName();
        {
            Model.AllAds = new List<Result>();
            Model.AllAds = Jsonresult;
        }
      return PartialView("_Details", Model);
    }

So, What's wrong with my code and how can i modify the code to get the new model values. Any help appreciated. Thanks in advance.

A: I observed that you have used wrong variable to replace the html in success,
I have replace PartialView to partialView
 var text = 'test';
  $.ajax({
    url: '@Url.Action("Subcategory", "Category")',
    type: 'GET',
    dataType: 'JSON',
    data: { item: text },
    success: function (partialView) {
        $('#partialviewpage').html(partialView);
    },
    error: function (xhr, ajaxOptions, thrownError) {

    }
});


Q: How to read the cursor more than once I am working on Oracle stored procedure and need inputs on the below use case.

*

*Stored procedure will fetch the data in the cursor after some calculations.

*The cursor data will be returned to front end.

Now I have a requirement to add cursor data in another table and send to front end.
As per my understanding, once we open and read cursor to store in another table, we can't send the same cursor to front end. We will have to fetch data from source table again and send to front end.
This impacts the performance.
Any ideas on achieving this without fetching twice?


Q: on hover one div, assign animation class on another div stack!
I have an animation that is assigned to the class .slide
I have on hover on a div, when I hover over the div I want the animation class be assigned to another div. Using CSS animations.
I'd appreciate the help and thanks!
Code:
http://codepen.io/iheartkode/pen/wWMQmG?editors=0110
share-container {
  position: relative;
  width: 150px;
  height: 75px;
  background: #FF5722;
  border-radius: 10px;
  cursor: pointer;
  &:hover {
    // assign animation class to the share-icons class
  }
  p {
    text-align: center;
    color: white;
  }
}

.share-icons {
  position: absolute;
  z-index: -2;
  top: 15px;
  left: 4px;
  margin: 0 auto;
  width: 120px;
  height: auto;
  padding: 10px;
  background: coral;
  text-align: center;
  color: white;
  font-size: 2em;
  cursor: pointer;
}
.slide {
  animation: slide 2s linear;
  @keyframes slide {
    from {
      transform: translateY(0px);
    }
    to {
      transform: translateY(100px);
    }
  }
}

A: Edited after your clarification:
Change this in your HTML:
<div class="share-icons slide">

And this in your SCSS:
&:hover .slide {
    // assign animation class to the share-icons class
    animation: slide 2s linear;
    @keyframes slide {
      from {
        transform: translateY(0px);
      }
      to {
        transform: translateY(100px);
      }
    }
  }

And then adjust the animation as needed.
And here's a fork in action:
http://codepen.io/denmch/pen/WxrLQZ


Q: Floating Point Precision using REST I'm pulling timeseries data in from a MS-SQL database using REST.  I've found that the floating point precision goes down from a value like 0.00166667 to 0.002 when I'm using REST to retrieve data, but using the DB designer's own tools, the precision is maintained.
Is this a limitation of the REST method, or is it something specific to the implementation?
Just to clarify -- my work is using a proprietary database that uses MS-SQL as its backbone.  It's not open-source so I can't poke around and see how requests are being handled.
A SOAP method is offered, which I'm going to try to implement to compare, but I'm more concerned whether or not this is a REST problem or not.

A: Representational State Transfer is just a general style of client-server architecture. It doesn't specify anything nearly so detailed such the appropriate handling of floating point values. The only constraints it imposes are things like the communication should be "stateless". So the concepts of REST exist on a higher level of abstraction and the issue you are seeing must be something specific to the implementation of the service that is providing the floating point values.


Q: Xamarin.Forms: deployment issue after Visual Studio upgrade After upgrading Visual Studio Professional 2019 to version 16.9.2, when I try to deploy on Android Emulator
api 28 (9.0), I get following error:
Error XA0130: Sorry. Fast deployment is only supported on devices running Android 5.0 (API level 21) or higher. Please disable fast deployment in the Visual Studio project property pages or edit the project file in a text editor and set the 'EmbedAssembliesIntoApk' MSBuild property to 'true'.
Before the upgrade, everything worked fine. This is really frustating!

A: To correct this problem I had to

*

*uninstall app on Android phone (important step)

*Unload Android Project from solution explorer

*This brings up the project file code now search code for
<EmbedAssembliesIntoApk>false</EmbedAssembliesIntoApk>

*Change false to true save

*reload project problem solved.

Note leave fast deploy checked.

A: Go to >> Solution Properties>> Android Options>> Uncheck "Use Fast Deployment(debug mode only)"

A: I had the same issue recently after adding images to my project found out that I had upper case letters as a name SomePicture.png renaming all images to lower case solved it.

A: @AlwinBrabu, I think you meant "Project Properties" -> Android Options -> Uncheck Fast Deployment(debug mode only).
This worked for me, although this is a workaround.  I do not consider it a solution.

A: To solve this, I had to right-click on the Android project in the Solution Explorer, then in Options -> Android Build uncheck the Fast Assembly Deployment option.
Then deploy the project on the Android emulator.
But after deploying it once, I went back to the settings and checked (i.e. ticked) the Fast Assembly Deployment option, and subsequent deploys worked fine.
I'm running Visual Studio for Mac 2022 version 17.0.1 (build 72).


Q: How to destroy two different sessions in the same php script? In my session start script, I choose the session_name and then do a session_start.
   $session_name = rand(0,1) ? 'first' : 'second';
   session_name($session_name);
   session_start();

The above code runs on every page load. After a few page loads, there will probably be sessions for both session_name 'first' and session_name 'second'.
This is my code which is in my logout script to try and destroy both these sessions:
session_start();
session_name("first");
session_unset();
session_destroy();
session_write_close();

session_start();
session_name("second");
session_unset();
session_destroy();
session_write_close();

The script above destroys first but not second. If I run the log out script a second time it then destroys the second session, as the first one is already deleted.
How do I destroy sessions for both session names in the same script?

A: TRY IT
<?php
    session_name("first");
    session_start();
    echo session_status();
    session_destroy();
    echo session_status();

    session_name("second");
    session_start();
    echo session_status();
    session_destroy();
    echo session_status();
?>

I've tested it on xampp and it returns values 2121 meaning session is active, none exist, the session is active, none exist.
I've placed session_name() before session_start() because setting the name as you did doesn't take effect after a session has already been started. I've googled it and it has to do something with the php.ini file where session.auto_start is set to "true".
The explanation and a debate on this topic are found here: http://php.net/manual/en/function.session-name.php - check comments.
EDITED:
After reviewing your edit again, you basically don't create two sessions but only one and it starts with a random name "first" or "second". You can destroy a session but the cookie will remain. I've tested your code on xampp and it does exactly that. First, the PHP starts one session and stores a cookie with a time value of "session", after reloading the page it will load one of two options again but this time it will change the existing cookie time to "N/A". You should search for a solution to clear your cookies on your domain after page loads like so:
<?php
    $session_name = rand(0,1) ? 'first' : 'second';
    session_name($session_name);
    session_start();

    deleteCookies($session_name);

    function deleteCookies($skip_this_one) {
        if (isset($_SERVER['HTTP_COOKIE'])) {
        $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
        foreach($cookies as $cookie) {
            $parts = explode('=', $cookie);
            $name = trim($parts[0]);
            if ($name == $skip_this_one) {
                //skip
            }else{
                setcookie($name, '', time()-1000);
                setcookie($name, '', time()-1000, '/');
            }
        }
    }
    //do something inside your session
    //when done, stop the session the way you want
    session_destroy();
}
?>

This will delete all previous cookies and keep the current session open.
This solution is re-written from here: how to delete all cookies of my website in php
Hope this helps :)

A: Please try below code
<?php unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
?>


Q: How Can I Make Custom Tabs Using Angular Materials Tabs? I want to use Angular Material library and build my own library with some custom designs. But facing some problems while splitting the material components. I think the problem is with shadow DOM. Here is the code that i want to achieve.
Code
custom-tabs-group.html -parent

  <mat-tab-group disableRipple>
    <ng-content></ng-content>
  </mat-tab-group>

custom-tabs.html -child
<custom-tabs-group [tabContent]="tabContent">
  <mat-tab *ngFor="let tab of tabContent" label="{{tab.title}}">{{tab.content}} </mat-tab>
</custom-tabs-group>

is it even possible? Please let me know

A: the code you shared got the ng-content usage backwards... the <custom-tabs-group> will be at the parent level and <ng-content> at the child level.
I tried 2 approaches:

*

*strategy #1: pass the content to the custom child inside the <mat-tab>... this worked

*strategy #2: pass the content to the custom child where <mat-tab> is inside the child... this didn't work

you can check the demo here

A: Actually i figured it out with some hack i don't know if its a good approch or not
custom-tabs.component.html

  <mat-tab-group disableRipple>
    <mat-tab *ngFor="let tab of tabsContentList" label="{{tab.label}}">

    </mat-tab>
  </mat-tab-group>

custom-tabs-component.ts
import { DomSanitizer } from '@angular/platform-browser';
import { Component, OnInit, ViewEncapsulation, AfterContentInit, ContentChildren, Input, ViewChild, ElementRef, QueryList } from '@angular/core';

@Component({
  selector: 'il-tabs-content',
  template: `

         <ng-content></ng-content>

       `
  ,
})
export class TabsContentComponent implements OnInit {
  @Input() label: String;
  @ViewChild('content') set content(content: ElementRef) {
    console.log("block three", content)
    this.htmlContent = content;
    if (this.htmlContent) {
      this.htmlContent = this.htmlContent.nativeElement.innerHTML;
    }
  }

  htmlContent: any;
  constructor() { }
  ngOnInit() {
  }

}

@Component({
  selector: 'il-tabs-group',
  templateUrl: './tabs.component.html',
  styleUrls: ['./tabs.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class TabsGroupComponent implements OnInit, AfterContentInit {
  @ContentChildren(TabsContentComponent) tabsContentList: QueryList<TabsContentComponent>;

  constructor(public sanitizer: DomSanitizer) { }

  ngOnInit() {

  }
  ngAfterContentInit() {
    this.tabsContentList.forEach((tabInstance) => {
      var sanEle = this.sanitizer.bypassSecurityTrustHtml(tabInstance.htmlContent)
      tabInstance.htmlContent = sanEle;
      return tabInstance
    })
  }
}

usage
  <il-tabs-group>
    <il-tabs-content label="hello-1">

hello-1 content

    </il-tabs-content>
    <il-tabs-content label="hello-2">

hello-2 content

    </il-tabs-content>
    <il-tabs-content label="hello-3">

hello-3 content

extra content

    </il-tabs-content>
  </il-tabs-group>

i defined two components 'il-tabs-content' and 'li-tabs-group'. with this now i can use my own custom tabs build over angular material tabing with dynamic tabs. Anyone with better approch are welcome to share their ideas. thanks


Q: assigning strtof value into 2D array in C I'm trying to parse a CSV file into a 2D array in C. I want to make a matrix wit the structure :
typedef struct {
    int row;
    int col;
    float **arr;
    int numElements;
} Matrix;

The function I'm using takes in a dynamically allocated 2D array of floats, and is returned. I'm reading the values in using fgets, tokenizing each value between commas using strtok and then converting the string returned using strtof.
First, I made the 2D arrays dynamically and then pass them to the function to be filled in with values,
RMatrix->arr = make2DArray(RMatrix->row, RMatrix->col);
    VMatrix->arr = make2DArray(VMatrix->row, VMatrix->col);

    printf("RMatrix->arr : %p \n", RMatrix->arr);
    printf("VMatrix->arr : %p \n", VMatrix->arr);

    parseCSV(fpRMatrix, RMatrix->arr, RMatrix->row, RMatrix->col, &(RMatrix->numElements), INPUT_LENGTH);
    printf("RMatrix parsed\n");
    parseCSV(fpVMatrix, VMatrix->arr, VMatrix->row, VMatrix->col, &(VMatrix->numElements), INPUT_LENGTH);
    printf("VMatrix parsed\n");

Below are the functions :
void parseCSV(FILE *fp, float **output, int row, int col, int *numElements ,int inputLength)
{
    char *buffer;
    int rowArr = 0;

    printf("Output : %p \n", output);

    buffer = (char*) malloc(inputLength * sizeof(char));

    while(fgets(buffer, inputLength, fp)) {
        char *p =strtok(buffer,",");
        int colArr = 0;
        float check = 0;

        while(p)
        {
            printf("p now : %s \n", p);
            check = strtof(p, (char**) NULL);
            printf("check now : %f \n", check);
            output[rowArr][colArr] = strtof(p, (char**) NULL);
            *numElements += 1;
            colArr++;
            p = strtok('\0',",");
            printf("output[%d][%d] : %f  ", rowArr, colArr, output[rowArr][colArr]);
        }
        printf("\n");
        rowArr++;
    }
    printf("numElements in the end : %d\n", *numElements);
    free(buffer);

}

float **make2DArray(int row, int col)
{
    float** arr;
    float* temp;

    arr = (float**)malloc(row * sizeof(float*));
    temp = (float*)malloc(row * col * sizeof(float));
    for (int i = 0; i < row; i++) {
        arr[i] = temp + (i * row);
    }

    return arr;

}

The output :
Name : RMatrix
NumElements : 0
Rows : 2
Cols : 4
Name : VMatrix
NumElements : 0
Rows : 2
Cols : 4
RMatrix->arr : 0x11684d0
VMatrix->arr : 0x1168520
Output : 0x11684d0
p now : 1
check now : 1.000000
output[0][1] : 0.000000  p now : 2
check now : 2.000000
output[0][2] : 0.000000  p now : 3
check now : 3.000000
output[0][3] : 0.000000  p now : 4

check now : 4.000000
output[0][4] : 0.000000
p now : 5
check now : 5.000000
output[1][1] : 4.000000  p now : 6
check now : 6.000000
output[1][2] : 0.000000  p now : 7
check now : 7.000000
output[1][3] : 0.000000  p now : 8

check now : 8.000000
output[1][4] : 0.000000
numElements in the end : 8
RMatrix parsed
Output : 0x1168520
p now : 1
check now : 1.000000
output[0][1] : 0.000000  p now : 2
check now : 2.000000
output[0][2] : 0.000000  p now : 3
check now : 3.000000
output[0][3] : 0.000000  p now : 4

check now : 4.000000
output[0][4] : 0.000000
p now : 5
check now : 5.000000
output[1][1] : 4.000000  p now : 6
check now : 6.000000
output[1][2] : 0.000000  p now : 7
check now : 7.000000
output[1][3] : 0.000000  p now : 8

check now : 8.000000
output[1][4] : 0.000000
numElements in the end : 8
VMatrix parsed

As you can see, the strtof call succeeded (reflected in p and check variable) but not the assignment into the array.
I've only been using C for a month and I'm fascinated by it. However, it's obvious I need to learn more. I really appreciate your help :)

A: this
arr[i] = temp + (i * row);

should be
arr[i] = temp + (i * col);

since i = [0,row-1]


Q: Is it good practice to use the xor operator for boolean checks? I personally like the exclusive or, ^, operator when it makes sense in the context of boolean checks because of its conciseness.  I much prefer to write
if (boolean1 ^ boolean2)
{
  //do it
}

than
if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
  //do it
}

but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations.
I'm curious as to the best practices regarding the usage of the ^ operator.

A: if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
  //do it
}

IMHO this code could be simplified:
if(boolean1 != boolean2)
{
  //do it
}

A: With code clarity in mind, my opinion is that using XOR in boolean checks is not typical usage for the XOR bitwise operator. From my experience, bitwise XOR in Java is typically used to implement a mask flag toggle behavior:
flags = flags ^ MASK;

This article by Vipan Singla explains the usage case more in detail.
If you need to use bitwise XOR as in your example, comment why you use it, since it's likely to require even a bitwise literate audience to stop in their tracks to understand why you are using it.

A: You can simply use != instead.

A: I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.
If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.

A: I find that I have similar conversations a lot.  On the one hand, you have a compact, efficient method of achieving your goal.  On the other hand, you have something that the rest of your team might not understand, making it hard to maintain in the future.
My general rule is to ask if the technique being used is something that it is reasonable to expect programmers in general to know.  In this case, I think that it is reasonable to expect programmers to know how to use boolean operators, so using xor in an if statement is okay.
As an example of something that wouldn't be okay, take the trick of using xor to swap two variables without using a temporary variable.  That is a trick that I wouldn't expect everybody to be familiar with, so it wouldn't pass code review.

A: I think it'd be okay if you commented it, e.g. // ^ == XOR.

A: You could always just wrap it in a function to give it a verbose name:
public static boolean XOR(boolean A, boolean B) {
    return A ^ B;
}

But, it seems to me that it wouldn't be hard for anyone who didn't know what the ^ operator is for to Google it really quick. It's not going to be hard to remember after the first time. Since you asked for other uses, its common to use the XOR for bit masking.
You can also use XOR to swap the values in two variables without using a third temporary variable.
// Swap the values in A and B
A ^= B;
B ^= A;
A ^= B;

Here's a Stackoverflow question related to XOR swapping.

A: I personally prefer the "boolean1 ^ boolean2" expression due to its succinctness.
If I was in your situation (working in a team), I would strike a compromise by encapsulating the "boolean1 ^ boolean2" logic in a function with a descriptive name such as "isDifferent(boolean1, boolean2)".
For example, instead of using "boolean1 ^ boolean2", you would call "isDifferent(boolean1, boolean2)" like so:
if (isDifferent(boolean1, boolean2))
{
  //do it
}

Your "isDifferent(boolean1, boolean2)" function would look like:
private boolean isDifferent(boolean1, boolean2)
{
    return boolean1 ^ boolean2;
}

Of course, this solution entails the use of an ostensibly extraneous function call, which in itself is subject to Best Practices scrutiny, but it avoids the verbose (and ugly) expression "(boolean1 && !boolean2) || (boolean2 && !boolean1)"!

A: != is OK to compare two variables. It doesn't work, though, with multiple comparisons.

A: str.contains("!=") ^ str.startsWith("not(")

looks better for me than
str.contains("!=") != str.startsWith("not(")

A: If the usage pattern justifies it, why not? While your team doesn't recognize the operator right away, with time they could. Humans learn new words all the time. Why not in programming?
The only caution I might state is that "^" doesn't have the short circuit semantics of your second boolean check. If you really need the short circuit semantics, then a static util method works too.
public static boolean xor(boolean a, boolean b) {
    return (a && !b) || (b && !a);
}

A: As a bitwise operator, xor is much faster than any other means to replace it. So for performance critical and scalable calculations, xor is imperative.
My subjective personal opinion: It is absolutely forbidden, for any purpose, to use equality (== or !=) for booleans. Using it shows lack of basic programming ethics and fundamentals. Anyone who gives you confused looks over ^ should be sent back to the basics of boolean algebra (I was tempted to write "to the rivers of belief" here :) ).


Q: JavaFX - GridPane Background Image I've been searching around the internet, and I still haven't found a solution.
All I want to do is: Set an image to my GridPane in a POPUP-window, that I've made, when a button is clicked.
Some programmers refers to:
grid.setStyle("-fx-background-image: url('URL')");

Which were my suggestion as well, but it does not seem to work.
I've also tried to set
Image image = new Image();
and then set an ImageView, but with no luck!
Hope someone in here has a quick fix for this answer.

A: //root.setStyle("-fx-background-image: url('https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQxsasGQIwQNwjek3F1nSwlfx60g6XpOggnxw5dyQrtCL_0x8IW')");
This worked out. But not all url's it likes.

A: In case you are using FXML, you have to add stylesheets to your GridPane in the Controller class. For example, gridPane is the reference variable of your GridPane and app.css is a name of your stylesheets:
gridPane.getStylesheets().addAll(getClass().getResource("/css/app.css").toExternalForm())

Then write something like this in your stylesheets:
#gridPane { -fx-background-image:url("file:C:/path/to/your/project/folder/src/main/resources/image.jpg"); }

In addition, you can add stylesheets app.css to GridPane in the SceneBuilder.
The aforementioned procedure worked for me.


Q: How to read Json in Google Data Studio, Big Query, Json I am using Big Query for as a cloud data warehouse and DataStudio for vizualisation.
In Big Query I have a table with a column named data written in JSON.  I only want to extract what is inside the field "city".
This formula below that someone gave me worked to extract what is inside the field "title". I used it to create a field in DataStudio.
REPLACE(REGEXP_EXTRACT(data, '"title":(.+)","ur'), "\"", "")

So, I tried in multiple ways to reuse this formula for the "city" field, but it hasn't worked. I don't understand this code.
What's inside my column data:
 {
    "address":{
        "city":"This is what i want",
        "country":"blablabla",
        "lineAdresse":"blablabla",
        "region":"blablabla",
        "zipCode":"blablabla"
    },
    "contract":"blablabla",
    "dataType":"blablabla",
    "description":"blablabla",
    "endDate":{
        "_seconds":1625841747,
        "_nanoseconds":690000000
    },
    "entreprise":{
        "denomination":"blabla",
        "description":"1",
        "logo":"blablabla",
        "blabla":"blablabla",
        "verified":"false"
    },
    "id":"16256R8TOUHJG",
    "idEntreprise":"blablabla",
    "jobType":"blablabla",
    "listInfosRh":null,
    "listeCandidats":[

    ],
    "field":0,
    "field":0,
    "field":14,
    "field":"1625834547690",
    "field":true,
    "field":"",
    "field":"ref1625834547690",
    "skills":[
        "field",
        "field",
        "field"
    ],
    "startDate":{
        "_seconds":1625841747,
        "_nanoseconds":690000000
    },
    "status":true,
    "title":"this I can extract",
    "urlRedirection":"blablabla",
    "validated":true
}

If anyone knows the formula to put in Data Studio to extract what's inside city and can explain it to me, this would help a lot.
Here's the formula I tried but where I got "null" result:
REPLACE(REGEXP_EXTRACT(data,'"city":/{([^}]*)}/'),"\"","") >>null

I tried this one but it wouldn't stop at the city. I got the address, the region, zipcode and all the rest after:
REPLACE(REGEXP_EXTRACT(data, '"city":(.+)","ur'), "\"", "")

A: It is possible to parse a JSON in a text field by ignoring any hierarchy and only looking for a specific field. In your case the field names were title and city . Please be aware that this approach is not save for user entered data: By setting the value of the "city":"\" hide \"" the script cannot extract the city.
select *,
REGEXP_EXTRACT(data, r'"title":\s*"([^"]+)') as title,
REGEXP_EXTRACT(data, r'"city":\s*"([^"]+)') as city

from(
Select ' {     "address":{         "city":"This is what i want",         "country":"blablabla",         "lineAdresse":"blablabla",         "region":"blablabla",         "zipCode":"blablabla"     },     "contract":"blablabla",     "dataType":"blablabla",     "description":"blablabla",     "endDate":{         "_seconds":1625841747,         "_nanoseconds":690000000     },     "entreprise":{         "denomination":"blabla",         "description":"1",         "logo":"blablabla",         "blabla":"blablabla",         "verified":"false"     },     "id":"16256R8TOUHJG",     "idEntreprise":"blablabla",     "jobType":"blablabla",     "listInfosRh":null,     "listeCandidats":[              ],     "field":0,     "field":0,     "field":14,     "field":"1625834547690",     "field":true,     "field":"",     "field":"ref1625834547690",     "skills":[         "field",         "field",         "field"     ],     "startDate":{         "_seconds":1625841747,         "_nanoseconds":690000000     },     "status":true,     "title":"this I can extract",     "urlRedirection":"blablabla",     "validated":true }' as data
)


Q: apply "nopin" to "og:image" I'm not a coder but I was able to build my site from nonstop searching for "how to do xxxx" on this site. Thank you all so much for the posts and info!
I want to know how I can apply the "nopin" tag for pinterest to my "og:image"
Here is a link to a sample page http://jamesngart.com/harvester.html
I made a horizontally cropped image of the illustration to be used as the og:image for facebook and twitter links, but I dont want pinterest to pick it up. I used the nopin tag for some images that I dont want pinned and it worked, but I cant seem to apply it to the OG:image.
pin interest is also not picking up any of the data-pin info i enter, I was thinking to add "this is a cropped image please pin the others" but nothing works. Here is my code:
    <meta property="og:image" content="http://jamesngart.com/img/OG-Harvester.jpg" nopin="nopin" />

Thank you!
James

A: Reading various articles about this on the wide web, there seems to be very few guides for specific images, but this
http://allyssabarnes.com/2013/07/22/how-to-block-your-images-from-being-pinned/
link shows:
<meta name="pinterest" content="nopin" description="Enter your new description here" />

and

Which leads me to establish that due to Opengraph being a meta feature that you would need to do something like:
 <meta property="og:image" content="jamesngart.com/img/OG-Harvester.jpg" nopin="nopin" />

I would also hope you'd be using https://developers.pinterest.com/docs/getting-started/introduction/ for reference as well.
See also https://stackoverflow.com/a/10421287/3536236
Which actually states that (as of 2012) Pinterest does not directly reference OG:images in its processing.
Overall it's a little questionable why you would want to share an image on OpenGraph, (ie for Facebook and Google searches) that would then not be available for Pinterest specifically.

A: Don't add the nopin attribute to the facebook open (og) graph metatag.
Instead create a new meta tag and add it below or above the opengraph tag.
In the following example - pinning is disabled for the whole page:
<meta property="og:image" content="jamesngart.com/img/OG-Harvester.jpg" />
<meta name="pinterest" content="nopin" />
If you want to disable pinning per image you have to add the nopin attribute to the image (IMG) tag:

Read more about pinterest data-attributes and metatags in this article at csstricks


Q: assign array value to element using loop How can I give li the value of a,b,c? currently with my below code I got all c.
arr = ['a','b','c'];

arr.forEach(function(obj){
var x = obj;
    $('li').each(function () {
        $(this).text(x);
    });

});

Something is wrong with my code?

A: That is because you are iterating over all li when iterating over array and setting the value.  jquery .text() accepts function as argument which accepts index as parameter. This will eliminates the need of iterating over li and array elements:
var arr = ['a','b','c'];
$('li').text(function(i){
  return arr[i];
});

Working Demo

A: First, you set the text of all li to 'a', then to 'b' and finally to 'c'.
Instead, you may try iterating the li elements, and set the text content of the current one to the corresponding item in arr:
var arr = ['a','b','c'];
$('li').each(function(i) {
    $(this).text(arr[i]);
});

var arr = ['a','b','c'];
$('li').each(function(i) {
    $(this).text(arr[i]);
});

Alternatively (but similarly), you can iterate the array, and set the text content of the corresponding li to the current value:
var arr = ['a','b','c'],
    $li = $('li');
arr.forEach(function(txt, i) {
  $li.eq(i).text(txt);
});

var arr = ['a','b','c'],
    $li = $('li');
arr.forEach(function(txt, i) {
  $li.eq(i).text(txt);
});

A: You should iterate by arr, not by all li elements, you can do it like this:
arr = ['a','b','c'];
$.each(arr, function(i,v){
    $('li').eq(i).text(v);
});

This way you will assign exactly the same number of li text as there is elements in the array.

A: In your code, everytime the outer iterator performed, all
 was texted with the iteration result. So as a result you'll get all 'c'.
To do it right, you should code like this:
arr = ['a','b','c'];
$('li').each(function(index) {
    $(this).text(arr[index]);
});

A: The jQuery each() function will pass in an index, which you can use
arr = ['a','b','c'];

$('li').each(function(i) {
    $(this).text(arr[i]);
});


Q: How do I use Binder to perform dynamic bindings in my C# Function? I need to bind to an output blob, but the blob path needs to be computed dynamically in my function. How do I do it?

A: Have consolidated all of the information from this an other posts along with comments and created a blog post that demonstrates how to use Binder with a real world scenario. Thanks to @mathewc this became possible.

A: Binder is an advanced binding technique that allows you to perform bindings imperatively in your code as opposed to declaratively via the function.json metadata file. You might need to do this in cases where the computation of binding path or other inputs needs to happen at runtime in your function. Note that when using an Binder parameter, you should not include a corresponding entry in function.json for that parameter.
In the below example, we're dynamically binding to a blob output. As you can see, because you're declaring the binding in code, your path info can be computed in any way you wish. Note that you can bind to any of the other raw binding attributes as well (e.g. QueueAttribute/EventHubAttribute/ServiceBusAttribute/etc.) You can also do so iteratively to bind multiple times.
Note that the type parameter passed to BindAsync (in this case TextWriter) must be a type that the target binding supports.
using System;
using System.Net;
using Microsoft.Azure.WebJobs;

public static async Task<HttpResponseMessage> Run(
        HttpRequestMessage req, Binder binder, TraceWriter log)
{
    log.Verbose($"C# HTTP function processed RequestUri={req.RequestUri}");

    // determine the path at runtime in any way you choose
    string path = "samples-output/path";

    using (var writer = await binder.BindAsync<TextWriter>(new BlobAttribute(path)))
    {
        writer.Write("Hello World!!");
    }

    return new HttpResponseMessage(HttpStatusCode.OK);
}

And here is the corresponding metadata:
{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ]
}

There are bind overloads that take an array of attributes. In cases where you need to control the target storage account, you pass in a collection of attributes, starting with the binding type attribute (e.g. BlobAttribute) and inlcuding a StorageAccountAttribute instance pointing to the account to use. For example:
var attributes = new Attribute[]
{
    new BlobAttribute(path),
    new StorageAccountAttribute("MyStorageAccount")
};
using (var writer = await binder.BindAsync<TextWriter>(attributes))
{
    writer.Write("Hello World!");
}


Q: Android - Open new activity on item clicked in RecyclerView I'm creating a simple app for newbies, but I'm stuck at the main part. I created RecyclerView list. I want to know how to open a new Activity clicking on the first item in the ListView (see in screenshot).
Here is my MainActivity file:
public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    DrawerLayout drawerLayout;
    NavigationView navigationView;

    private ArrayList<String> countries;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    private void initViews() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        countries = new ArrayList<>();
        countries.add("Computer");
        countries.add("RAM");
        countries.add("ROM");
        countries.add("MotherBoard");
        countries.add("Printer");
        countries.add("CPU");
        countries.add("Pendrive");
        countries.add("Keyboard & Mouse");
        RecyclerView.Adapter adapter = new DataAdapter(countries);
        recyclerView.setAdapter(adapter);

        recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            GestureDetector gestureDetector = new GestureDetector(getApplicationContext(),
                new GestureDetector.SimpleOnGestureListener() {
                    @Override
                    public boolean onSingleTapUp(MotionEvent e) {
                        return true;
                    }
                });

            @Override
            public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
                View child = rv.findChildViewUnder(e.getX(), e.getY());
                if (child != null && gestureDetector.onTouchEvent(e)) {
                    int position = rv.getChildAdapterPosition(child);
                    Toast.makeText(getApplicationContext(), countries.get(position),
                        Toast.LENGTH_SHORT).show();
                }
                return false;
            }

            @Override
            public void onTouchEvent(RecyclerView rv, MotionEvent e) {
            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
            }
        });
    }
}

DataAdapter:
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
    private ArrayList<String> countries;

    public DataAdapter(ArrayList<String> countries) {
        this.countries = countries;
    }

    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
        viewHolder.tv_country.setText(countries.get(i));
    }

    @Override
    public int getItemCount() {
        return countries.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView tv_country;
        public ViewHolder(View view) {
            super(view);
            tv_country = (TextView)view.findViewById(R.id.tv_country);
        }
    }
}

A: You should use onItemClickListener or OnClickListener
 recyclerView.setOnClickListener(new View.OnClickListener() {
 ...
 }

A: In the onBindViewHolder function add onClickListner on items.
@Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {

    viewHolder.tv_country.setText(countries.get(i));
    viewHolder.tv_country.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });

}

In this example i added onCLickListner on tv_country. If you need further help ask me in comments.


Q: Different behaviour of self referential model. Is it a bug? It seems that I found a bug. I have two similar models that behave differently.
I have a Post model that belongs_to an Author.
I have a Task model that is self-referencing.
Model code:
app/models/author.rb:
class Author < ActiveRecord::Base
  has_many :posts
end

app/models/post.rb:
class Post < ActiveRecord::Base
  belongs_to :author

   scope :published, -> { where(status: 1) }

   after_create do
     puts '========================================='
     puts "author_id is present: '#{author_id}'"
     puts "what about task association? '#{author}'"
     puts '========================================='
   end
end

app/models/task.rb:
class Task < ActiveRecord::Base
  belongs_to :task
  has_many :tasks

  scope :published, -> { where(status: 1) }

  after_create do
    puts '========================================='
    puts "task_id is present: '#{task_id}'"
    puts "what about task association? '#{task}'"
    puts '========================================='
  end
end

Both Post and Task are similarly scoped, but behave differently:
Author.create.posts.published.create    # works

Task.create.tasks.published.create      # doesn't work

Task.create.tasks.create                # works

There is an after_create callback in Task model, where it should print the parent Task but it is nil despite task_id having the correct ID of parent.
Why is it behaving differently?


Q: Return String Generated by PHP Webpage I have a url like the following:
http://www.test.co.uk/Requests.php?accessToken=01XJSK
Depending on wether or not the access token is valid, either a 1 or 'invalidAT' is returned.  However when I try to return that value, I end up returning HTML and not the string.
This is what I am currently trying:
- (NSString *) getDataFrom:(NSString *)url{

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setHTTPMethod:@"GET"];
    [request setURL:[NSURL URLWithString:url]];

    NSError *error = [[NSError alloc] init];
    NSHTTPURLResponse *responseCode = nil;

    NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

    if([responseCode statusCode] != 200){
        NSLog(@"Error getting %@, HTTP status code %i", url, [responseCode statusCode]);
        return nil;
    }

    return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}

Can anyone explain how I go about returning either the '1' or the 'invalidAT'?

A: The url you give as an example "http://www.sonect.co.uk/Requests.php?accessToken=01XJSK", returns html with a frame that has "http://lvps92-60-123-84.vps.webfusion.co.uk/Requests.php?accessToken=01XJSK" as it's source:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>

<head>
 <title>www.sonect.co.uk</title>

</head>
<frameset rows="100%,*" border="0">
  <frame src="http://lvps92-60-123-84.vps.webfusion.co.uk/Requests.php?accessToken=01XJSK"  frameborder="0" />
  <frame frameborder="0" noresize />
</frameset>

<!-- pageok -->
<!-- 02 -->
<!-- -->
</html>

That source will return 1 as response.

A: You are being returned with iFrame source with
http://lvps92-60-123-84.vps.webfusion.co.uk/Requests.php?accessToken=01XJSK
You have to call this URL and you will get response.
In browser this run perfectly because of iFrame is getting executed.


Q: How to install NetBeans IDE 8.0.2 (php version) without losing data preference I have NetBeans IDE 8.0.2 installed with all supported technologies like C, C++, Java etc which is approximately 205Mb and that hampers my PC's performance as it load very slowly. So I just want to install the PHP module which is only 64Mb.
How do I install only the PHP version without losing my data preference and projects?

A: I would recommend a fresh install of your IDE, which can be done by:

*

*Find the NetBeans Project folder in My Documents

*Copy that to another location

*Un-install the IDE from Control Panel

*Restart you PC

*Download the php version here

*Install it, start your IDE and just copy paste the project to the folder created in My Document for NetBeansProject

As far the preferences are concerned, if they are not very hard to create once again, a fresh install is good to go with as removal of the other modules like C, C++, or Java from IDE directly would still keep some files or cache(NetBeans version dependent) which would still hamper your PC sometimes.

A: For installing Netbeans first of all you must have a latest version of Java  SDK installed on your PC.After that if you want to gain the data you must have the backup of the www folder which gets created while installation. After that  in Netbeans you can start a project and then copy-paste your created pages(php,html,css,js) in that project. And you are all set to start from where you left off.


Q: Efficiently preventing duplicate accesses I have a statement computing a multiply-accumulate operation that looks something like this:
return A->set(A->get() + B->get() * C->get());

Now, A, B, and C may not be unique, and I want to minimize redundant get()s. The only way I can think of optimizing this is with
  if (A == B && B == C) {
    double a = A->get();
    return A->set(a + a * a);
  } else if (A == B) {
    double a = A->get();
    return A->set(a + a * C->get());
  } else if (A == C) {
    double a = A->get();
    return A->set(a + B->get() * a);
  } else if (B == C) {
    double b = B->get();
    return A->set(A->get() + b * b);
  } else {
    return A->set(A->get() + B->get() * C->get());
  }

Is there a more efficient way? What about generalizing this to more than three arguments??

A: You can store them in a map. The solution can be extended easily to arbitrarily many pointers, but I've used three here for concreteness.
std::unordered_map<MyType *, double> computed_values;
for (MyType *p: {A, B, C}) {
    if (computed_values.find(p) == computed_values.end()) {
        computed_values[p] = p->get();
    }
}
double result = computed_values[A] + computed_values[B] * computed_values[C];
A->set(result);

As others have pointed out, make sure you profile to make sure this is actually worth the overhead of std::unordered_map lookups.

A: Assuming get() methods are really costly to the extent of producing measurable performance difference,
double a,b,c;
a = A->get();
b = (B==A?a:B->get());
c = (C==B?b:(C==A?a:c->get()));
return A->set(a+b*c);

A: Assuming the get() methods are reasonably cheap, you'd be better off just doing:
return A->set(A->get() + B->get() * C->get());

The other approach simply inserts a bunch of conditional jumps into your code, which could easily end up  being more expensive than the original code.


Q: React useEffect infinite loop despite empty array I have a react hook.
This hook has sub-hooks, that when generated, generate for themselves an ID.
This ID is always unique, as it is simply increased by 1 each time a new sub-hook is created.
const App = () => {
  const [ idCounter, setIdCounter ] = React.useState(0);

  const genId = () => {
    setIdCounter( id => id + 1 );
    return `ID-${idCounter}`;
  }

  const SomeComponent = () => {
    const [ componentId, setComponentId ] = React.useState(null);

    React.useEffect(() => {
      let generatedId = genId();
      setComponentId( id => generatedId );
      console.log(`generated '${generatedId}'`)
    }, []);

    return
nothing works

  }

  return <SomeComponent />
};

This loops and logs the generated id over and over again. Why on earth would it do this?
useEffect() is dependent on... nothing!! It should run only once, no?
How can I get this not to happen? I would like to be able to create several of SomeComponent from within App in the future.

A: First things first,

I would like to be able to create several of SomeComponent from within App in the future.

This (at least the way you're doing it) is not something that is possible or should be done at all when using React. You cannot create a component inside another component.
The reason your useEffect is in an infinite loop can be all sorts of things at the moment. It can be that it is not positioned in the highest scope, but my guess is that the following happens:
genId() is called, and state is updated, re-render is initialized (because of state update), and const SomeComponent = () => {...} is initialized again, thus activating useEffect again.
To fix this, first things first remove <SomeComponent /> from being created inside <App /> They should be completely separated. Secondly, pass the genId function as a prop, and add it to useEffect dependency list, since you need it there.
This would be a great start since now the code is semantically and by the rules correct.
const SomeComponent = ({ genId }) => {
  const [ componentId, setComponentId ] = React.useState(null);

  React.useEffect(() => {
    let generatedId = genId();
    setComponentId(generatedId);
    console.log(`generated '${generatedId}'`)
  }, [genId]);

  return
nothing works

}

const App = () => {
  const [ idCounter, setIdCounter ] = React.useState(0);

  const genId = () => {
    setIdCounter( id => id + 1 );
    return `ID-${idCounter}`;
  }

  return <SomeComponent genId={genId} />
};

A: I wont answer this but just make the point having sub-components have some disadvantages. You sub-componeentn is almost imposible to unit test. Maybe you can move it to top level componennt and accept generatedId as a prop
const SomeComponent = ({generatedId}) => {
    const [ componentId, setComponentId ] = React.useState(null);

    React.useEffect(() => {

      setComponentId( id => generatedId );
      console.log(`generated '${generatedId}'`)
    }, []);

    return
nothing works

}

const App = () => {
  const [ idCounter, setIdCounter ] = React.useState(0);

  const genId = () => {
    setIdCounter( id => id + 1 );
    return `ID-${idCounter}`;
  }

  return <SomeComponent  generatedId={genId()}/>
};


Q: Trying to change even list links css? So here's what I was trying to do
CSS:
li:nth-child(2n) {
background-color:gray;
}

HTML:

This works well. But when I try
li>a:nth-child(2n) {
    color:white;
}

This doesn't work IDK why?

A: You can use the even rule to target all the even children, like this.
li:nth-child(even) a {
   color: white;
}

Here's a reference: https://www.w3.org/Style/Examples/007/evenodd.en.html

A: In your first example, you are saying "the nth li" of which there are several. In the second example, you are saying "the nth a in a li" of which there is only one.

A: Perhaps it worked taking all lis together strange
   li:nth-child(2n)>a
   { color:white}


Q: Navigation not working in react-bootstrap suddenly My react app used to work with react-bootstrap and now suddenly the navigation is not working. Here is my package.json. At the moment, it only shows the "Roommates" brand but not other items like sign in or contact or about and there is a small button next to it, when i click on the button, it expands for a second, the menus show and disappear again, and also when the screen is small, the hamburger menu doesnt show.
{
 "name": "newreactstuff",
 "version": "0.1.0",
 "private": true,
 "dependencies": {
 "react": "^16.2.0",
 "react-bootstrap": "^0.32.1",
 "react-dom": "^16.2.0",
 "react-router": "^4.2.0",
 "react-router-dom": "^4.2.2",
 "react-scripts": "1.1.1"
  },
 "scripts": {
 "start": "react-scripts start",
 "build": "react-scripts build",
 "test": "react-scripts test --env=jsdom",
 "eject": "react-scripts eject"
  },
"proxy": "http://localhost:3001/"
}

Here is my Nav component
import React, { Component } from 'react';
import {
  Link
 } from 'react-router-dom';
import { NavItem } from 'react-bootstrap';
import { MenuItem } from 'react-bootstrap';
import { NavDropdown } from 'react-bootstrap';
import { Nav, Navbar, NavItem, NavDropdown, MenuItem, FormControl, FormGroup,
Button } from 'react-bootstrap';

class Navigation extends Component {

render() {
 return (
  <Navbar inverse collapseOnSelect>
   <Navbar.Header>
    <Navbar.Brand>
     <Link to="/">Roommates</Link>
   </Navbar.Brand>
   <Navbar.Toggle />
 </Navbar.Header>
 <Navbar.Collapse>

<Link to="/">Sign In</Link>

<Link to="/contact">Contact</Link>

<Link to="/about">About</Link>

  </Navbar.Collapse>
 </Navbar>
     )
   }
 }

export default Navigation;


Q: Why can't I use a ScrollView within a ColumnLayout? I have a ScrollView around a ListView. But when I put this in a ColumnLayout, the ListView disappears.
My actual code is larger and more complicated, but I've reduced the problem down to this small example.
import QtQuick 2.11
import QtQuick.Window 2.11
import QtQuick.Layouts 1.11
import QtQuick.Controls 2.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ListModel {
        id: theModel
        ListElement { display: "one" }
        ListElement { display: "two" }
        ListElement { display: "three" }
        ListElement { display: "four" }
        ListElement { display: "five" }
    }

    ColumnLayout {
        ScrollView
        {
            width: 150
            height: 150
            clip: true
            ListView {
                model: theModel
                anchors.fill: parent
                delegate: Column {
                    TextField {
                        text: display
                    }
                }
            }
        }
        Rectangle {
            color: "black"
            width: 100
            height: 30
        }
    }
}

Without the ColumnLayout and the Rectangle, I get a scrollable window showing part of the ListView as expected. But with them included, there is no sign of the ListView apart from some blank space above the rectangle.

A: A Qt Quick Layout resize all its children items (e.g. ColumnLayout resizes children's height, RowLayout resizes children's width), so you should use Layout attached property to indicate how to layout them, rather than setting the sizes. e.g.
ScrollView {
    Layout.maximumHeight: 150 // height will be updated according to these layout properties

    width: 150
    clip: true
    ListView {
        model: theModel
        anchors.fill: parent
        delegate: Column {
            TextField {
                text: display
            }
        }
    }
}

A: A Layout changes the sizes and positions of its children. But as I was specifying the sizes of the children I only wanted to change the positions. A Positioner is used for this (specifically, a Column instead of a ColumnLayout). Additionally I had not set the size of the parent Layout (/Positioner), so I now do this with anchors.fill: parent.
    Column {
        anchors.fill: parent
        ScrollView
        {
            width: 150
            height: 150
            clip: true
            ListView {
                model: theModel
                anchors.fill: parent
                delegate: Column {
                    TextField {
                        text: display
                    }
                }
            }
        }
        Rectangle {
            color: "black"
            width: 100
            height: 30
        }
    }

Thanks to other's comment and answer for helping me realize this!


Q: Driver.current_url not reflecting the opening of a link- selenium After using Selenium to log in to LinkedIn, I'm trying to navigate to the jobs page using the following:

jobs = driver.find_element(
    By.XPATH, '//*[@id="global-nav"]/div/nav/ul/li[3]/a')

jobs.click()

job_src = driver.page_source
print(driver.current_url)

The above returns: https://www.linkedin.com/feed/
However, looking at the browser that selenium opens up, it looks as though https://www.linkedin.com/jobs/? is clicked on.
Is my XPATH wrong? I copied it from Chrome Dev tools.
From there, I'm trying to scrape the job titles using :
soup = BeautifulSoup(job_src, 'html.parser')
job_list_html = soup.select('.job-card-list__title')

for job in job_list_html:
    print(job.get_text())

But all that's returned is an empty list.

A: The issue you are running into is that you need to wait until the page has loaded. Here is my suggestion.
First after you log in you can navigate directly to the job list URL. This is likely to be less fragile than using the XPath:
driver.get('https://www.linkedin.com/jobs/collections/recommended/')

The following is the most important piece you are missing:
wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'job-card-list__title')))

You can look into other wait commands here, but the above appeared to work for me.
Next, I noticed that this only lists a few jobs since the rest are dynamically loaded when you scroll. What I did is simulated the scrolling with:
driver.execute_script('res = document.querySelector("#main > div > section.scaffold-layout__list > div"); res.scrollTo(0, res.scrollHeight)')
time.sleep(2)

The sleep of 2 seconds is needed again to give time for that to execute before you get the source.
With that wait and the scroll, your code for getting the list of job names works.
job_src = driver.page_source
soup = BeautifulSoup(job_src, 'html.parser')
job_list_html = soup.select('.job-card-list__title')
print(len(job_list_html))
for job in job_list_html:
    print(job.get_text())

You may notice that the job list is paginated, so this code will only get the first page of jobs, but hopefully this gets you on the right track.


Q: Grouping rows from a single day into a count - MYSQL I've been trying to work through this problem for a bit, and clearly I'm missing something (probably something obvious).
I'm trying to group rows from a single day into a count. So the output should look like this:
Date         Count
2009-09-12   2
2009-09-13   5
2010-01-09   4

...and so on.
My current SQL looks like this:
SELECT `date`, COUNT(*) FROM `sales_flat_table` GROUP BY `date`;

And outputs data that looks like this:
Date        Count
2009-09-12  1
2009-09-12  1
2009-09-13  1
2009-09-13  1
2009-09-13  1
2009-09-13  1
2009-09-13  1

...and so on.
What am I missing? Thanks!

A: My best guess is that date is really a datetime and it has a time component.  To get just the date, use the date() function:
SELECT date(`date`) as `date`, COUNT(*)
FROM `sales_flat_table`
GROUP BY date(`date`);


Q: Filtering permutations of strings What I'm trying to do is create a set of permutations of a string which contains a '[' and ']' in the string. Then, add only the strings that were created by the create_perm which contains an '[' as the first and ']' as the last to a new set and return that set.
What I've done:
def create_perm(lst_str):
    if len(lst_str) <= 1:
        return {lst_str}
    old_set = set()
    for idx, c in enumerate(lst_str):
        for perm in create_perm(lst_str[:idx] + lst_str[idx+1:]):
            old_set.add(c + perm)
    return old_set

def perm(lst_str):
    new_set = set()
    for idx in create_perm(lst_str):
        if idx.startswith('[') and idx.endswith(']'):
                new_set.add(idx)
    return new_set

Examples:
perm('[1]2')
{'[12]', '[21]'}
perm('[1]23')
{'[123]', '[213]', '[321]', '[312]', '[231]', '[132]'}
perm('[1]2,3')
{'[2,13]', '[3,21]', '[12,3]', '[,213]', '[2,31]', '[,312]', '[1,23]', '[13,2]', '[321,]', '[312,]', '[,132]', '[23,1]', '[123,]', '[,321]', '[1,32]', '[132,]', '[,231]', '[3,12]', '[32,1]', '[21,3]', '[213,]', '[,123]', '[31,2]', '[231,]'}

so,
first I create the permutations of a string which contain a '[' and ']' within:
>>> create_perm('[2,],1')
{',]2,[1', '2,1,][', '2][1,,', ',][2,1', ']2,1,[', ',[,]12', '1,],[2', ',[2,1]', ',[12],', '2[,]1,', '1][,,2', ',,]2[1', '1[2,],', ...}

then return a new set with only the strings that begin with '[' and ends with ']
>>> perm('[2,],1')
{'[,2,1]', '[2,,1]', '[12,,]', '[1,,2]', '[,12,]', '[,21,]', '[21,,]', '[2,1,]', '[,,21]', '[,1,2]', '[,,12]', '[1,2,]'}

I can just call perm and that will call create_perm within.
The problem with this is that it can take quite a while when more characters are added to the string. But I think I know what to do to increase the speed a bit, and here's my idea:
Idea:
When creating the permutations of the string, don't bother adding/creating strings that don't start with '[' and end with ']' into the set, then we can simply remove the perm function which loops through each item and checks if the string starts with a '[' and ends with a ']'. In the end, there will be less amount of items to check therefore increasing the speed.
But how would of I go upon changing the create_perm function to not create strings that don't start with '[' and end with ']'?
Any help would be appreciated. If there is an even more better approach than my idea please let me know

A: Just strip them out, you don't need them to generate the perms.
def create_perm(lst_str):
    li = list(lst_str.replace('[','').replace(']',''))
    for perm in itertools.permutations(li):
        yield '[{}]'.format(''.join(perm))

demo:
list(create_perm('[1]2,'))
Out[102]: ['[12,]', '[1,2]', '[21,]', '[2,1]', '[,12]', '[,21]']

This uses itertools.permutations instead of recursively generating the perms.

A: Why can't you strip out the brackets, generate all permutations of the resulting string, then put the brackets around each result?


Q: ConnectionPoolTimeoutException: Timeout waiting for connection from pool putObject () s3Client Java I'm uploading image files to s3 using the s3 aws client in my java application, but sometimes I've been getting the error
ERROR 9 --- [io-8080-exec-27] b.c.i.h.e.handler.HttpExceptionHandler   : com.amazonaws.SdkClientException: Unable to execute HTTP request: Timeout waiting for connection from pool
com.amazonaws.SdkClientException: Unable to execute HTTP request: Timeout waiting for connection from pool
Caused by: org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool

but I haven't identified the reason for this error to occur and what solution I need to implement. I observed in the documentation the implementation of a ClientConfiguration setMaxConnections and passing it to the AmazonS3ClientBuilder object, but I believe that this would be increasing the problem and not actually correcting it, would I be correct?
I did not find detail why this problem with connection pooling occurs when using putObject (), if someone knows the reason or can explain through my implementation why this problem occurs. In our application there is also a configuration for SQS Config for queues
S3Config
public class S3Config {

    @Bean
    public AmazonS3 s3client() {
            return AmazonS3ClientBuilder.standard()
                    .build();
    }
}

Service Upload
public List<String> uploadImage(Long id, List<MultipartFile> files) throws Exception {
    Random rand = new Random();
    Product product = this.productService.findById(id);
    List<String> imgPath = new ArrayList<>();
    for (MultipartFile file : files) {
      String name = (product.getName() + this.brandService.findBrandById(product.getBrand()).getName() + rand.nextInt(999999)).replaceAll(" ", "-");
      String fullPath = this.s3Service.uploadImageFile(
              file,'.' + Objects.requireNonNull(file.getOriginalFilename()).split("\\.")[1],
              name,
              awsBucketProperties.getName(),
              awsBucketProperties.getEndpoint());
      imgPath.add(this.utils.removeImageDomain(fullPath));
    }
    return imgPath;
  }

Service S3
public String uploadImageFile(final MultipartFile file, final String ext, final String filename, final String bucketName, final String bucketEndpoint) throws IOException {

        byte[] imageData = file.getBytes();
        InputStream stream = new ByteArrayInputStream(imageData);
        String s3FileName = filename + ext;
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(stream.available());

        try {
            s3client.putObject(new PutObjectRequest(bucketName, s3FileName, stream, metadata)
                    .withCannedAcl(CannedAccessControlList.PublicRead));
        } catch (AmazonClientException ex) {
            ex.printStackTrace();
        }
        return String.format("%s/%s", bucketEndpoint, s3FileName);
    }


Q: How to load Html page which is outside application context using JSP include or c:import or symlink I need to load some html pages created dynamically by some other application into my application jsp page using jsp include tag <jsp:include page="${Htmlpath}" /> OR <jsp:include page="D:\MySharedHTML\test.html" />. My idea is to have a shared folder on server like "MySharedHTML" and let other application create html files there and my app will access by giving full path. But jsp include is saying "requested resource D:\MySharedHTML\test.html is not available". Any inputs how to do it. Thanks In Advance.

A: It has to be available by an URL. The D:\MySharedHTML\test.html is very definitely not a valid URL. A valid URL look like this http://localhost:8080/MySharedHTML/test.html.
Whether to use <jsp:include> or <c:import> depends on whether the URL is an internal or an external URL. The <jsp:include> works only on internal URLs (thus, resources in the same webapp, also the ones privately hidden in /WEB-INF). The <c:import> works additionally also on external URLs (thus, resources in a completely different webapp, but those have to be publicly accessible; i.e. you have got to see the desired include content already when copypasting the URL in browser's address bar).
In your particular case, you seem to have it elsewhere in the server's local disk file system which is not available by a true URL at all. In that case you've basically 2 options:

*

*Add the root folder of that path as a virtual host to the server configuration. How to do that depends on the server make/version which you didn't tell anything about. To take Tomcat as an example, that would be a matter of adding the following entry to its /conf/server.xml:
<Context docBase="D:\MySharedHTML" path="/MySharedHTML" />

This way all of the folder's contents is available by http://localhost:8080/MySharedHTML/*, including the test.html. This way you can use <c:import> on it (note: <jsp:include> is inapplicable as this is not in the same webapp).
<c:import url="/MySharedHTML/test.html" />

*Create a servlet which acts as a proxy to the local disk file system. Let's assume that you're using Servlet 3.0 / Java 7 and that you can change ${Htmlpath} variable in such way that it merely returns test.html, then this should do:
@WebServlet("/MySharedHTML/*")
public class PdfServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getPathInfo().substring(1);
        File file = new File("D:\\MySharedHTML", filename);
        response.setHeader("Content-Type", getServletContext().getMimeType(filename));
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "inline; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
        Files.copy(file.toPath(), response.getOutputStream());
    }

}

(when not using Servlet 3.0 / Java 7 yet, just fall back to the obvious web.xml regisration and InputStream/OutputStream loop boilerplate)
As the servlet runs in the same webapp, <jsp:include> should work just fine:
<jsp:include page="/MySharedHTML/${HtmlFilename}" />

A: You don't include by full path. The folder MySharedHTML will need to be under your application folder, and you include by relative path.
So say your webapp was at
 c:\Program Files\Apache Software Foundation\Tomcat\webapps\myapp\

You would put your MySharedHTML in there
 c:\Program Files\Apache Software Foundation\Tomcat\webapps\myapp\MySharedHTML

And then include by relative path:
 <jsp:include page="./MySharedHTML/test.html" />

A: Alternatively we can achieve with the help of symlink or shortlink or softlink, so that there will be no much coding. What I did in my case is created a softlink for MySharedHTML, which is under my application web content to some path in D drive.
As symlinks are disabled by default to enable them in your Tomcat server, you need add below configuration to context.xml, which is under conf folder of tomcat server.
<Context allowLinking="true">


Q: ValueError: need more than 1 value to unpack, split a line I have a file with questions and answers on the same line, I want to seperate them and append them to their own empty list but keep getting this error:
builtins.ValueError: need more than 1 value to unpack
questions_list = []
answers_list = []

questions_file=open('qanda.txt','r')

for line in questions_file:
    line=line.strip()

    questions,answers =line.split(':')

    questions_list.append(questions)
    answers_list.append(answers)

A: This is probably because when you're doing the splitting, there is no :, so the function just returns one argument, and not 2. This is probably caused by the last line, meaning that you're last line has nothing but empty spaces. Like so:
>>> a = '   '
>>> a = a.strip()
>>> a
''
>>> a.split(':')
['']

As you can see, the list returned from .split is just a single empty string. So, just to show you a demo, this is a sample file:

a: b
c: d
e: f

g: h

We try to use the following script (val.txt is the name of the above file):
with open('val.txt', 'r') as v:
    for line in v:
        a, b = line.split(':')
        print a, b

And this gives us:
Traceback (most recent call last):
a  b

c  d
  File "C:/Nafiul Stuff/Python/testingZone/28_11_13/val.py", line 3, in <module>

    a, b = line.split(':')
e  f
ValueError: need more than 1 value to unpack

When trying to look at this through a debugger, the variable line becomes \n, and you can't split that.
However, a simple logical ammendment, would correct this problem:
with open('val.txt', 'r') as v:
    for line in v:
        if ':' in line:
            a, b = line.strip().split(':')
            print a, b

A: line.split(':') apparently returns a list with one element, not two.
Hence that's why it can't unpack the result into questions and answers. Example:
>>> line = 'this-line-does-not-contain-a-colon'
>>> question, answers = line.split(':')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

A: Try:
question, answers = line.split(':', maxsplit=1)
question, __, answers = line.partition(':')

Also in Python 3 you can do something else:
question, *many_answers = line.split(':')

which looks like:
temp = line.split(':')
question = temp[0]
many_answers = tuple(temp[1:])

A: The reason why this happens could be a few, as already covered in the other answers. Empty line, or maybe a line only have a question and no colon. If you want to parse the lines even if they don't have the colon (for example if some lines only have the question), you can change your split to the following:
questions, answers, garbage = (line+'::').split(':', maxsplit=2)

This way, the values for questions and answers will be filled if they are there, and will be empty it the original file doesn't have them. For all intents and purposes, ignore the variable garbage.


Q: Is it possible to use wrapper functions in .so library? If not, is there anything that can provide the same functionality? In a binary foo, it calls function pthread_mutex_lock(). I do not have access to its source code, so I cannot recompile it. But I want to make it use my own implementation of locks.
To use my own locks, I want to create a library lock.so, then use LD_PRELOAD to replace the original pthread_mutext_lock calls. But I need to use pthread_mutex_lock in the middle of my implementation of lock(). Is there anyway I can use wrapper functions (-Wl,-wrap=pthread_mutex_lock) to do that? I believe the ld is performed by the linker, is it? So if I cannot use the wrapper function, how can I do it?
Thanks for any suggestions.


Q: Disnake: delete ephemeral interaction response I have a bot that allows users to play games with slash commands. The bot responds with ephemeral messages. To keep it tidy, it would like to remove some responses (e.g. if the user doesn't react after a few minutes). However, I'm struggling to remove ephemeral messages.
The bot is sending a response with:
await inter.send(file=file, embed=embed,components=components, ephemeral=True)

If ephermal=False, the following code deletes the bot response:
await inter.delete_original_message()

However, if ephermal=True, I get the following error when trying to delete the message:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/disnake/ext/commands/slash_core.py", line 680, in invoke
await call_param_func(self.callback, inter, self.cog, **kwargs)
File "/usr/local/lib/python3.8/site-packages/disnake/ext/commands/params.py", line 817, in call_param_func
return await maybe_coroutine(safe_call, function, **kwargs)
File "/usr/local/lib/python3.8/site-packages/disnake/utils.py", line 580, in maybe_coroutine
return await value
File "/code/cogs/game.py", line 271, in game
await game(
File "/code/cogs/game.py", line 189, in game
await inter.delete_original_message()
File "/usr/local/lib/python3.8/site-packages/disnake/interactions/base.py", line 526, in delete_original_message
await deleter
File "/usr/local/lib/python3.8/site-packages/disnake/webhook/async_.py", line 222, in request
raise NotFound(response, data)
disnake.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message

Is there another way of deleting ephemeral messages?
The relevant documentation section: https://docs.disnake.dev/en/latest/api.html#disnake.ApplicationCommandInteraction.delete_original_message
Edit:
whentrying to set the delete_after property of the ephemeral message I get:
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: ephemeral messages can not be deleted via endpoints

I guess this is a hint that discord does not allow ephemeral messages to be deleted via API by any means.

A: You figured it out, but overall the Discord API does not allow you to delete an ephemeral message. The best you can get is changing the message content.


Q: How to increase Animation Duration on every click in JS? CSS
#plus{ animation-duration: 5s;}

I want to increase it on every click using JavaScript...
JS Code
var increasePlus = document.getElementById("plus");
increasePlus.addEventListener('click', () => {
var sec= 5 + "s";
if(sec=="5s"){
   sec = 6 + "s";
   increasePlus.style.animationDuration = sec;
}
if(sec=="6s"){
   sec = 7 + "s";
   increasePlus.style.animationDuration = sec;
}
});

It doesn't work !!!

A: Going through the logic of the given code we can see that the animation-duration is always set to the same amount (7s) on every click - it never changes after the first click:
var increasePlus = document.getElementById("plus");
increasePlus.addEventListener('click', () => {
var sec= 5 + "s";
if(sec=="5s"){//this is always true as sec has just been set to 5s
   sec = 6 + "s";//so sec is set to 6s
   increasePlus.style.animationDuration = sec;
}
if(sec=="6s"){//this is always true as sec has (just) been set to 6s
   sec = 7 + "s";//so sec is now set to 7s
   increasePlus.style.animationDuration = sec;//and so the animation-duration is ALWAYS set to 7s on a click
}
});

It is difficult to click on a moving object which is what the given code seems to require (the clickable element id plus is also the one given the animation duration in that code) so in this snippet the plus element gets clicked and that updates the animation duration of a separate object which is the one that moves.

    const increasePlus = document.getElementById("plus");
    const theObject = document.getElementById('object');

    increasePlus.addEventListener('click', () => {

    //get the current animation-duration
    //remember this has an s at the end so we need to get rid of that so we can add to it
    let sec= window.getComputedStyle(theObject, null)["animationDuration"].replace('s','');
    //add 1 to it
    sec++;
    //and set the animation-duration
    theObject.style.animationDuration = sec + 's';
    });
#plus{
  font-size: 60px;
}

#object {
  position: relative;
  animation-name: move;
  animation-duration: 5s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

  width: 100px;
  height: 100px;
  background-color: magenta;
}

@keyframes move {
  0% {
    top: 0;
  }
  100% {
    top: 30vh;
  }
}
  <button id="plus">+</button>

A: I think this can fail because of this line
var sec= 5 + "s";

this line will execute always when you click on the button, so after that in "if" condition you will always get sec = '5s' and than it will be decreased to '4s'.
If you want that code to work, you could place "var sec = 5+'s' above the listener declaration.


Q: Spring data mongo can't save GeoData b/c of No property type found When trying to update an object with geoData spring data mongo throws the ff exception
org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property type found on org.springframework.data.mongodb.core.geo.GeoJsonGeometryCollection!
an example object structure is like this
class Location{
    ....
    @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
    GeoJsonGeometryCollection geomerty
}

repository
interface LocationRepository extends MongoRepository<Location, String> {

}

the save method (which is called on update)
//the exception is thrown here
locationRepository.save(updatedLocation)

I haven't added the type field, it is added by GeoJsonGeometryCollection conveter .
Any workaround is welcome.

A: It started working when I upgraded my spring boot version from 1.3 to 1.4


Q: Symfony2 DoctrineFixturesBundle namespace error I have a big problem with the fixtures bundle which I can't resolve. I
follow the steps as they are meant to be followed, adding the lines to
the deps file, installing them, registering them in the autoload and
appkernel.
When I try to run even only app/console, it breaks with:
Fatal error: Class 'Doctrine\Bundle\DoctrineBundle\Command\DoctrineCommand'
not found in /var/www/.../bundles/Doctrine/Bundle/FixturesBundle/
Command/LoadDataFixturesDoctrineCommand.php on line 40
Which seems right because I don't have a DoctrineBundle directory
under Doctrine\Bundle, only the DoctrineFixturesBundle.
If I change that line to Symfony\Bundle\DoctrineBundle\... it works
perfectly, because that class resides under that namespace actually.
Of course I can't leave it that way.
I searched through the documentation, issues, everything, but it seems
that noone has this same issue, so I must be missing some obvious
point here.
Any ideas?
Thanks

A: Not long ago, all Doctrine bundles moved to the Doctrine organizaton. This causes some confusion based on which repository and branch you are using.
If you're using Symfony 2.0.x, then your deps should look something like this:
[DoctrineFixturesBundle]
    git=http://github.com/doctrine/DoctrineFixturesBundle.git
    target=bundles/Symfony/Bundle/DoctrineFixturesBundle
    version=origin/2.0

Notice the target/namespace is actually Symfony\Bundle\DoctrineFixturesBundle.

However, you shouldn't have any problems using the latest DoctrineFixturesBundle with Symfony 2.0.x - as long as you upgrade the rest of the Doctrine dependencies also. You can use this in your deps instead:
[doctrine-common]
    git=http://github.com/doctrine/common.git
    version=2.2.0

[doctrine-dbal]
    git=http://github.com/doctrine/dbal.git
    version=2.2.1

[doctrine]
    git=http://github.com/doctrine/doctrine2.git
    version=2.2.0

[doctrine-fixtures]
    git=http://github.com/doctrine/data-fixtures.git

[DoctrineFixturesBundle]
    git=http://github.com/doctrine/DoctrineFixturesBundle.git
    target=bundles/Doctrine/Bundle/FixturesBundle


Q: How to save my javascript array to a file? My phonegap/iOS application has a file named data.js which contains an array. The application works with this array and some changes are stored into it.
Now when the user quits my application I want it to save the changes to the data.js file. Is there any way to do this?
UPDATE This is my array (the only thing in data.js):
var data = [
    [0, "A", "B", "0", "0"],
    [1, "C", "D", "0", "0"],
    [2, "E", "F", "0", "0"],
    ...
];

SOLVED!
I used JSON to stringify my array and save it to the localStorage. It only has to work with Mobile Safari, so this is a good solution. Thanks for giving me the hints that made me solve my problem.

A: If you are using phonegap than for sure you can work with file system.
Solution is to encode your array into JSON using serializeArray() method in JQuery.
Once you encode your array you will get JSON string which you have to store in a file using PhoneGap's Filewriter() function. For more detail on that visit this link.
I hope it helped you :-).

A: JavaScript cannot tamper with the file system directly. You can do one of two things:

*

*Save the changes onto a cookie and read it the next time

*Send the changes (via AJAX) to a PHP file which would generate a downloadable file on the server, and serve it to the client.
There are probably more solutions, but these are the most reasonable two I can think of.

A: Phonegap (at http://phonegap.com/tools/) is suggesting Lawnchair: http://westcoastlogic.com/lawnchair/
so you'd read that file into data.js instead of storing the data literally there

A: You could also save your array (or better yet its members) using localStorage, a key/value storage that stores your data locally, even when the user quits your app. Check out the guide in the Safari Developer Library.

A: use Lawnchair to save the array as a JSON object. The JSON object will be there in the memory till you clear the data for the application.
 If you want to save it permanently to a file on the local filesystem then i guess you can write a phonegap plugin to sent the data across to the native code of plugin which will create/open a file and save it.


Q: adding an EventListener to an Enter_Frame event function I was just curious if I add an a EventListener such as addEventListener(MouseEvent.CLICK, onClick);
Inside an ENTER_FRAME event function will it add an instance of that MouseEvent Listener every frame?
Here is my code now just wondering if this is bad practice:
    addEventListener(Event.ENTER_FRAME, engineLogic);

inside my engineLogic function:
    //Max objects for rock throwers on left
        if (aXPositionArray.length == 0)
        {
            //Remove listener to add more and make button turn grey etc
            rockThrowerSpawnScreen.left.removeEventListener(MouseEvent.CLICK, chooseSpawnSideRockThrowers);
            rockThrowerSpawnScreen.left.visible = false;
        }else
        if (aXPositionArray.length != 0)
        {
            rockThrowerSpawnScreen.left.addEventListener(MouseEvent.CLICK, chooseSpawnSideRockThrowers);
            rockThrowerSpawnScreen.left.visible = true;
            trace("LISTENER");
        }

or does it only add it once and checks the function every frame?


Q: To send an image every 50 ms., should I use TCP or UDP? I am building a C# application, using the server-client model, where the server is sending an image (100kb) to the client through a socket every 50ms...
I was using TCP, but besides the overhead of this protocol, sometimes the client ended up with more than one image on the socket. And I still haven't though of a clever mechanism to split the bytes of each image (actually, I just need the most recent one).
I tried using UDP, but got to the conclusion that I can't send 100kb dgrams, only 64kb ones. And even so, I shouldn't use more than 1500bytes; otherwise the packet would be divided along the network and the chances of losing parts of the packet would be greater.
So now I'm a bit confused. Should I continue using TCP and put some escaping bytes in the end of each image so the client can separate them? Or should I use UDP, send dgrams of 1500 bytes and come up with a mechanism for ordering and recovering?
The key goal here is transmitting the images very fast. I don't mind losing some on the way as long as the client keeps receiving newer ones.
Or should I use another protocol? Thanks in advance!

A: First of all, your network might not be able to handle this no matter what you do, but I would go with UDP. You could try splitting up the images into smaller bits, and only display each image if you get all the parts before the next image has arrived.
Also, you could use RTP as others have mentioned, or try UDT. It's a fairly lightweight reliable layer on top of UDP. It should be faster than TCP.

A: You should consider using Real-time Transport Protocol (aka RTP).
The underlying IP protocol used by RTP is UDP, but it has additional layering to indicate time stamps, sequence order, etc.
RTP is the main media transfer protocol used by VoIP and video-over-IP systems.  I'd be quite surprised if you can't find existing C# implementations of the protocol.
Also, if your image files are in JPEG format you should be able to produce an RTP/MJPEG stream.  There are quite a few video viewers that already have native support for receiving and displaying such a stream, since some IP webcams output in that format.

A: I'd recommend using UDP if:

*

*Your application can cope with an image or small burst of images not getting through,

*You can squeeze your images into 65535 bytes.

If you're implementing a video conferencing application then it's worth noting that the majority use UDP.
Otherwise you should use TCP and implement an approach to delimit the images. One suggestoin in that regard is to take a look at the RTP protocol. It's sepcifically designed for carrying real-time data such as VoIP and Video.
Edit: I've looked around quite a few times in the past for a .Net RTP library and apart from wrappers for non .Net libraries or half completed ones I did not have much success. I just had another quick look and this may be of this one ConferenceXP looks a bit more promising.

A: The other answers cover good options re: UDP or a 'real' protocol like RTP.
However, if you want to stick with TCP, just build yourself a simple 'message' structure to cover your needs.  The simplest?  length-prefixed.  First, send the length of the image as 4 bytes, then send the image itself.  Easy enough to write the client and server for.

A: If the latest is more important than every picture, UDP should be your first choice.
But if you're dealing with frames lager than 64K your have to-do some form of re-framing your self. Don't be concerned with fragmented frames, as you'll have to deal with it or the lower layer will. And you only want completed pictures.
What you will want is some form of encapsulation with timestamps/sequences.


Q: Prevent "mv" command from raising error if no file matches the glob. eg" mv *.json /dir/ I want to move all JSON files created within a jenkins job to a different folder.
It is possible that the job does not create any json file.
In that case the mv command is raising an error and so that job is failing.
How do I prevent mv command from raising error in case no file is found?

A: Welcome to SO.
Why do you not want the error?
If you just don't want to see the error, then you could always just throw it away with 2>/dev/null, but PLEASE don't do that. Not every error is the one you expect, and this is a debugging nightmare. You could write it to a log with 2>$logpath and then build in logic to read that to make certain it's ok, and ignore or respond accordingly --
mv *.json /dir/ 2>$someLog
executeMyLogParsingFunction # verify expected err is the ONLY err

If it's because you have set -e or a trap in place, and you know it's ok for the mv to fail (which might not be because there is no file!), then you can use this trick -
mv *.json /dir/ || echo "(Error ok if no files found)"

or
mv *.json /dir/ ||: # : is a no-op synonym for "true" that returns 0

see https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html
(If it's failing simply because the mv is returning a nonzero as the last command, you could also add an explicit exit 0, but don't do that either - fix the actual problem rather than patching the symptom. Any of these other solutions should handle that, but I wanted to point out that unless there's a set -e or a trap that catches the error, it shouldn't cause the script to fail unless it's the very last command.)
Better would be to specifically handle the problem you expect without disabling error handling on other problems.
shopt -s nullglob # globs with no match do not eval to the glob as a string
for f in *.json; do mv "$f" /dir/; done # no match means no loop entry

c.f. https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html
or if you don't want to use shopt,
for f in *.json; do [[ -e "$f" ]] && mv "$f" /dir/; done

Note that I'm only testing existence, so that will include any match, including directories, symlinks, named pipes... you might want [[ -f "$f" ]] && mv "$f" /dir/ instead.
c.f. https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html

A: This is expected behavior -- it's why the shell leaves *.json unexpanded when there are no matches, to allow mv to show a useful error.
If you don't want that, though, you can always check the list of files yourself, before passing it to mv. As an approach that works with all POSIX-compliant shells, not just bash:
#!/bin/sh

# using a function here gives us our own private argument list.
# that's useful because minimal POSIX sh doesn't provide arrays.
move_if_any() {
  dest=$1; shift  # shift makes the old $2 be $1, the old $3 be $2, etc.
  # so, we then check how many arguments were left after the shift;
  # if it's only one, we need to also check whether it refers to a filesystem
  # object that actually exists.
  if [ "$#" -gt 1 ] || [ -e "$1" ] || [ -L "$1" ]; then
    mv -- "$@" "$dest"
  fi
}

# put destination_directory/ in $1 where it'll be shifted off
# $2 will be either nonexistent (if we were really running in bash with nullglob set)
# ...or the name of a legitimate file or symlink, or the string '*.json'
move_if_any destination_directory/ *.json

...or, as a more bash-specific approach:
#!/bin/bash

files=( *.json )
if (( ${#files[@]} > 1 )) || [[ -e ${files[0]} || -L ${files[0]} ]]; then
  mv -- "${files[@]}" destination/
fi

A: Loop over all json files and move each of them, if it exists, in a oneliner:
for X in *.json; do [[ -e $X ]] && mv "$X" /dir/; done


Q: Refer to an object initialized Asynchronously with an HTTP service I have a class that contains an array of an object called LearningElementDTO , which is being initialized on the ngOnInit() method  Asynchronously with observable .
the problem i have is when i try to refer to this array at the loading of the component , i got the  error :
Cannot read property '0' of undefined
the problem here is that i refer to the object LearningElementDTO[0] befor it was initialized .

  private learningElements: LearningElementDTO[];

  constructor(private service: LearningService) { }

  ngOnInit() {
    this.loadData();

    // here is where the undefined problem happens
    console.log(this.learningElements[0].name);
  }
  private loadData(): void {
    this.service.getLearningElements().subscribe(
      (reponse: any) => {
        this.learningElements = reponse;
      }
    );
  }
}

is there any workaround to avoid referring to abjects that are initialized in the same way ?

A: You can use pipe for this:
private learningElements: LearningElementDTO[];

constructor(private service: LearningService) { }

ngOnInit() {
    this.loadData().subscribe(reponse => {
      console.log(this.learningElements[0].name);
    });
}

private loadData(): Observable<LearningElementDTO[]>{
    return this.service.getLearningElements().pipe(
      map((reponse: any) => {
        this.learningElements = reponse;
        return response;
      })
     );
  }
}

A: When your console.log is executed, the response hasn't come back yet. You need to move this code into your subscribe function after you assign the server response to your local variable this.learningElements
this.service
    .getLearningElements()
    .subscribe(response => {
        this.learningElements = response;
        console.log(this.learningElements[0].name);
    });


Q: Using construtors with Integer I'm newbe in Java and I've got some questions about using constructors.
In what situations I should use new Integer() statement? Look at the code:
    Integer a = 129;//1
    Integer b = new Integer(129);//2
    List<Integer> list= new ArrayList<Integer>();
    list.add(new Integer(1));//3
    list.add(2);//4

Which row is the example of bad programming practise?

A: Using new Integer() will guarantee that you have a new Integer object reference.
Using the value directly will not guarantee that, since auto boxing int to Integer may not do that object instantiation.
I would say that you will only need new Integer(1) in really strange edge cases, so most of the time I would say you never need to do new Integer...
Also please bear in mind that auto boxing / unboxing may produce some errors in some edge cases.
Integer x = null;
int y = x; // Null Pointer Exception

Long iterations where auto(un)boxing is happening may have a performance cost that an untrained eye might not notice

A: Use autoboxing as a default pattern - it's been about forever and makes life ever-so-slightly easier.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, ..

While there are slight difference with new Integer (see other answers/comments/links), I generally do not consider using new Integer a good approach and strictly avoid it.


Q: Can Java Web Start be configured to update the current server version instead of the latest? Summarizing my research so far it seems as if Java Web Start will use the timestamp provided via a web server to determine whether a certain jar has been updated or not. The update behaviour can be influenced by the jnlp element "update" where elements "check" and "policy" which allow to define how often an update check will be done and whether the user is prompted to confirm the update or not.
However I did not find any opportunity to define another mechanism than the timestamp comparison to determine if an application has been updated or not. Actually we're having a discussion at the moment if it makes more sense (for us) if not the newest, but the current server version should be downloaded to the client. This could also e.g. be an older server version which has been restored on the server, because a formerly active newer server version has been rolled backed.
In case of a server-sided application rollback every user has to manually clear its Java cache at the moment, which is of course possible but not very convenient.
Can Java Web Start be configured/forced to always download the application version from the server if this is "different" from the locally cached version?

A: I don't konw if it exactly meets your need, but have a look at webstart's Version Download Protocol.
To sum  it up:
With versioned download you can specify each jar-version to be used in the jnlp-file like this:
    <jar href="jackson-core.jar" version="2.0.2" />

and deploy your jar-file on the server  with a filename of jackson-core__V2.0.2.jar.
With this protocol webstart will only use jar-files whose version exactly matches the given version from the jnlp-file. Another advantage is, that when the specified version is already present in the local cache webstart will not try to download the version again - regardless of timestamps etc.
Advantages:

*

*Full control over versions used via jnlp-file.

*Less download-requests for jars present in cache

Disadvantages:

*

*New versions require a change in the jnlp-file

*Not suitable for SNAPSHOT-builds since the file's timestamp is completely ignored and version-numbers don't change for SNAPSHOT-builds.


Q: Issue with foreach Laravel This Question is continuation of My first question
So I have an array
Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 79
                    [name] => shelin
                    [status] => 0
                )

            [1] => stdClass Object
                (
                    [id] => 80
                    [name] => shanu
                    [status] => 2
                )

            [2] => stdClass Object
                (
                    [id] => 81
                    [name] => linto
                    [status] => 2
                )

            [3] => stdClass Object
                (
                    [id] => 82
                    [name] => joseph
                    [status] => 0
                )

        )

)

I sort this array
$sorted = $collection->sortByDesc('status');

my view
return view('voyager::users.viewusersAppraisals')->with('values', $sorted);

Now, I got array like
Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
                [2] => stdClass Object
                    (
                        [id] => 81
                        [name] => linto
                        [status] => 2
                    )

            [1] => stdClass Object
                (
                    [id] => 80
                    [name] => shanu
                    [status] => 2
                )

            [0] => stdClass Object
                (
                    [id] => 79
                    [name] => shelin
                    [status] => 0
                )

            [3] => stdClass Object
                (
                    [id] => 82
                    [name] => joseph
                    [status] => 0
                )

        )

)

and my foreach loop
 @foreach($values as $data)<?php

?>

                                {{$data->name}}

                            @endforeach

I expect output like so
linto
shanu
shelin
joseph

But I get output like so
 joseph
linto
shanu
shelin

Any help would be appreciated. Thanks in advance.

A: It must be your variable be getting overwritten somewhere in the code which you have not mentioned.
Also please dd($sorted) your result after executing the eloquent query to see whether you are getting data from db in right format as per your need.


Q: Excel: How to format a 10 digit number into date time I have a number like so 2016031802 and I want it to show up as 2016/03/18 2:00 so that I can use it in a graph of something/time where time is incremented hourly. How can I go about formatting this number so that it shows up in date time format?
I am using Excel 2011.

A: Use this:
=DATE(LEFT(A1,4),MID(A1,5,2),MID(A1,7,2))+TIME(RIGHT(A1,2),0,0)

Then format the cells with a custom format of:
yyyy/mm/dd h:mm


Q: AVR SBI for SPI Ports H+ atmega2560 I'm am not that strong in avr/assembly and I'm having problems selecting "CS" from PORTH on atmega2560 ... can you help me?
the code:
#define DDR_CS  _SFR_IO_ADDR(DDRH), 5   // MMC CS pin (DDR, PORT)
#define PORT_CS _SFR_IO_ADDR(PORTH), 5

#define DDR_CK  _SFR_IO_ADDR(DDRB), 1   // MMC SCLK pin (DDR, PORT)
#define PORT_CK _SFR_IO_ADDR(PORTB), 1

#define DDR_DI  _SFR_IO_ADDR(DDRB), 2   // MMC DI pin (DDR, PORT)
#define PORT_DI _SFR_IO_ADDR(PORTB), 2

#define PIN_DO  _SFR_IO_ADDR(PINB), 3   // MMC DO pin (PIN, PORT)
#define PORT_DO _SFR_IO_ADDR(PORTB), 3

;---------------------------------------------------------------------------;
.nolist
#include <avr/io.h>
.list
.text

;---------------------------------------------------------------------------;
; Initialize MMC port
;
; void init_spi (void);

.global init_spi
.func init_spi
init_spi:
     sbi    DDR_CS      ; CS: output
     sbi    DDR_DI      ; DI: output
     sbi    DDR_CK      ; SCLK: output
     sbi    PORT_DO     ; DO: pull-up
     ret
.endfunc

The error that I'm geting:

asmfunc.S:44: Error: number must be positive and less than 32

I found this post and I think this is the answer bat I don't know how to write it in the correct syntax.


Q: how to implement background services in react native? How to implement background service in my app? I want to run the app in the background always without user interaction