Given a search string, fetch all movies results from the api

Was told this code was ‘weird’ and didn’t pass the coding test. I tried to split up to show the different levels of abstraction but maybe I went overboard? I told them this in the walk through of the code as things like console logging would be something more like save to database or something more complex so it’s its own abstraction.

const https = require('https'); /*  * Complete the function below.  * Use console.log to print the result, you should not return from the function.  * Base url: https://jsonmock.hackerrank.com/api/movies/search/?Title=  */ async function getMovieTitles(substr) {      // get first page results     const results = await fetchMoviePage(substr, 1);     let matches = results.data.map(extractMovieTitle);      // base case - if we only have one page of results then we done here     if (results.total_pages === 1) {         return sortAndPrintResults(matches);     }      // fill an incremented integer array from page 2 to last page     const pages = fillRange(2, results.total_pages);      // for each page fetch data and add to results list     for await (const page of pages) {         const { data } = await fetchMoviePage(substr, page);         matches = matches.concat( data.map(extractMovieTitle) );     }      sortAndPrintResults(matches); }  /**  * send sorted results to stdout  */ function sortAndPrintResults(results){     console.log(results.sort().join('\n')); }  /**  * fetches a page of movie results.  */ async function fetchMoviePage(substr, page) {     try {         return await fetchMatchingMovies(substr, page);      } catch (error) {         console.log(`Error retrieving movies for $  {substr} on page $  {page}: $  {error}`);         return {data:[]};     } }  /**  * Fills an array of incremented integers from start to end  */ function fillRange(start, end) {     return Array(end - start + 1).fill().map((item, index) => start + index); };  /**  * returns the movie title from a movie object  */ function extractMovieTitle(movie) {     return movie.Title; }  /**  * fetch a list of movies matching a search string  */ function fetchMatchingMovies(searchString, page) {     const queryString = `https://jsonmock.hackerrank.com/api/movies/search/?Title=$  {searchString}&page=$  {page}`;      return new Promise((resolve, reject) => {          https.get(queryString, res => {             let data = '';             res.on('data', chunk => data += chunk);             res.on('end', () => resolve(JSON.parse(data)));          }).on('error', e => reject(e));     }); } 

Fetch Link field Label and Link separately in views-view-fields template

How can I fetch label and link field in views-view-fields–VIEW-NAME-HERE.html.twig file

So far I have tried

{{ fields.field_action_link.content }} give me the anchor tag prebuilt (html) {{ fields.field_action_link.0.url }} {{ content.field_action_link[0]['#url'] }} 

but none of them seems to work for me. I am able to retrieve all other fields including image field.

Trying to fetch document sets only in a given library

i have build a console app to fetch the document sets and upload a document in a particular doc set in a given library. Before adding a document I am fetching all the document set using caml query. It was working fine till I add a document. After adding a document it throws an exception of “object reference is not set to an instance of an object.” After checking the item in the library, I saw that there is no title for the document which I have uploaded, which indeed throwing exception.

I just want to fetch the document set only and not documents. Is there a way to achieve this? Please help. Thanks

Fetch the multiple images from JSON using foreach

I am fetching the images & its positions from JSON using foreach…. Is there any way i can improve code standard for performance & other things….

var target;  let jsonData = {   "path" : " newyear collage\/",   "info" : {     "author" : "",     "keywords" : "",     "file" : "newyear collage",     "date" : "sRGB",     "title" : "",     "description" : "Normal",     "generator" : "Export Kit v1.2.8"   },   "name" : "newyear collage",   "layers" : [     {       "x" : 0,       "height" : 612,       "layers" : [         {           "x" : 0,           "color" : "0xFFFFFF",           "height" : 612,           "y" : 0,           "width" : 612,           "shapeType" : "rectangle",           "type" : "shape",           "name" : "bg_rectangle"         },         {           "x" : 160,           "height" : 296,           "layers" : [             {               "x" : 0,               "height" : 296,               "src" : "ax0HVTs.png",               "y" : 0,               "width" : 429,               "type" : "image",               "name" : "mask_image_1"             },             {               "radius" : "26 \/ 27",               "color" : "0xACACAC",               "x" : 188,               "y" : 122,               "height" : 53,               "width" : 53,               "shapeType" : "ellipse",               "type" : "shape",               "name" : "useradd_ellipse1"             }           ],           "y" : 291,           "width" : 429,           "type" : "group",           "name" : "user_image_1"         },         {           "x" : 25,           "height" : 324,           "layers" : [             {               "x" : 0,               "height" : 324,               "src" : "hEM2kEP.png",               "y" : 0,               "width" : 471,               "type" : "image",               "name" : "mask_image_2"             },             {               "radius" : "26 \/ 27",               "color" : "0xACACAC",               "x" : 209,               "y" : 136,               "height" : 53,               "width" : 53,               "shapeType" : "ellipse",               "type" : "shape",               "name" : "useradd_ellipse_2"             }           ],           "y" : 22,           "width" : 471,           "type" : "group",           "name" : "user_image_2"         }       ],       "y" : 0,       "width" : 612,       "type" : "group",       "name" : "newyearcollage08"     }   ] };   $  (document).ready(function() {      // upload image onclick      $  ('.container').click(function(e) {          var res = e.target;         target = res.id;         console.log(target);         if (e.target.getContext) { 		// click only inside Non Transparent part             var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;             if (pixel[3] === 255) {                 setTimeout(() => {                     $  ('#fileup').click();                 }, 20);             }         }      });      function getAllSrc(layers) {         let arr = [];         layers.forEach(layer => {             if (layer.src) {                 arr.push({                     src: layer.src,                     x: layer.x,                     y: layer.y                 });             } else if (layer.layers) {                 let newArr = getAllSrc(layer.layers);                 if (newArr.length > 0) {                     newArr.forEach(({                         src,                         x,                         y                     }) => {                         arr.push({                             src,                             x: (layer.x + x),                             y: (layer.y + y)                         });                     });                 }             }         });         return arr;     }       function json(data)          {             var width = 0;             var height = 0;              let arr = getAllSrc(data.layers);              let layer1 = data.layers;             width = layer1[0].width;             height = layer1[0].height;             let counter = 0;             let table = [];              for (let {                     src,                     x,                     y                 } of arr) {                  $  (".container").css('width', width + "px").css('height', height + "px").addClass('temp');                  var mask = $  (".container").mask({                     maskImageUrl: 'https://i.imgur.com/' + src,                     onMaskImageCreate: function(img) {                          img.css({                             "position": "absolute",                             "left": x + "px",                             "top": y + "px"                         });                      },                     id: counter                 });                 table.push(mask);                 fileup.onchange = function() {                      let mask2 = table[target];                     mask2.loadImage(URL.createObjectURL(fileup.files[0]));                     document.getElementById('fileup').value = "";                 };                 counter++;             }          }  json(jsonData); }); // end of document ready  // jq plugin   (function($  ) {     var JQmasks = [];     $  .fn.mask = function(options) {         // This is the easiest way to have default options.         var settings = $  .extend({             // These are the defaults.             maskImageUrl: undefined,             imageUrl: undefined,             scale: 1,             id: new Date().getUTCMilliseconds().toString(),             x: 0, // image start position             y: 0, // image start position             onMaskImageCreate: function(div) {},         }, options);           var container = $  (this);          let prevX = 0,             prevY = 0,             draggable = false,             img,             canvas,             context,             image,             timeout,             initImage = false,             startX = settings.x,             startY = settings.y,             div;          container.mousePosition = function(event) {             return {                 x: event.pageX || event.offsetX,                 y: event.pageY || event.offsetY             };         }          container.selected = function(ev) {             var pos = container.mousePosition(ev);             var item = $  (".masked-img canvas").filter(function() {                 var offset = $  (this).offset()                 var x = pos.x - offset.left;                 var y = pos.y - offset.top;                 var d = this.getContext('2d').getImageData(x, y, 1, 1).data;                 return d[0] > 0             });              JQmasks.forEach(function(el) {                 var id = item.length > 0 ? $  (item).attr("id") : "";                 if (el.id == id)                     el.item.enable();                 else el.item.disable();             });         };          container.enable = function() {             draggable = true;             $  (canvas).attr("active", "true");             div.css({                 "z-index": 2             });         }          container.disable = function() {             draggable = false;             $  (canvas).attr("active", "false");             div.css({                 "z-index": 1             });         }          container.onDragStart = function(evt) {             if (evt.target.getContext) {                 var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;                  $  (canvas).attr("active", "true");                 container.selected(evt);                 prevX = evt.clientX;                 prevY = evt.clientY;                 var img = new Image();                 evt.originalEvent.dataTransfer.setDragImage(img, 10, 10);                 evt.originalEvent.dataTransfer.setData('text/plain', 'anything');              }         };          container.getImagePosition = function() {             return {                 x: settings.x,                 y: settings.y,                 scale: settings.scale             };         };          container.onDragOver = function(evt) {              if (evt.target.getContext) {                 var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;                 if (pixel[3] === 255) {                     if (draggable && $  (canvas).attr("active") === "true") {                         var x = settings.x + evt.clientX - prevX;                         var y = settings.y + evt.clientY - prevY;                         if (x == settings.x && y == settings.y)                             return; // position has not changed                         settings.x += evt.clientX - prevX;                         settings.y += evt.clientY - prevY;                         prevX = evt.clientX;                         prevY = evt.clientY;                         container.updateStyle();                     }                 } else {                     evt.stopPropagation();                     return false;                 }             }         };          container.updateStyle = function() {             clearTimeout(timeout);             timeout = setTimeout(function() {                 //context.clearRect(0, 0, canvas.width, canvas.height);                 context.beginPath();                 context.globalCompositeOperation = "source-over";                 image = new Image();                 image.setAttribute('crossOrigin', 'anonymous');                 image.src = settings.maskImageUrl;                 image.onload = function() {                     canvas.width = image.width;                     canvas.height = image.height;                     context.drawImage(image, 0, 0, image.width, image.height);                     div.css({                         "width": image.width,                         "height": image.height                     });                 };                  img = new Image();                 img.src = settings.imageUrl;                 img.setAttribute('crossOrigin', 'anonymous');                 img.onload = function() {                     settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;                     settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;                     context.globalCompositeOperation = 'source-atop';                     context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);                     initImage = false;                 };             }, 20);         };          // change the draggable image         container.loadImage = function(imageUrl) {             console.log("load");             if (img)                 img.remove();             // reset the code.             settings.y = startY;             settings.x = startX;             prevX = prevY = 0;             settings.imageUrl = imageUrl;             initImage = true;             container.updateStyle();         };          // change the masked Image         container.loadMaskImage = function(imageUrl, from) {             if (div)                 div.remove();             canvas = document.createElement("canvas");             context = canvas.getContext('2d');             canvas.setAttribute("draggable", "true");             canvas.setAttribute("id", settings.id);             settings.maskImageUrl = imageUrl;             div = $  ("<div/>", {                 "class": "masked-img"             }).append(canvas);              // div.find("canvas").on('touchstart mousedown', function(event)             div.find("canvas").on('dragstart', function(event) {                  if (event.handled === false) return;                 event.handled = true;                 container.onDragStart(event);             });              div.find("canvas").on('touchend mouseup', function(event) {                 if (event.handled === false) return;                 event.handled = true;                 container.selected(event);             });              div.find("canvas").bind("dragover", container.onDragOver);             container.append(div);             if (settings.onMaskImageCreate)                 settings.onMaskImageCreate(div);             container.loadImage(settings.imageUrl);         };         container.loadMaskImage(settings.maskImageUrl);         JQmasks.push({             item: container,             id: settings.id         })         return container;     }; }(jQuery));
.temp {}  .container { 	background: gold;   position: relative;   }  .masked-img { 	overflow: hidden;	 	position: relative; }
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>  <input id="fileup" name="fileup" type="file" style="display:none" >  <div class="container">  </div>

Tablas dinamicas a partir de fetch y php

tengo una duda. ¿Cómo puedo hacer que se actualice una tabla (en la vista de un usuario “X”) a partir de la inserción de datos desde otro perfil de usuario (un usuario “Y”)? Estoy usando fetch api de javascrpt para hacer las peticiones a un script php, sin embargo no tengo idea de como hacer que en cuanto alguien inserte un registro se active el fetch api y me muestre el nuevo registro en la vista. Algo mas o menos como los mensajes de facebook (que en cuanto se envía el mensaje se notifica al receptor y se lo muestra)

From server, how recognize javascript fetch() call was made (asp.net mvc)

From inside an asp.net controller action, I’m interested in knowing if the call was made by a javascript fetch() call. Is there any part of the Request object that I can interrogate to discover this?

For example, if I’m interested in knowing if the caller is a javascript $ .ajax call, on the server-side I can call this method:

Request.IsAjaxRequest(); 

and if it returns true I know that the call was something like this:

       $  .ajax({         url: '/MyDomain/MyControllerAction',         type: 'GET',         success: function (data) {             doSomething(data);         },         error: function (XMLHttpRequest, ajaxOptions, ex) {             doSomethingElse(XMLHttpRequest, ajaxOptions, ex);     }); 

Is there something like this I can call or interrogate to discover if the caller was a javascript fetch(), eg a call like this:

fetch('/MyDomain/MyControllerAction')        .then(function (data) {           if(data.ok){             return data.json();            }         })         .then(function (data) {             doSomething(data)         })         .catch(function (error) {             doSomethingElseAgain(error);         }); 

“Fetch the data if it doesn’t exist” selector?

Let’s say I have a react component like this:

const MyComponent = ({data}) => (<div>{JSON.stringify(data)}</div>);   const myReduxSelector = (state, id) => state.someData[id];   export default connect(     (state, ownProps) => ({      data: myReduxSelector(state, ownProps.someId)     }) )(MyComponent);  

Now this works fine, if the data already exists.

What’s the tidiest way to handle this, if the data doesn’t already exist?

The only way I can really see to to this, to add an onMount/construct function to dispatch an action that will fetch it.

eg.

class MyComponent extends React.Component {      constructor(props) {         super(props);          if (!props.data) {             this.props.fetchData();          }     }      render() {        const {data} = this.props;            return <div>{JSON.stringify(data)</div>;      }  }  export default connect(     (state, ownProps) => ({          data: myReduxSelector(state, ownProps.someId)      }),      (dispatch, ownProps) => ({         fetchData: () => dispatch(createFetchDataAction(ownProps.someId))      }) )(MyComponent);  

The problem with this is – say I have lots of components that all do this, it just becomes a pain to write and maintain.

Is there a tidy, established pattern for solving this problem? Use of redux-saga is acceptable.

Can Apple Mail fetch gmail signatures?

My organisation’s people use a mixture of Apple Mail and Gmail.com as a client for our Gmail addresses. We use a GSuite app to set peoples’ Gmail signatures, which works great for those sending email from Gmail.com, but the signature is not ‘imported’ by Apple Mail. This means people have to manually copy their Gmail signature into the Apple Mail signature preferences. Is there any way to remedy this?

I understand that this may not be a shortcoming of Apple Mail, but a shortcoming of Gmail.