Categories
discuss

Audio duration returns NaN

Accessing an HTML5 audio element (a .ogg file) with JavaScript in Chrome. The file does play properly, yet somehow it will not recognize the duration.

I just cribbed this code: https://www.w3schools.com/jsref/prop_audio_duration.asp (I know w3schools isn’t great, but it seems like something else is the problem…)

var x = document.getElementById("testTone").duration;
console.log("duration:"+x);  // duration:NaN

var y = document.getElementById("testTone");
y.play();   // works!

the element…

<audio controls id="testTone">
    <source src="autoharp/tone0.ogg" type="audio/ogg">
</audio>

Answer

Add preload="metadata" to your tag to have it request the metadata for your audio object:

<audio controls id="testTone" preload="metadata">
    <source src="autoharp/tone0.ogg" type="audio/ogg">
</audio>

In your code, attach an event handler, to set the duration when the metadata has been loaded:

var au = document.getElementById("testTone");
au.onloadedmetadata = function() {
    console.log(au.duration)
};
Categories
discuss

Removing a bootstrap popover dynamically using jquery

This following works when a list item is selected and then hovered and a popover is shown. But when I try to remove popover data attributes from list tag, all the tag removes but the popover does not remove. How to remove the popover such that when an item is not selected, the popover is not shown?

/* Latest compiled and minified JavaScript included as External Resource */
// Checked list box items

$(function() {
  $('.list-group.checked-list-box .list-group-item').each(function() {



    // Settings
    var $widget = $(this),
      $checkbox = $('<input type="checkbox" class="hidden" />'),
      color = ($widget.data('color') ? $widget.data('color') : "primary"),
      style = ($widget.data('style') == "button" ? "btn-" : "list-group-item-"),
      settings = {
        on: {
          icon: 'glyphicon glyphicon-check'
        },
        off: {
          icon: 'glyphicon glyphicon-unchecked'
        }
      };

    $widget.css('cursor', 'pointer')
    $widget.append($checkbox);

    // Event Handlers
    $widget.on('click', function() {
      $checkbox.prop('checked', !$checkbox.is(':checked'));
      $checkbox.triggerHandler('change');
      updateDisplay();
    });
    $checkbox.on('change', function() {
      var id = $(this).closest('li').attr('id');
      var isChecked = $checkbox.is(':checked');
      if (isChecked) addPopOver(id);
      else removePopOver(id);
      updateDisplay();
    });

    function addPopOver(id) {
      id = "#" + id;
      $(id).attr('data-toggle', "popover");
      $(id).attr('data-trigger', "hover");
      $(id).attr('data-original-title', $(id).text());
      $(id).attr('data-content', "(No items selected)");
      $('[data-toggle=popover]').popover();
    }

    function removePopOver(id) {
      id = "#" + id;
      $(id).removeAttr("data-toggle");
      $(id).removeAttr("data-trigger");
      $(id).removeAttr("data-original-title");
      $(id).removeAttr("data-content");
    }
    // Actions
    function updateDisplay() {
      var isChecked = $checkbox.is(':checked');

      // Set the button's state
      $widget.data('state', (isChecked) ? "on" : "off");

      // Set the button's icon
      $widget.find('.state-icon')
        .removeClass()
        .addClass('state-icon ' + settings[$widget.data('state')].icon);

      // Update the button's color
      if (isChecked) {
        $widget.addClass(style + color + ' active');
      } else {
        $widget.removeClass(style + color + ' active');
      }
    }

    // Initialization
    function init() {

      if ($widget.data('checked') == true) {
        $checkbox.prop('checked', !$checkbox.is(':checked'));
      }

      updateDisplay();

      // Inject the icon if applicable
      if ($widget.find('.state-icon').length == 0) {
        $widget.prepend('<span class="state-icon ' + settings[$widget.data('state')].icon + '"></span>');
      }
    }
    init();
  });

  $('#get-checked-data').on('click', function(event) {
    event.preventDefault();
    var checkedItems = {},
      counter = 0;
    $("#check-list-box li.active").each(function(idx, li) {
      checkedItems[counter] = $(li).text();
      counter++;
    });
    $('#display-json').html(JSON.stringify(checkedItems, null, 't'));
  });
});
/* Check Box For item required */

.state-icon {
  left: -5px;
}

.list-group-item-primary {
  color: rgb(255, 255, 255);
  background-color: rgb(66, 139, 202);
}


/* DEMO ONLY - REMOVES UNWANTED MARGIN */

.well .list-group {
  margin-bottom: 0px;
}

.list-inline>li {
  display: inline-block;
  padding-right: 12px;
  padding-left: 20px;
  margin-bottom: 3px;
  font-size: 17px;
}

#check-list-box {
  padding: 10px;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>

<ul id="check-list-box" class="list-group checked-list-box list-inline ">
  <li class="list-group-item event-item" id="venue" data-color="danger">Venue</li>
  <li class="list-group-item event-item" id="catering" data-color="info">Catering</li>
  <li class="list-group-item event-item" id="desserts" data-color="warning">Desserts</li>
  <li class="list-group-item event-item" id="photographer" data-color="success">Photographer</li>
  <li class="list-group-item event-item" id="bus" data-color="danger">Party buses</li>
  <li class="list-group-item event-item" id="castles" data-color="danger">Bouncy Castles</li>
  <li class="list-group-item" data-color="danger">Other</li>
  <!--<input type="textbox" name ="other" >-->
</ul>

Answer

You could use .popover('destroy').

function removePopOver(id) {
      id = "#" + id;
      $(id).popover('destroy')
}
Categories
discuss

Node Fetch Post Request using Graphql Query

I’m trying to make a POST request with a GraphQL query, but it’s returning the error Must provide query string, even though my request works in PostMan.

Here is how I have it running in PostMan:

enter image description here

enter image description here

And here is the code I’m running in my application:

const url = `http://localhost:3000/graphql`;    
return fetch(url, { 
  method: 'POST',
  Accept: 'api_version=2',
  'Content-Type': 'application/graphql',
  body: `
    {
      users(name: "Thomas") { 
        firstName
        lastName 
      } 
    }
  `
})
.then(response => response.json())
.then(data => {
  console.log('Here is the data: ', data);
  ...
});

Any ideas what I’m doing wrong? Is it possible to make it so that the body attribute I’m passing in with the fetch request is formatted as Text like I’ve specified in the PostMan request’s body?

Answer

The body is expected to have a query property, containing the query string. Another variable property can be passed as well, to submit GraphQL variables for the query as well.

This should work in your case:

const url = `http://localhost:3000/graphql`;
const query = `
  {
    users(name: "Thomas") { 
      firstName
      lastName 
    } 
  }
 `

return fetch(url, { 
  method: 'POST',
  Accept: 'api_version=2',
  'Content-Type': 'application/graphql',
  body: JSON.stringify({ query })
})
.then(response => response.json())
.then(data => {
  console.log('Here is the data: ', data);
  ...
});

This is how to submit GraphQL variables:

const query = `
  query movies($first: Int!) {
    allMovies(first: $first) {
      title
    }
  }
`

const variables = {
  first: 3
}

return fetch('https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr', {
  method: 'post',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({query, variables})
})
.then(response => response.json())
.then(data => {
  return data
})
.catch((e) => {
  console.log(e)
})

I created a complete example on GitHub.

Categories
discuss

Android/Kotlin: unresolved reference: timber

I’m trying to write a kotlin library for Android and can’t include timber. I always get the following error:

Error:error: unresolved reference: timber

I have this in my build.gradle:

apply plugin: 'java-library'
apply plugin: 'kotlin'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
}

sourceCompatibility = "1.8"
targetCompatibility = "1.8"

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        maven {url "https://maven.google.com"}
        mavenCentral()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    compile 'com.jakewharton.timber:timber:4.5.1'
    testCompile 'junit:junit:4.12'
}

My source file is very simple at the moment:

package net.mbonnin.test

import timber.log.Timber

class Main() {

    fun main() {
        Timber.d("hello world")
    }
}

It fails on the import statement.

I’m using Android studio 3 canary 4 and kotlin 1.1.2-4. Any idea what I’m doing wrong ? Or is timber not usable in kotlin ?

Answer

apply plugin: 'java-library'
apply plugin: 'kotlin'

You’re not applying any android plugin and thus don’t know how to handle @aar artifacts. But these are the default artifacts when using Android libraries. Sometimes you might find @jar artifacts with the dependency as well, but not that often any more. And Timber is

A logger with a small, extensible API which provides utility on top of Android’s normal Log class.

You could teach Gradle to understand @aar files, but then you’d run into issues with the Android dependencies when using Timber.

So basically you have to make you module an Android Kotlin library instead.

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
Categories
discuss

Why does the closure compiler create void 0 instead of shorter alternatives?

Comparing these strings:

{}[0]
[][0]
void 0

Why does Closure Compiler generate

void 0

when it could generate

[][0]

or

{}[0]

or even

[].a

as torazaburo mentioned which are 1 character shorter?

Answer

Minimum code size isn’t the only goal of the Closure compiler. Another goal (I assume) is to generate code that is as fast as the original.

void 0 is likely to be faster across various JavaScript runtimes. It doesn’t have to construct an object or array and dereference a nonexistent property.

A JavaScript runtime engine could possibly optimize away the {}[0] or [][0], but why would the Closure compiler want to depend on that? If those don’t get optimized away, they would be significantly slower than void 0.

Keep in mind that JavaScript code is usually downloaded in compressed form, and if void 0 appears in multiple places they are likely to get compressed out.

Also see Blaise’s answer for another good reason not to use {}[0] or [][0].

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..