text:
Q: How do I highlight the marker on the map when click on matching carousel corresponding to the marker to the map? Say the first carousel slide is Los Angeles California and when click on it, the red dot marker on the map will change its color to like blue on Los Angeles, CA coordinate. When click on the 2nd slide the 1st highlighted marker will back to default red and the new marker will be highlighted to blue.
I am not sure how to go about connecting these two using Vanilla JS.
If logic connects, I can easily change the red dot color using CSS.

I am using DataMaps to render the USA map with coordinates of certain cities from a JSON file and slick-carousel for the bottom carousel.
JSON
[
    {
        "city": "Madison",
        "state": "WI",
        "latitude": 43.07199845990384,
        "longitude": -89.40813691528471
    },
    {
        "city": "Columbus",
        "state": "OH",
        "latitude": 40.00178899021552,
        "longitude": -83.01964928313465
    }
]

Here I fetch the json file, initialization of DataMaps and logic for populate json objects into carousel HTMLs.
// Get JSON data
fetch('assets/json/cities.json')
  .then(function (response) {
      return response.json();
  })
  .then(function (data) {
      appendData(data);
  })
  .catch(function (err) {
      console.log('error: ' + err);
  });

var map = new Datamap({
  element: document.getElementById("map"),
  responsive: true,
  height: null,
  width: null,
  scope: 'usa',
  geographyConfig: { // USA map color
    popupOnHover: false,
    highlightOnHover: false,
    borderWidth: 1,
    borderOpacity: 0.6,
    borderColor: '#ffffff'
  },
  bubblesConfig: { // USA city popup color
    borderWidth: 1,
    borderOpacity: 1,
    borderColor: '#c5002e',
    popupOnHover: true,
    radius: null,
    fillOpacity: 1,
    animate: true,
    highlightOnHover: true,
    highlightFillColor: '#c5002e', //  hover dot color
    highlightBorderColor: '#c5002e',
    highlightBorderWidth: 1,
    highlightBorderOpacity: 1,
    highlightFillOpacity: 0.75,
    exitDelay: 100,
    key: JSON.stringify,
    popupTemplate: function(geography, data) {
      return '
' + data.name + '
';
    },
  },
    fills: {
      defaultFill: '#3a3a3a', // map color
      city: '#c5002e' //  dot color
  }
});

// Responsive map
window.addEventListener('resize', function() {
  map.resize();
});

// Loop to grab all json objects and render them in the page
function appendData(data) {
  for (var i = 0; i < data.length; i++) {
    var city = (data[i].city),
        state = (data[i].state),

    const locations = document.createElement("div");

    // Add html
    locations.innerHTML = `

${city} ${state}

    `;

    document.querySelector(".city__locations").append(locations)

  }

Slick-carousel code
//initilize city locations slick carousel
$(document).ready(function() {
  $(".city__locations").slick({
    dots: true,
    prevArrow: '<button type="button" class="city__locations-prev-button"/>',
    nextArrow: '<button type="button" class="city__locations-next-button"/>',
    infinite: true,
    slidesToShow: 4,
    slidesToScroll: 1,
    responsive: [
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 3,
          slidesToScroll: 1
        }
      },
      {
        breakpoint: 640,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 1
        }
      },
      {
        breakpoint: 480,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1
        }
      }
    ]
  });
});

HTML

Here is initial example in jsbin.
If this all work out, there is another date feature I would like to implement it. When the current date is bigger/equal to the date in the json date object, the red dot marker will also be highlighted it.
Any help is appreciated.
Thanks!

A: if you can add some data attributes to the
return '
' + data.name + '
';

then with the carousel divs wire up a mouse over event and then you can use the data attributes to match the div to the corresponding icon. With the date you can again add a custom CSS class in the above line to create a highlight a bit like so:
return '
' + data.name + '
';

It's hard to help without a minimal reproducible example
I hope this helps

A: Here is a glow effect, the glow is a bit much, CSS isn't my strong suit but should do what you wanted and you can tweak the CSS. I couldn't find a way to override the CSS on the map dots, so I used a div that is positioned in the create the glow effect

// Init USA map
var map = new Datamap({
  element: document.getElementById("map"),
  responsive: true,
  height: null,
  width: null,
  scope: 'usa',
  geographyConfig: { // USA map color
    popupOnHover: false,
    highlightOnHover: false,
    borderWidth: 1,
    borderOpacity: 0.6,
    borderColor: '#ffffff'
  },
  bubblesConfig: { // USA city popup color
    borderWidth: 1,
    borderOpacity: 1,
    borderColor: '#c5002e',
    popupOnHover: true,
    radius: null,
    fillOpacity: 1,
    animate: true,
    highlightOnHover: true,
    highlightFillColor: '#c5002e', //  hover dot color
    highlightBorderColor: '#c5002e',
    highlightBorderWidth: 1,
    highlightBorderOpacity: 1,
    highlightFillOpacity: 0.75,
    exitDelay: 100,
    key: JSON.stringify,
    popupTemplate: function(geography, data) {
      return '
' + data.name + '
';
    },
  },
  fills: {
    defaultFill: '#3a3a3a', // map color
    city: '#c5002e' //  dot color
  }
});

// Responsive map
window.addEventListener('resize', function() {
  map.resize();
});

// City popup
map.bubbles([{
    radius: 10,
    fillKey: 'city',
    name: 'Madison, WI',
    cityId: "1",
    latitude: 43.07199845990384,
    longitude: -89.40813691528471
  },
  {
    radius: 10,
    fillKey: 'city',
    name: 'Columbus, OH',
    cityId: "2",
    latitude: 40.00178899021552,
    longitude: -83.01964928313465
  },
  {
    radius: 10,
    fillKey: 'city',
    name: 'Gainesville, FL',
    cityId: "3",
    latitude: 29.645407365499,
    longitude: -82.348610942268
  },
  {
    radius: 10,
    fillKey: 'city',
    name: 'Chestnut Hill, MA',
    cityId: "4",
    latitude: 42.335294607839636,
    longitude: -71.16643600759312
  }
]);

//initilize city locations slick carousel
$(document).ready(function() {
  $(".city__locations").slick({
    dots: true,
    prevArrow: '<button type="button" class="city__locations-prev-button"/>',
    nextArrow: '<button type="button" class="city__locations-next-button"/>',
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 1,
    responsive: [{
        breakpoint: 1024,
        settings: {
          slidesToShow: 3,
          slidesToScroll: 1
        }
      },
      {
        breakpoint: 640,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 1
        }
      },
      {
        breakpoint: 480,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1
        }
      }
    ]
  });
  $(".city__locations-slide").each(function() {
    $(this).mouseover(function() {
      const location = $(this)
        .children(".city__locations__locations-slide-inner")
        .children("p").html()
      const mapMatch = $(".datamaps-bubble").filter(function() {
        return $(this).data("info").name === location
      })
      $(".glow").css({
        top: mapMatch.position().top + 'px',
        left: mapMatch.position().left + 'px',
      }).show();
    }).mouseout(function() {
      $(".glow").hide();
    })
  })
});
.glow {
  display: none;
  position: absolute;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #fff;
  box-shadow: 0 0 60px 30px #fff, 0 0 100px 60px #f0f, 0 0 140px 90px #0ff;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="robots" content="noindex">
  <meta name="viewport" content="width=device-width">
  <title>USA Map with carousel</title>

  <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/gh/kenwheeler/slick@1.8.1/slick/slick.css" />
  <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/gh/kenwheeler/slick@1.8.1/slick/slick-theme.css" />

Madison, WI

Columbus, OH

Gainesville, FL

Chestnut Hill, MA

https://jsfiddle.net/PatrickHume/e1m7quj6/90/
I hope this helps ?


text:
Q: Simple youtube javascript api 3 request not works i've tried to write a simple youtube request to search video with youtube javascript api v3.
This is the source code:
<!DOCTYPE html>

When i load this page on google chrome (updated), nothing happens, the page remains blank.
I have request the API Key for browser apps (with referers) and copied in the method gapi.client.setApiKey.
Anyone can help me?
Thanks

A: Try this example here
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google AJAX Search API Sample</title>

Loading...

A: When you use
you have to upload the html file somewhere online or use XAMPP on your PC
To use html for searching YT videos, using Javascript on PC, as I know, we need to use other codings:
1- Use javascript code similar to this for API version 2.0. Except only the existence of API KEY v3.
2- Use the jQuery method "$.get(..)" for the purpose.
See:

http://play-videos.url.ph/v3/search-50-videos.html
For more details see (my post "JAVASCRIPT FOR SEARCHING VIDEOS"):
http://phanhung20.blogspot.com/2015_09_01_archive.html

var maxRes = 50;
 function searchQ(){
      query = document.getElementById('queryText').value;
      email = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50'+
      '&order=viewCount&q='+ query + '&key=****YOUR API3 KEY*****'+
      '&callback=myPlan';
      var oldsearchS = document.getElementById('searchS');
      if(oldsearchS){
            oldsearchS.parentNode.removeChild(oldsearchS);
      }
      var s = document.createElement('script');
      s.setAttribute('src', email);
      s.setAttribute('id','searchS');
      s.setAttribute('type','text/javascript');
      document.getElementsByTagName('head')[0].appendChild(s);
  }

  function myPlan(response){
          for (var i=0; i<maxRes;i++){
          var videoID=response.items[i].id.videoId;
          if(typeof videoID != 'undefined'){
          var title=response.items[i].snippet.title;
          var links = '
'+
                '
'+(i+1)+ '. '+ title + '
';
          document.getElementById('list1a').innerHTML += links ;
          }
      }
 }

  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <input type="text"  value="abba" id="queryText" size="80">
  <button type="button" onclick="searchQ()">Search 50 videos</button>

A: I used the original code that Tom posted, It gave me 403 access permission error. When I went back to my api console & checked my api access time, it was expired. So I recreated the access time for the api. It regenerated new time. And the code worked fine with results.

A: Simply i must make request from a web server.
Thanks all for your reply

redpajama_set_name: RedPajamaStackExchange


text:
Q: copy song info from mp3 file to aac file from terminal I am trying to create a script that performs various conversions between formats of audio files. In one particular step, I use afconvert in Terminal to convert an mp3 to aac(mpeg4/m4a), but in this process all of the info attached to the audio file (name, artist etc) is lost. I tried to id3cp to copy over the info but this doesn't work (I think because aac files don't use ID3 tags...).
Could someone suggest a way of copying all of the associated info on the mp3 files to the aac (m4a) file? Is there a way it can be retained during the conversion (preferable) or alternately a Terminal command to copy the info over?

A: I prefer the mutagen Python library for tag editing, since it has good support for a wide variety of formats with a consistent interface. Here's a script for copying the metadata of a file:
import mutagen
import mutagen.easyid3
old = mutagen.easyid3.EasyID3('example.mp3')
new = mutagen.File('example.m4a')
new.update(old)
new.save()

You can open any file with mutagen.File, but that gives you raw access to the coded ID3 tags like 'TPE1', instead of human-readable tags like 'artist', so EasyID3 is used instead.


text:
Q: Does the removeAllObjects method of an NSArray or NSMutableArray release memory? I need to know if the removeAllObjects method of an NSArray or NSMutableArray releases memory.
If my array has got 10000 elements.
Can I use the
[array removeAllObjects];

to release the memory and reload it with other elements? Or it leaks memory?
Thanks
EXAMPLE
if the size of my NSMutable array is 20mb with 10.000 elements for example... if I use the removeAllObjects method...will its size  be 0mb?

A: Yes, it releases all the objects, it doesn't leak. (It doesn't, of course, explicitly deallocate them - they are only deallocated if the only reference to them was held by the array.)

A: An NS[Mutable]Array is a collection of references to object. Calling -removeAllObjects nils those references. The capacity and memory used by the array itself stay the same. In the case of NSMutableArray, those references can be reused to point to other objects. NSArray lacks the method -removeAllObjects because it's not mutable.
removeAllObjects will be marginally slower for a high number of objects than initWithCapacity. The real performance difference would be having to avoid growing the array when the number of objects reaches the limit.
As others pointed out, the objects are only released if there are no more strong references to them.

A: No it does not leak objects. It is the same as removing every object individually except it is more convenient and faster.


text:
Q: How to insert JNDI-name dynamic into Spring My problem starts here. I have a rest service and I want to lookup remote-ejbs.
I am using Jersey and Spring as frameworks for that.
My actual approache works but, it is not dynamic enough.
I defined in my context something like that:
<jee:remote-slsb id="myServiceBean"
                 jndi-name="ejb/ServiceBean"
                 business-interface="..."
                 >
      <jee:environment>
      ...
      </jee:environment>
</jee:remote-slsb>

I would like to do something like
<jee:remote-slsb id="myServiceBean"
                     jndi-name="${ejb.ServiceBean.JNDI_NAME}"
                     business-interface="..."
                     >
    <jee:environment>
    ...
    </jee:environment>
</jee:remote-slsb>

I need to do that because the JNDI_NAME can change because of the versions.
ServiceBean{
     public static String JNDI_NAME = ejb/2.1/ServiceBean
}

I was thinking to do this by writing Java-Code which replace the value when i build my Project with maven. But that feels not right.
So the generic question would be how can i get a String from a Java class into an xml when building a project with maven.

A:
Use maven-resources-plugin and Filtering :

src/main/config
    +dev
        +app.properties
    +int
        +app.properties

src/main/resources
    +context.xml

app.properties (dev)
    +ejb.ServiceBean.JNDI_NAME=XXX
app.properties (int)
    +ejb.ServiceBean.JNDI_NAME=YYY

In context.xml
<jee:remote-slsb id="myServiceBean"
                     jndi-name="${ejb.ServiceBean.JNDI_NAME}"
                     business-interface="..."
                     >
<jee:environment>

In pom.xml

<properties>
    <env_dyn>dev</env_dyn>
...
...
<build>
    <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
    </resources>
    <filters>
            <filter>src/main/config/${env_dyn}/app.properties</filter>
    </filters>
...
...

mvn clean install=> ejb.ServiceBean.JNDI_NAME=XXX in context.xml because default properties>env_dyn=dev
mvn clean install -Denv_dyn=dev => ejb.ServiceBean.JNDI_NAME=XXX in context.xml
mvn clean install -Denv_dyn=rec => ejb.ServiceBean.JNDI_NAME=YYY in context.xml


text:
Q: SOLVED - blank react page when trying to render an image I am getting a blank react page when trying to render an image. I am using the @material-ui/core package and it installed correctly.
Here is the code I am using.
Any help would be appreciated.
Thanks!
Here is the code:

import React from 'react';
import { Container, AppBar, Typography, Grow, Grid } from '@material-ui/core';
import memories from './images/memories.png';

const App = () => {
    return (
        <Container maxWidth="lg">
            <AppBar position="static" color="inherit">
                <Typography variant="h2" align="center">Memories</Typography>

            </AppBar>
        </Container>

    );
}

export default App;

Here is what I am getting in the debugging console:
SyntaxError: Cannot use import statement outside a module
at compileFunction (vm:360:18)
at wrapSafe (internal/modules/cjs/loader:1088:15)
at Module._compile (internal/modules/cjs/loader:1123:27)
at Module._extensions..js (internal/modules/cjs/loader:1213:10)
at Module.load (internal/modules/cjs/loader:1037:32)
at Module._load (internal/modules/cjs/loader:878:12)
at executeUserEntryPoint (internal/modules/run_main:81:12)
at  (internal/main/run_main_module:23:47)
I tried to uninstall and reinstall the material-ui package, checked the syntax and made sure the "memories.png" image is in the right location.

A: You are importing components incorrectly. According to the documentation of MUI you have to import a Container from @mui/material/Container for example. Probably you are seeing errors about this in the React logs as well(?) Check out the docs for each component, they all have code snippets that show how to import.

A: here is the updated code using import from '@mui/material';

import React from 'react';
import { Container } from '@mui/material';
import { AppBar } from '@mui/material';
import { Typography } from '@mui/material';

import memories from './images/memories.png';

const App = () => {
    return (
        <Container maxwidth="lg">
            <AppBar position="static" color='inherit'>
                <Typography variant="h2" align='center'>Memories</Typography>

            </AppBar>
        </Container>

    );
}

export default App;

however I am still getting a blank react page and the same logs in my console:
SyntaxError: Cannot use import statement outside a module at compileFunction (vm:360:18) at wrapSafe (internal/modules/cjs/loader:1088:15) at Module._compile (internal/modules/cjs/loader:1123:27) at Module._extensions..js (internal/modules/cjs/loader:1213:10) at Module.load (internal/modules/cjs/loader:1037:32) at Module._load (internal/modules/cjs/loader:878:12) at executeUserEntryPoint (internal/modules/run_main:81:12) at (internal/main/run_main_module:23:47)


text:
Q: Nested loop and File io I am making a simple program for fun. This should take input for X amount of files to be filled with Y amount of random 0's and 1's.
When I run this I would like to have 2 files both filled with 20 random 0's and 1's in each file. At the moment when I run this only the first file gets filled and the second one is left empty.
I think it has something to do with my second loop but I am not sure, how can I get this to work?
import random

fileamount = int(raw_input("How many files should I make? > "))
amount = int(raw_input("How many characters in the files? > "))
print "I will now make %r files with %r characters in them!\n" % (fileamount, amount)
s1 = 0
s2 = 0

while s2 < fileamount:
    s2 = s2 + 1
    textfile = file('a'+str(s2), 'wt')
    while s1 < amount:
        s1 = s1 + 1
        textfile.write(str(random.randint(0,1)))

A: In addition to reseting the value of s1, make sure you close your files. Sometimes, the output does not get written to the file if the program ends before the buffer is written to disk.
You can guarantee the file is closed by using a with statement.
The file will be closed when Python's flow of execution leaves the with suite.
import random

fileamount = int(raw_input("How many files should I make? > "))
amount = int(raw_input("How many characters in the files? > "))
print "I will now make %r files with %r characters in them!\n" % (fileamount, amount)

for s2 in range(fileamount):
    with open('a'+str(s2), 'wt') as textfile:
        for s1 in range(amount):
            textfile.write(str(random.randint(0,1)))

A: You don't reinit s1 to 0. So the second time there will be nothing written to the file.
import random

fileamount = int(raw_input("How many files should I make? > "))
amount = int(raw_input("How many characters in the files? > "))
print "I will now make %r files with %r characters in them!\n" % (fileamount, amount)

s2 = 0
while s2 < fileamount:
    s2 = s2 + 1
    textfile = open('a'+str(s2), 'wt') #use open
    s1 = 0
    while s1 < amount:
        s1 = s1 + 1
        textfile.write(str(random.randint(0,1)))
    textfile.close() #don't forget to close

A: s2 does not go back to zero after first loop. So next file does not get any character. So put s2=0 just before the inner loop.
better to use range function.
import random

fileamount = int(raw_input("How many files should I make? > "))
amount = int(raw_input("How many characters in the files? > "))
print "I will now make %r files with %r characters in them!\n" % (fileamount, amount)

for s2 in range(fileamount):
    textfile = file('a'+str(s2+1), 'wt')
    for b in range(amount):
        textfile.write(str(random.randint(0,1)))


text:
Q: Sinon stub getting "TypeError": Cannot read property 'then' of undefined I'm trying to stub 2 axios calls with different arguments inside a function where the first works while for second I get error. Can anyone help me understand where I'm going wrong?
index.js
function getInfo (endpoint, headers, id){
 return axios
.post(endpoint,id)
.then((response) => {
 const newUrl = response.data.url
return axios
.post(newUrl,id)
.then((result)=>{
if(result.data){
return result.data
}
})
})
}

index.test.js
const axios = require('axios'). default;

describe ('To test response', function () {
let response:{
data:{
url:'abc'
}
}

test('success', async function (){
let stubPost = sinon.stub(axios,'post')
stubPost.withArgs(endpoint,id).onCall(0).returns(Promise.resolve(response))
stubPost.withArgs('abc',id).onCall(1).returns(Promise.resolve(response.data))

const res = getInfo (endpoint, headers, id);
})
})


text:
Q: Passing results from expensive methods as they come for multiple layers I've got a code that looks similar to this:
List<String> ids = expensiveMethod();
List<String> filteredIds = cheapFilterMethod(ids);

if (!filteredIds.isEmpty()) {
    List<SomeEntity> fullEntities = expensiveDatabaseCall(filteredIds);
    List<SomeEntity> filteredFullEntities = anotherCheapFilterFunction(fullEntities);
    if (!filteredFullEntities.isEmpty()) {
        List<AnotherEntity> finalResults = stupidlyExpensiveDatabaseCall(filteredFullEntities);
        relativelyCheapMethod(finalResults);
    }
}

It's basically a waterfall of a couple expensive methods that, on their own, all either grab something from a database or filter previous database results. This is due to stupidlyExpensiveDatabaseCall, which needs as few leftover entities as possible, hence the exhaustive filtering.
My problem is that the other functions aren't all quite cheap either and thus they block the thread for a couple of seconds while stupidlyExpensiveDatabaseCall is waiting and doing nothing until it gets the whole batch at once.
I'd like to process the results from each method as they come in. I know I could write a thread for each individual method and have some concurrent queue working between them, but that's a load of boilerplate that I'd like to avoid. Is there a more elegant solution?

A: There's a post about different ways to parallelize, not only the parallelStream() way, but also that consecutive steps run in parallel the way you described, linked by queues. RxJava may suit your need in this respect. Its a more complete variety of the  rather fragmentary reactive streams API in java9. But I think, you're only really there if you use a reactive db api along with it.
That's the RxJava way:
public class FlowStream {

@Test
public void flowStream() {
    int items = 10;

    print("\nflow");
    Flowable.range(0, items)
            .map(this::expensiveCall)
            .map(this::expensiveCall)
            .forEach(i -> print("flowed %d", i));

    print("\nparallel flow");
    Flowable.range(0, items)
            .flatMap(v ->
                    Flowable.just(v)
                            .subscribeOn(Schedulers.computation())
                            .map(this::expensiveCall)
            )
            .flatMap(v ->
                    Flowable.just(v)
                            .subscribeOn(Schedulers.computation())
                            .map(this::expensiveCall)
            ).forEach(i -> print("flowed parallel %d", i));

    await(5000);

}

private Integer expensiveCall(Integer i) {
    print("making %d more expensive", i);
    await(Math.round(10f / (Math.abs(i) + 1)) * 50);
    return i;
}

private void await(int i) {
    try {
        Thread.sleep(i);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

private void print(String pattern, Object... values) {
    System.out.println(String.format(pattern, values));
}

}

The maven repo:
   <!-- https://mvnrepository.com/artifact/io.reactivex.rxjava2/rxjava -->
    <dependency>
        <groupId>io.reactivex.rxjava2</groupId>
        <artifactId>rxjava</artifactId>
        <version>2.2.13</version>
    </dependency>

A: You could use CompleteableFuture to divide up each non-CPU-bound step. The usage is similar to the javascript promise API.
public void loadEntities() {
    CompletableFuture.supplyAsync(this::expensiveMethod, Executors.newCachedThreadPool())
            .thenApply(this::cheapFilterMethod)
            .thenApplyAsync(this::expensiveDatabaseCall)
            .thenApply(this::anotherCheapFilterFunction)
            .thenApplyAsync(this::stupidlyExpensiveDatabaseCall)
            .thenAccept(this::relativelyCheapMethod);
}

private List<String> expensiveMethod() { ... }
private List<String> cheapFilterMethod(List<String> ids) { ... }
private List<SomeEntity> expensiveDatabaseCall(List<String> ids) { ... }
private List<SomeEntity> anotherCheapFilterFunction(List<SomeEntity> entities) { ... }
private List<AnotherEntity> stupidlyExpensiveDatabaseCall(List<SomeEntity> entities) { ... }
private void relativelyCheapMethod(List<AnotherEntity> entities) { ... }

You can also pass your own thread pool at each step if you'd like to have more control over execution.

A: You can use Java 8 Stream API. It's impossible to process a DB query "as they come in" because the result set will come in all at once. You'd have to change your method to handle single entities.
expensiveMethod().parallelStream()
  .filter(this::cheapFilterMethod)                // Returns Boolean
  .map(this::expensiveDatabaseCallSingle)         // Returns SomeEntity
  .filter(this::anotherCheapFilterFunction)       // Returns boolean for filtered entities
  .map(this::stupidlyExpensiveDatabaseCallSingle) // Returns AnotherEntity
  .forEach(this::relativelyCheapMethod);          // void method

I would also suggest using an ExecutorService to manage your threads so you don't consume all resources just creating a bunch of threads:
ExecutorService threadPool = Executors.newFixedThreadPool(8);
threadPool.submit(this::methodForParallelStream);


text:
Q: How to set span's text from text area on page load I want to set the text in a span from a text area's value when the page has loaded.
I have a span:

I have a text area which I set the value for with a rails variable:
<%= f.text_area :text_message, value: @user.text_message, id: 'text_message' %>

When the page has loaded I want the span's text to be the same as the text areas text. Something like (which doesn't work):
(document).ready(function() {
  var message_text = $("#text_message").value;
    $("#message").html(message_text);
});

A: You are trying to use DOM object property value with jQuery object. You need to use val() instead of value. The value attribute could only be assessed with javascript DOM object but not with jQuery object.
Change
var message_text = $("#text_message").value

To
var message_text =  $("#text_message").val();

OR, use indexer to convert the jQuery object to DOM object.
var message_text = $("#text_message")[0].value;

A: jquery object doesn't have the definition of value it is in javascript.
Use val() function for it.
var message_text = $("#text_message").val();

and you also forgot to use $with document object
$(document).ready(function() {
  var message_text = $("#text_message").val()
    $("#message").html(message_text);
});

Js Fiddle Demo

A: on dom ready use
$(document).ready(function() {
  var message_text = $("#text_message").val();
    $("#message").text(message_text);
});

$(document).ready(function() {
  var message_text = $("#text_message").val();
    $("#message").html(message_text);
});

A: You need to use text() or html() instead of .value to grab the content.
$(document).ready(function() {
    var message_text = $("#text_message").text();
    $("#message").html(message_text);
});

Working example

A: Use text() to set the text insted of html() DEMO
$(document).ready(function() {//$ is missing here
    var message_text = $("#text_message").value
    $("#message").text(message_text);
});

When ypu set the text the span wiil be for example0:
hi //here hi is set as text


text:
Q: How to remove duplicate row but save the latest one (VBA)? I have an excel where I have 2 sheets and I want to import selected columns to another sheet and delete possible duplicate rows. The problem is, that when I run my code, it deletes my latest duplicate row, eventhough I want to save latest row and delete the other 'older' duplicate. I really appreciate any help! Thank you :) Here is my code what I have tried so far:
Private Sub CommandButton1_Click()

Cells.RemoveDuplicates Columns:=Array(1, 2, 3)

Dim lastrow As Long, erow As Long
lastrow = Worksheets("one").Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To lastrow
Worksheets("one").Cells(i, 1).Copy
erow = Worksheets("two").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("one").Paste Destination:=Worksheets("two").Cells(erow + 1, 1)

Worksheets("one").Cells(i, 3).Copy
Worksheets("one").Paste Destination:=Worksheets("two").Cells(erow + 1, 2)

Next i

End Sub

Another question is, I have tried this code for test excel, but where I want to use this macro has a lot larger data. It takes a very long time to go through all the data.. is the problem in my code or is the actual excel just so big? I hope I explain everything crearly.
Thank you!

A:
"The problem is, that when I run my code, it deletes my latest duplicate row..."

The problem is the sort order of your data.
Remove Duplicates moves from first index to last and and keeps the first occurrence.  So you either need to sort your data such that your "oldest" duplicate is the first occurrence at top or you have to use a different method to remove duplicates.

"is the problem in my code or is the actual excel just so big?"

It could be both, but one thing is certain, your code can definitely run faster.
The low hanging fruit is to put Application.EnableScreenUpdating = False in the beginning of you sub. That stops Excel from updating the screen when your runs.  It will make a huge difference.  Just remember to set it back to True again.
You're also looping through a range one row at a time but I don't see any particular reason why you need to.  You can copy the while range in a single statement without looping.   You don't even need to copy of you don't care about ordering the format, you could transfer the values just make the ranges equal each other.
An example of how you to transfer values without cutting or looping
  Worksheets("two").Range("A2:A" & lastrow).Value = Worksheets("one").Range("E2:E" & lastrow).Value

You can use the same approach with copy and paste if you prefer.


text:
Q: Allow Numbers and Special Characters only not alphabets i have a textbox, in that i want to restrict the alphabets only, that is it will accept only numbers and special charcaters not alphabets..
i had tried the below java script ,but it will not working ....
<script type="text/javascript">
    //Function to allow only numbers to textbox
    function validate(key) {
        //getting key code of pressed key
        var keycode = (key.which) ? key.which : key.keyCode;
        //comparing pressed keycodes

        if (keyCode >= 65 && keyCode <= 90) {
            return false;
        }
    }
    </script>

and in the textbox
 <asp:TextBox ID="txt1" runat="server" OnTextChanged="txtoldpwd_TextChanged"
                            onkeypress="return validate(event)"></asp:TextBox>

A: Write script as
<script type="text/javascript">
    function Validate(event) {
        var regex = new RegExp("^[0-9-!@#$%*?]");
        var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    }
</script>

and call like
<asp:TextBox ID="txtcheck" onkeypress="return Validate(event);" runat="server" />

A:

$(function(){
$('input').keypress(function(e){
var txt = String.fromCharCode(e.which);
console.log(txt + ' : ' + e.which);
if(!txt.match(/[A-Za-z+#.]/))
{
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"  />

A: function AllowAlphabet(evt) {
 var charCode = (evt.which) ? evt.which : event.keyCode;
 if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
 return true;
 else
return false;
}

A: You can  use regular expression validator. Here is
      <asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txt1"
    ErrorMessage="Enter a valid number" ValidationExpression="^\d+$"></asp:RegularExpressionValidator>

Or if you want to use JavaScript:
Try this example:
http://www.codeproject.com/Tips/328178/Allow-only-Numeric-values-in-ASP-Text-box-control


text:
Q: how to count duplicate elements in array in java I have an array of integers like = 3,1,2,3,1 ; and I just want to count how many duplicates this array has. for example this array has 4 duplicates now. input is the array and the output will be number of duplicating elements.
is there any methods or classes for it? can you help me to implement my own?
Note : I'm not looking for number of occurrence of a specified element. I just want to know how many duplicates this array has at all. for example I said it has 4 duplicates for the mentioned array. 2 of them are "3" and 2 of them are "1"!

A: The easiest way is to use a map.  The array is converted to a stream of integers. The groupingBy collector uses the integers as keys to the map.  The counting collector counts the number or occurrences of those integers.

    int[] nums = { 1, 20, 2, 3, 1, 2, 3, 2, 221, 20 };

    Map<Integer, Long> dups = Arrays.stream(nums)
            .boxed()
            .collect(Collectors.groupingBy(a -> a, Collectors.counting()));

To print it you can do this for each key and value.
    dups.forEach((k,v)-> System.out.println(k + " -> " + v));

To count the total duplicates, take the map and sum those values > 1.
    long sum = dups.values()
                  .stream()
                  .filter(a-> a > 1)
                  .count();

    System.out.println("There are " + sum + " duplicates in all");

A: Well a map can be used to store then numbers and the amount of times they appeared:
Map<Integer,Integer> map = new HashMap<>();
for(int i: numbers) { //suppose you have the numbers in 'numbers' array
   if(map.containsKey(i) { //this number is in the map already
      map.put(i, map.get(i)+1);
   } else { //we didnt see this number before
      map.put(i, 1);
   }
}

//now we loop the map to sum the repeating numbers
int sum = 0;
for(int amount: map.values()) {
   if(amount > 1) sum += amount;
}

An advantage of this method is that you know exactly how many of each numbers the are in the array. You may need that info later.


text:
Q: How to sum running total for Quantity column per item and get only the day which the stock became Zero in the total   Posting Date  Item No_    Quantity    TOTAL   DAYS
  30/06/2016    100920        20         20
  03/07/2016    100920        -3         17
  04/07/2016    100920        -2         15
  05/07/2016    100920        -3         12
  06/07/2016    100920        -1         11
  07/07/2016    100920        -1         10
  08/07/2016    100920        -1          9
  09/07/2016    100920        -4          5
  10/07/2016    100920        -1          4
  11/07/2016    100920        -1          3
  13/07/2016    100920        -1          2
  17/07/2016    100920        -2          0     4
  21/07/2016    100920        40         40
  21/07/2016    100921        40         40
  22/07/2016    100921       -4          36
  23/07/2016    100921       -3          33
  25/07/2016    100921       -3          30
  26/07/2016    100921       -2          28
  27/07/2016    100921       -2          26
  29/07/2016    100921       -3          23
  30/07/2016    100921       -5          18
  31/07/2016    100921       -4          14
  01/08/2016    100921      -10           4
  02/08/2016    100921       -3           1
  06/08/2016    100921       -1           0     1
  07/08/2016    100921       20          20

I need to sum the running total for quantity column by item and return only the days in which the stock has become zero in the total column. I also need to get the time difference between the date that it became zero and the next day we received an order
I need the output to be:
  Posting Date  Item No_    TOTAL   DAYS
   17/07/2016   100920        0      4
   06/08/2016   100921        0      1

A: I think you want to calculate the total and days columns, although your question isn't clear on this.  If so:
select t.*, (next_posting_date - posting_date) as days
from (select t.*,
             sum(quantity) over (partition by item_no order by posting_date) as total,
             lead(posting_date) over (partition by item_no order by posting_date) as next_posting_date
      from t
     ) t
where total = 0;

Date functions are notoriously database-dependent, so the exact syntax for days may depend on your database.


text:
Q: Android Annotations Custom View I am trying to implement Android Annotations to my View. But I cant figure out how to do it correctly. My Problem at the moment is that the fields in the View are always NULL.
I think I have a bit of an understanding problem how to use Android Annotations with Views and Adapters. Can someone give me a hint how I would do this correctly?
In my fragment I use the following adapter:
ItemAdapter
@EBean
public class ItemAdapter extends BaseAdapter {

public ItemAdapter(Context context) {
    this.context = context;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    GalleryListView view;
    if (convertView == null) {
        view = GalleryListView_.build(context);
    } else {
        view = (GalleryListView) convertView;
    }

    imageUrls = getDocumentListAll();
    DDocuments doc = documentProxy.getElementByDocument(imageUrls.get(position));
    view.init(imageUrls.get(position), Uri.fromFile(new File(doc.getPath())));

    // before I used annotations I did set my Image using this. But now I dont really know how to use this line
    // ImageLoader.getInstance().displayImage(Uri.fromFile(new File(doc.getPath())).toString(), holder.image, options, animateFirstListener);
}
}

GalleryListView
@EViewGroup(R.layout.gallery_list)
public class GalleryListView extends LinearLayout {
    @ViewById
    ImageView   image;

    @ViewById
    TextView    text;

    public void init(String imageText, Uri imageUri) {
        text.setText(imageText);
        image.setImageURI(imageUri);
    }
}

A: The problem is that the Views have not been injected when you're making your call to init.  So, a solution should be to not set the view's text directly; rather, you want to set a variable that you know will be read into the Views after they have been injected.
One way to do this is to make use of @AfterViews. A method with the @AfterViews annotation will be called after View injection has taken place.
Off the top of my head it would look like this:
@EViewGroup(R.layout.gallery_list)
public class GalleryListView extends LinearLayout {
    String mText;
    Uri mUri;

    @ViewById
    ImageView   image;

    @ViewById
    TextView    text;

    public void init(String imageText, Uri imageUri) {
        mText = imageText;
        mUri = imageUri;
    }

    @AfterViews
    void afterViews() {
        text.setText(mText);
        image.setImageURI(mUri);
    }
}

This might not be the best solution, but it should get the job done.  I suggest keeping the Android Annotation Cookbook handy; there are other similar annotations that will come in handy.

A: Where are you getting context from?
Try replacing
    view = GalleryListView_.build(context);

with
    view = new GalleryListView_(context);

In any case, for such a small view I don't see the profit of using Android Annotations, maybe if you had multiple resources I would understand, but for such little code, I recommend you to implement te constructor and inflate the resources yourself there.


text:
Q: Aggregating Nested Fields in Kibana /Elastic Search I have defined an Index in elastic cache 6
PUT my_index
{
 "mappings": {
  "_doc": {
  "properties": {
    "user": {
      "type": "nested"
       }
      }
     }
  }
 }

and loaded some same data as follows
 PUT my_index/_doc/1
{
 "group" : "coach",
"user" : [
    {
    "first" : "John",
    "last" :  "Frank"
   },
   {
    "first" : "Hero",
    "last" :  "tim"
   }
  ]
}

PUT my_index/_doc/2
{
 "group" : "team",
"user" : [
    {
    "first" : "John",
    "last" :  "term"
   },
   {
    "first" : "david",
    "last" :  "gayle"
   }
  ]
}

Now I am trying to search in the discover page or the visualization page, but I receive a blank

A: after a bit of trial and error and googling around i found that does not support nested type for aggregation and search out of the box. To enable this you must install a plugin and the best plugin i found is listed below.
https://ppadovani.github.io/knql_plugin/overview/
The plugin provides all the features from the discover tab to the visualization tab.


text:
Q: Import Variables from Text File in Powershell I've got a couple of Powershell scripts that automate DLL transferal and I'd like to import the variables from one text file into the various scripts. My example:
Variables.txt
$foo = "blarg"
$bar = "other blarg"

And then I'd like to do something like this:
Script.ps1
Imports Variables.txt
echo "$foo $bar"

A: This can be accomplished by Dot Sourcing.
Create a .ps1 file, declare your variables in it, then dot source the file. This will bring any variables declared in the file into the global scope.
Example:
Contents of Variables.ps1:
$foo = "blarg"
$bar = "other blarg"

Dot source it:
. ./Variables.ps1
Write-Host "$foo $bar"


text:
Q: google sheets if and statements not workings =IF(and('Form Responses 5'!BA:BA="Service/install",if('Form Responses 5'!Y:Y="V723")),sum('Form Responses 5'!Z:Z),"")
I want it so
if ba:ba="service.install" then add z:z
if ba:ba="sending" then add z:z
bonus if I could get it to be also included
if ba:ba="receive" then subtract z:z
if none of the above, do nothing
I keep getting 'wrong number of arguments'
I've been trying for about 3 hours. I can't get it do do much. Sometimes it'll say false in the cell.
edit:
I just noticed I missed putting in half of what I wanted. I want it so if ba:ba="service.install" and y:y="V723" then add z:z
if ba:ba="sending" and Y:Y="V723" then add z:z
bonus if I could get it to be also included if ba:ba="receive" then subtract z:z
if none of the above, do nothing
https://docs.google.com/spreadsheets/d/1aeckdhKBFTlaRS42wzDM1lG0CTx_ultMqjjHkRkdzYk/edit?usp=sharing

A: try:
=IFERROR(SUM(FILTER('Form Responses 5'!Z:Z; REGEXMATCH(
                    'Form Responses 5'!BA:BA; "(?i)Service/install|sending");
                    'Form Responses 5'!Y:Y="V723")))


text:
Q: hammer-time.min.js contains undefined function hasTouchNone I downloaded hammer-time.min.js and when I run, I am getting an exception on my browser.

TypeError: this.hasTouchNone is not a function. (In 'this.hasTouchNone(a.target)', 'this.hasTouchNone' is undefined)

Am I missing a library?
Update:
I have tried downloading the full Javascript (non-minified version). And it is working fine. When I checked the code, the hasTouchNone function is not in the code.

A: Looks like you answered it yourself with:

Update: I have tried downloading the full Javascript (non-minified version). And >it is working fine. When I checked the code, the hasTouchNone function is not in >the code.


text:
Q: OS X Kindle App: Where are the books located? I was expecting to find .epub or .prc files on my hard-disk, but didn't. Does anyone know: Where are the ebooks that the official Kindle App downloads located?

A: The Kindle app stores AZW files, but only downloads them for Amazon-purchased content that you have opened in the Kindle app on that computer.
The AZW files are saved in ~/Documents/My Kindle Content.
Their names are random-looking (like B0043M4ZH0_EBOK), so it takes a little work to figure out which file corresponds to which book. Here's how you do that:
Open the book of interest on Amazon.com (make sure you're looking at the Kindle edition). It's URL will be something like this:
http://www.amazon.com/Ultimate-Hitchhikers-Guide-Galaxy-ebook/dp/B0043M4ZH0/ref=tmm_kin_title_0?ie=UTF8&m=AG56TWVU5XWC2&qid=1309013055&sr=8-2, but all you're interested in is the code after /dp/. In this case, it's B0043M4ZH0.
So, you know that the AZW file with the name B0043M4ZH0_EBOK is The Ultimate Hitchhiker's Guide to the Galaxy.

A: Well, by going to the "Content Folder" in Kindle "Preferences," and clicking on same, I found the .azw files, but greyed out. They are in ~/Library/Application Support/Kindle/My Kindle Content/.
You can also use the "find" command in Terminal: find  ~ -name '*.azw' to locate them.

A: These files are now (October 2012) stored in:
~/Library/Containers/com.amazon.Kindle/Data/Library/Application Support/Kindle/My Kindle Content/

If they move again you can find them by running the command:
find  . -name *.azw

A: You can find (and change) the location of your books in the general preferences. Simply choose Preferences from the Kindle menu. In the General tab, you can find an entry Content Folder and a button to change it.
This works at least on a fresh installation of Kindle from the App Store, running Mountain Lion.
Addition: Worth saying that if you change it that it will automatically move everything from the existing location to the new location so you don't have to worry about it losing track of your books.

A: After reading the above, I created a new folder under /Documents and then changed the target file location in Kindle/Preferences. Kindle app then copied the files to their. Then they became visible. Before that I also couldn't find them.

A: You can define the location of the files (and see where they are) in you application.
Under Kindle -> Preferences you will find the content folder. if you hover the mouse over you can see all of them one at a time.


text:
Q: Excel-like filtering in kendo grid is not working I am looking for excel like filtering in kendo grid. From Telerik demos I could find a demo with this feature like below:
 .Columns(columns =>
 {
     columns.Bound(p => p.ProductName).Filterable(ftb => ftb.Multi(true));
 });

Where as if I implement ".Filterable(ftb=>ftb.Multi(true))" in my code, I am getting an error like "error CS1660: Cannot convert lambda expression to type 'bool' because it is not a delegate type". Can someone please guide me how to implement this feature.

A: Filterable(ftb => ftb.Multi(true) should just work.
Note that Excel-like filtering was only released two weeks ago. Did you update Kendo UI to version 2015 Q1?
What's new:

Grid
The Grid adds highly requested functionality, such as:

*

*Excel-like filtering, i.e. a multi-select checkboxes option as part of the filtering menu


text:
Q: How does defense stacking work? How does defense stacking work?
Suppose that I have 45% "Protego Power" and 44% "Defense" and I also have "Defense +30%" from the Protection Charm. (This seems to be the max possible for a Professor.)
Suppose I get attacked by a monster that deals 100 damage base. How much damage do I actually take?
What if the monster is a Dark Wizard (which is my deficiency) and my Deficiency Defense is 50%? Do I take more damage or less?

A: I found an answer at this reddit link:
https://www.reddit.com/r/harrypotterwu/comments/csgsdd/all_about_combat_damage_what_i_know_or_i_think_i/
Here's the relevant part:

Damage = Power * Proficiency * Defence * Protego
Power = BasicEnemyPower * (1 + 0.0816 * Level) * (1 - WeakeningHex)
Proficiency = 1 + (BasicEnemyProficiencyPower * (1 + 0.01 * Level) - DeficiencyDefence)

ProficiencyPower is also scaled with level. That's why DeficiencyDefence > 0.5 is still useful.

Defence = 1 - (Defence + ProfessorShield - (EnemyDefenceBreach - ConfusionHex))
Protego = 1 - ProtegoPower

No comment in the article about how much EnemyDefenseBreach might be, but assuming that number is zero, a character with 44% defense and 45% protego power would take 100*(1-.44)*(1-.45)=30.8 damage from a 100-damage monster.
With a 30-point professor shield, that goes to 100*(1-.74)*(1-.45)=14.3 damage from a 100-damage monster.
The reddit link seems to imply that monsters start at 0.5 proficiency power at level 0, and they scale to 1.5 proficiency power at level 100.  So with 50% deficiency defense, damage would be unchanged for a level-0 monster and would be doubled for a level-100 monster.

Although taking less damage is nice, it won't actually get you much farther in the tower.  The tower is a race to kill all the monsters before the time runs out.  In a large group, if you go down a magizoologist will just bring you back.  To make progress in the tower, focus on damage output.


text:
Q: Submitting a JCL via FTP I need to submit a JCL via FTP.
Wrote below code for it:
open server.com
uname
password
quote site LRECL=80 BLKSIZE=27920 RECFM=FB
literal SITE FILETYPE=JES
GET 'PDS.NAME(JCLNAME)' 'LOCAL\PATH\file.txt'
disconnect
bye

The problem is that even after the job gets completed in spool, it takes around 10 minutes before this script gets completed.
It seems to get stuck at 125 When Job is done, Will retrieve its output.
Maybe i am missing some pre initialization. Please advise.

A: It looks like the JES system doesn't really know how to process the request. If you take a read of the Steps for submitting a job and automatically receiving output article it explains that in order to get the output of the job automatically, the JCL JOBNAME must be USERIDx. So if my userid is ABC123, then my JOBNAME should be ABC123A. They also recommend a slightly different set up than you. Try this:
open server.com
USERID
password
SITE FILEtype=JES NOJESGETBYDSN
GET 'PDS.NAME(USERIDx)' 'LOCAL\PATH\file.txt'
disconnect
bye

When I tried your FTP commands, I got the same results (waiting for 10 minutes). I think it has to do with the JES interface level and how long the different files are held for. Using the commands above (and using the proper naming), the SYSOUTS will comeback when the job has completed as long as they are in HELD status. If there are some outputs that are not in HELD status, it will skip them.

A: Confused why you're using 'GET'.
I have always used 'PUT' to submit a JCL via FTP.
Here's a snippet of a batch job I'd use to submit JCL via FTP:
::: -- FTP Compress DOC --
:ftp_COMPRESS
echo.
echo  " ----------------------------------- "
echo  " COMPRESSING dataset                 "
echo  " --------------------------------------- "
IF EXIST ftptemp.txt del ftptemp.txt
echo user %FTPUserID%>> ftptemp.txt
echo %FTPPwd%>> ftptemp.txt
echo cd ..>> ftptemp.txt
echo cd DATASET>> ftptemp.txt
echo del %filename%>> ftptemp.txt
echo quote site file=jes>> ftptemp.txt
echo put compit.jcl>> ftptemp.txt
echo quote site file=seq
echo quit>> ftptemp.txt
ftp -n -s:ftptemp.txt %host%

pause

Here's the JCL job on my local machine saved as compit.jcl, same directory as .bat:
 //COMPIT    JOB CARD
 //*-------------------------------------------------------------
 //COMPRESS EXEC PGM=IEBCOPY
 //SYSPRINT DD SYSOUT=*
 //LIB DD DSN=DATASET,DISP=OLD
 //SYSIN DD *
  COPY INDD=LIB,OUTDD=LIB
 /*

The job itself was a quick way I'd compress a dataset before uploading more members to it.


text:
Q: How to check isEmpty on Column Data Spark scala My data looks like :
[null,223433,WrappedArray(),null,460036382,0,home,home,home]

How do I check if the col3 is empty on query in spark sql ? I tried to explode but when I do that the empty array rows are disappearing. Can some suggest me a way to do this.
I tried :
val homeSet = result.withColumn("subscriptionProvider", explode($"subscriptionProvider"))

where subscriptionProvider(WrappedArray()) is the column having array of values but some arrays can be empty. I need to get the subscriptionProvider with null values and subscriptionProvider array has "Comcast"

A: Try:
import org.apache.spark.sql.functions._

val tmp = df.withColumn("subscriptionProvider",
  when(size($"subscriptionProvider") !== 0, $"subscriptionProvider").otherwise(array(lit(null).cast("string"))))

tmp.withColumn("subscriptionProvider", explode($"subscriptionProvider"))

A: LostInOverflow's answer is good for keeping in the dataframe mindset. However it depends on the size of your lists as to whether size is efficient. If you are going to have large lists, then dropping out and back into the dataframe might be best:
val dfSchema = df.schema
val filtered = df.rdd.filter(!_.getList[String](2).isEmpty)
sqlContext.createDataFrame(filtered, dfSchema)


text:
Q: Salesforce Controller Extension Testing: System.QueryException: List has no rows for assignment to SObject I'm looking for some help testing a controller extension. I keep receiving the error: "System.QueryException: List has no rows for assignment to SObject" which is referring to the SOQL statement in my class.
Class
public class productdata {

public productdata(ApexPages.StandardController controller) {
}

public String getTag(){
    Product2 prod;
    prod = [SELECT Name FROM Product2 WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    return Prod.Name;
}

Test Class
@isTest

private class TestProductData {
    static testMethod void TestProductDataMethod(){
    Product2 TP = new Product2(Name='TestRecord');
    insert TP;
    System.assertEquals('TestRecord', TP.name);

    PageReference pageRef = page.productpage;
    Test.setCurrentPage(pageRef);

    ApexPages.StandardController sc = new ApexPages.standardController(TP);
    productdata controller = new productdata(new ApexPages.StandardController(TP));
    ApexPages.currentPage().getParameters().put('id', '01t300000007hKrAAI');

    controller.getTag();
    }

Thanks!

A: You shouldn't manually assign your record ids (as they will change with each run of the test).
ApexPages.currentPage().getParameters().put('id', '01t300000007hKrAAI');

Instead do:
ApexPages.currentPage().getParameters().put('id', TP.id);


text:
Q: JavaScript scrollTop function I have been using JavaScript scrollTop function to scroll the div to top by 5 px. but its not working.
I am using:
scdiv.scrollTop = "5px";

The problem is it scrolls the div to top instead of moving to 5 px. Any suggestions?

A: scrollTop is a property, its value is an int.
div.scrollTop += 5;

https://developer.mozilla.org/en/DOM/element.scrollTop

A: $("#yourButtonId").on('click',function(){

var scDiv = $("#scdiv");

var top = scDiv.css('top');

top = parseInt(top);

scDiv.css('top',(top-5)+"px");

//To make it visually scrollable

  scDiv.animate({
    top: top
  },500);

});

A: scrollTop accepts integer numbers, it doesn't understand CSS values like px, so you would use something like this: element.scrollTop += 5;
See an example here: http://jsfiddle.net/pMafC/.
You can click a button to make the div scroll.
See scrollTop - MDN.


text:
Q: Update docx metadata for a large number of files using python-docx I have about 300 docx files in folders and subfolders that I need to update metadata for. I have a separate 300+ line csv file containing the metadata: each row containing filename, keywords, title in rows.
I want to loop through the docx files pulling content from the csv and inserting the metadata into the docx files. Docx files are stored 2 sub folders down from the root folder.
So far, I have the following sketched out. What I am struggling with is figuring out how to loop through the csv file and apply the metadata to each file in sequence. I'm sure there is a relatively easy way to approach this, Setting up the loop and getting the csv content in is where I'm lost. I'm a noob, so kind of feeling my way as I go.
Any tips appreciated.
#running in python 3.5.2 32bit
import csv
from docx import Document
import os
import sys

csv_path = ("datasheet_metadata_uplift.csv")

def update_docx_metadata(document, keywords, title):
    """
    Update the *keywords*, and *title* metadata
    properties in *document*.
    """
    core_properties = document.core_properties
    core_properties.keywords = keywords
    core_properties.title = title

def read_csv_lines(filename, keywords, title):
    """
    Reads the csv lines, returns *filename*, *keywords*, *title*
    """
    with open(csv_path, 'r') as f:
        csv_file = csv.reader(f)
        for row in csv_file:
            filename = row[0]
            keywords = row[1]
            title = row[2]

def open_docx(filename):
     """
     Search for docx file and open it
     """
     for root, dirs, files in os.walk("."):
         if filename in files:
            doc_path = os.path.join(path, filename)

csv_lines = read_csv_lines(filename, keywords, title)
for filename, keywords, title in csv_lines:
    document = Document(doc_path)
    update_doc_metadata(filename, keywords, title)
    document.save(doc_path)

A: The next step I would recommend Aidan is to refactor your code into coherent functions. This will allow you to execute the required actions where needed, each with a single function call, such that intent and flow is not obscured.
You might start with something like this:
def update_doc_metadata(document, author, keywords, title, subject):
    """
    Update the *author*, *keywords*, *title*, and *subject* metadata
    properties in *document*.
    """
    core_properties = document.core_properties
    core_properties.author = author
    core_properties.keywords = keywords
    core_properties.title = title
    core_properties.subject = subject

Notice a few things:

*

*It's coherent, meaning it does all of only one thing. This makes is more reusable.

*It doesn't depend on anything that doesn't come in as a parameter. This makes it easy to test (if you did that) and generally easy to understand because all the context you need is in those ten lines.

*It has a docstring that states plainly what it does. This is a useful discipline not only because it helps a reader (most likely you, weeks or months later) understand the intent, but because it forces you to explain what you're doing. A lot of times you can detect a mis-factored function because it's hard or long to explain. (The asterisks around the parameters make them show up in italics in certain documentation packages.)

If you proceed like this, locating and "extracting" coherent bits into functions, the core logic of the main code will become much clearer.
I think the overall structure is something like this:
csv_lines = read_csv_lines(csv_path)
for filename, keywords, title in csv_lines:
    doc_path, document = open_docx(filename)
    update_doc_metadata(document, author, keywords, title, subject)
    document.save(doc_path)

A: So i figured this out, it ended up being quite simple. I also made it easier for myself by putting the full filepaths in the csv. thanks to scanny for the encouragement. next stop, the docs and tutorial pages :)
#runs in python 3.5.2 32-bit
#docx requires 32 bit operation
import csv
from docx import Document
import os
import sys

#path to the csv file - csv file must contain rows as follows:
#full filepath, title, subject
#ensure there are no commas, other than the csv delimiters

csv_path = "datasheet_metadata_uplift.csv"

#set up the lists that will be used to hold csv values
filename = []
title = []
keywords = []

#sets up the csv file, and parses the "columns" to one of three lists: filename, title, keywords
f = open(csv_path)
csv_file = csv.reader(f)

#chops up csv into [] lists
for row in csv_file:
    filename.append(row[0])
    title.append(row[1])
    keywords.append(row[2])

#get the number of lines in the csv, and thus the number of files that need updating
file = open(csv_path)
num_lines = len(file.readlines())

#do the updates on every filename in the list
i = 0
while i < num_lines:
    if i < num_lines:
        #update the docx files, one for each csv file entry
        document = Document(filename[i])
        core_properties = document.core_properties
        core_properties.keywords = (keywords[i])
        core_properties.title = (title[i])
        core_properties.subject = ("YOUR_SUBJECT_HERE")
        core_properties.comments = (" ")
        core_properties.company = ("YOUR_COMPANY_HERE")
        document.save(filename[i])
        i+=1

print ("finished!")


text:
Q: How to completely disable black screen and clock-page on CentOS 8 console (before login)? I want my screen to stay EXACTLY the same after it's finished booting, forever, which means I NEVER want it to go black, and I NEVER want to see that clock overlay appearing over the top of my username selection login dialog (it's a VM - has no real monitor, so all this blanking and screen saving garbage makes no sense).  Basically - when something goes wrong, like a kernel problem, I can't see on the console what that was, since it's gone black and only shows up if a key is pressed, which (in the case of kernel issues) doesn't always still work.
I've already included this on my boot line:
consoleblank=0
I've tried this:-
gsettings set org.gnome.desktop.session idle-delay 0
I've even tried this:-
rm -rf  /usr/bin/xdg-screensaver /usr/lib/python3.6/site-packages/orca/scripts/apps/gnome-screensaver-dialog /usr/lib64/libxcb-screensaver* /usr/lib64/pkgconfig/xcb-screensaver* /usr/lib64/totem/plugins/screensaver /usr/libexec/gsd-screensaver-proxy
I'm in runlevel 5 - I'd prefer not to go back to 3 ( which consoleblank=0 works for ).
Anyone got any clues?  Basically - I never want to see this timewasting dumb idea again

(or it's evil cousin - the near-totally black version [go mousey, you at least escaped the blackout!!]):-

A: Update: I rebooted and it appears that the "delete all possible culprits" trick stuck and worked:
rm -rf  /usr/bin/xdg-screensaver /usr/lib/python3.6/site-packages/orca/scripts/apps/gnome-screensaver-dialog /usr/lib64/libxcb-screensaver* /usr/lib64/pkgconfig/xcb-screensaver* /usr/lib64/totem/plugins/screensaver /usr/libexec/gsd-screensaver-proxy

Not elegant, but, problem solved...
I also posted a bug report in gdm settings, because it supports this setting:-

but gdm itself does not honor it, and there's no way to change the settings for gdm itself (it's a user which you can't log in as), so gdm should respect the settings of the user that spawned it (root).

A: I will suggest to set it directly under dconf db,  :
Create the following conf file : /etc/dconf/db/local.d/01-centos-event-settings
[org/gnome/desktop/session]
idle-delay=uint32 0

Update db :
dconf update
Check if the new value has been set :
gsettings get org.gnome.desktop.session idle-delay

And also be sure that selinux is in permissive mode.


text:
Q: values at coordinates to image I have a text file with measurement data which looks like this.
x   y   z
1   3   -2
2   1   -3
3   1   1
2   2   3
1   2   2
2   3   0

This would imply the following measurement (on an x,y grid)
-2   0
 2   3
    -3   1

I want to create an image from these values where no measurement would mean that the image is transparent. If possible I would like to map the z values (from for example -9.4 to +3.2) to a colormap such as colormap.jet
I've tried to do this using the Python Image Library and putpixel but this is very slow and I'm sure there must be a better way of doing this.
My current code:
    basePath = os.path.dirname(os.path.realpath(file)) # defines the directory where the current file resides
srcFiles = glob.glob('*.pts')
for fileName in srcFiles:
data = pd.read_csv(os.path.join(basePath, fileName), names=['x', 'y', 'z'], delim_whitespace=True)

print fileName
maxX = data.x.max()
minX = data.x.min()
maxY = data.y.max()
minY = data.y.min()
minZ = data.z.min()
maxZ = data.z.max()

width = maxX-minX
height = maxY-minY

img = Image.new('L', (int(width), int(height)))

for x in range(int(width)):
    for y in range(int(height)):
        value = data[(data['x'] == (minX+x)) & (data['y'] == (minY+y))]['z']
        if len(value) == 0:
            value = 99.;

        img.putpixel((x,y),int(value))

img.save('test.png')

A: Maybe you should just use a numpy matrix to manipulate the image. I didn't do the csv read part as you already have it. The masked array let you have transparent pixels.
import numpy as np
import matplotlib.pyplot as plt

INPUT = np.array(
[[1,   3,   -2]
,[2,   1,   -3]
,[3,   1,   1]
,[2,   2,   3]
,[1,   2,   2]
,[2,   3,   0]])

# get ranges
xmin = INPUT[:,0].min()
xmax = INPUT[:,0].max()
ymin = INPUT[:,1].min()
ymax = INPUT[:,1].max()
zmin = INPUT[:,2].min()
zmax = INPUT[:,2].max()

# create array for image : zmax+1 is the default value
shape = (xmax-xmin+1,ymax-ymin+1)
img = np.ma.array(np.ones(shape)*(zmax+1))

for inp in INPUT:
    img[inp[0]-xmin,inp[1]-ymin]=inp[2]

# set mask on default value
img.mask = (img==zmax+1)

# set a gray background for test
img_bg_test =  np.zeros(shape)
cmap_bg_test = plt.get_cmap('gray')
plt.imshow(img_bg_test,cmap=cmap_bg_test,interpolation='none')

# plot
cmap = plt.get_cmap('jet')
plt.imshow(img,cmap=cmap,interpolation='none',vmin=zmin,vmax=zmax)
plt.colorbar()

plt.imsave("test.png",img)
plt.show()
plt.close()

note that the imsave does not save the figure I show here but the image as you want which wouldn t be interesting with 3x3 pixels.


text:
Q: Python code doesn't work after imported from PyCharm to Repl.it (ParseError: bad input) I was working on a simple one-point perspective 3D-Engine in PyCharm which uses Turtle to render images. The code simply just renders three (badly-made) stars floating around and changing colours. I've also worked on the site repl.it tons of hours before, and thought that I would "upload" my code there so that I could continue working on it online from other places when I got time. But it seems as if there were a difference between the two compilers in PyCharm and Repl.it: The exact same code that works fine in PyCharm just spits out a Compiler Error in Repl.it. The exact error is ParseError: bad input on line 59 which is really annoying. Here below is the code. I don't expect anyone to read all the code, but rather just take a quick look at that specific line to see if it's just me being a moron. Just a heads up, it's very long!
    import turtle
    import time
    import math

    turtle.getscreen()
    turtle.colormode(255)
    turtle.bgcolor(0, 0, 0)
    turtle.pensize(7)
    turtle.speed(99)

    def draw_line(start_x, start_y, start_z, end_x, end_y, end_z, shift_x, shift_y, shift_z):
        fov = 10
        turtle.penup()
        print("Drawing Line -- First pos: " + str(fov*((start_x+shift_x)/(start_z+shift_z))) + ", Second pos: " + str(fov*((start_y+shift_y)/(start_z+shift_z))))
        turtle.goto(fov*((start_x+shift_x)/(start_z+shift_z)), fov*((start_y+shift_y)/(start_z+shift_z)))
        turtle.pendown()
        turtle.goto(fov*((end_x+shift_x)/(end_z+shift_z)), fov*((end_y+shift_y)/(end_z+shift_z)))
        turtle.penup()

    def draw_star(pos_x, pos_y, pos_z):
        turtle.tracer(0, 0)

        draw_line(-10, -10, 1,  0, 10, 1,  pos_x, pos_y, pos_z)
        draw_line(0, 10, 1,  10, -10, 1, pos_x, pos_y, pos_z)
        draw_line(10, -10, 1,  -10, 3, 1, pos_x, pos_y, pos_z)
        draw_line(-10, 3, 1,  10, 3, 1, pos_x, pos_y, pos_z)
        draw_line(10, 3, 1, -10, -10, 1, pos_x, pos_y, pos_z)

        draw_line(-10, -10, 1.1,  0, 10, 1.1,  pos_x, pos_y, pos_z)
        draw_line(0, 10, 1.1,  10, -10, 1.1, pos_x, pos_y, pos_z)
        draw_line(10, -10, 1.1,  -10, 3, 1.1, pos_x, pos_y, pos_z)
        draw_line(-10, 3, 1.1,  10, 3, 1.1, pos_x, pos_y, pos_z)
        draw_line(10, 3, 1.1, -10, -10, 1.1, pos_x, pos_y, pos_z)

        draw_line(-10, -10, 1, -10, -10, 1.1, pos_x, pos_y, pos_z)
        draw_line(0, 10, 1,  0, 10, 1.1, pos_x, pos_y, pos_z)
        draw_line(10, -10, 1,  10, -10, 1.1,  pos_x, pos_y, pos_z)
        draw_line(-10, 3, 1, -10, 3, 1.1, pos_x, pos_y, pos_z)
        draw_line(10, 3, 1,  10, 3, 1.1, pos_x, pos_y, pos_z)
        print("Finished drawing star at " + str(pos_x) + " " + str(pos_y) + " " + str(pos_z))

        turtle.update()

    i = 0
    i2 = 0
    i3 = 0
    clr = 0
    back = False

    while True:
        turtle.clear()

        valuelist = [math.cos(i/1.2), math.cos(i2/1.2), math.cos(i3/1.2)]
        sortedlist = sorted(valuelist)

        match (sortedlist.index(valuelist[len(valuelist) - 3])):
            case 0:
                turtle.pencolor(clr, 255-clr, clr)
                turtle.pensize(5-(math.cos(i/1.2)*3))
                draw_star(math.cos(i)*10-30, math.sin(i)*10, math.cos(i/1.2)/3)
            case 1:
                turtle.pencolor(255-clr, clr, clr)
                turtle.pensize(5 - (math.cos(i2 / 1.2) * 3))
                draw_star(math.cos(i2)*10, math.sin(i2)*10, math.cos(i2/1.2)/3)
            case 2:
                turtle.pencolor(clr, 255-clr, clr)
                turtle.pensize(5 - (math.cos(i3 / 1.2) * 3))
                draw_star(math.cos(i3)*10+30, math.sin(i3)*10, math.cos(i3/1.2)/3)

        match (sortedlist.index(valuelist[len(valuelist) - 2])):
            case 0:
                turtle.pencolor(clr, 255 - clr, clr)
                turtle.pensize(5 - (math.cos(i / 1.2) * 3))
                draw_star(math.cos(i) * 10 - 30, math.sin(i) * 10, math.cos(i / 1.2) / 3)
            case 1:
                turtle.pencolor(255 - clr, clr, clr)
                turtle.pensize(5 - (math.cos(i2 / 1.2) * 3))
                draw_star(math.cos(i2) * 10, math.sin(i2) * 10, math.cos(i2 / 1.2) / 3)
            case 2:
                turtle.pencolor(clr, 255 - clr, clr)
                turtle.pensize(5 - (math.cos(i3 / 1.2) * 3))
                draw_star(math.cos(i3) * 10 + 30, math.sin(i3) * 10, math.cos(i3 / 1.2) / 3)

        match (sortedlist.index(valuelist[len(valuelist) - 1])):
            case 0:
                turtle.pencolor(clr, 255 - clr, clr)
                turtle.pensize(5 - (math.cos(i / 1.2) * 3))
                draw_star(math.cos(i) * 10 - 30, math.sin(i) * 10, math.cos(i / 1.2) / 3)
            case 1:
                turtle.pencolor(255 - clr, clr, clr)
                turtle.pensize(5 - (math.cos(i2 / 1.2) * 3))
                draw_star(math.cos(i2) * 10, math.sin(i2) * 10, math.cos(i2 / 1.2) / 3)
            case 2:
                turtle.pencolor(clr, 255 - clr, clr)
                turtle.pensize(5 - (math.cos(i3 / 1.2) * 3))
                draw_star(math.cos(i3) * 10 + 30, math.sin(i3) * 10, math.cos(i3 / 1.2) / 3)

        i = i + 0.2
        i2 = i2 - 0.25
        i3 = i3 + 0.3

        if clr > 245:
            back = True

        if clr < 15:
            back = False

        if back:
            clr = clr - 15
        else:
            clr = clr + 15

        time.sleep(0.1)

A: Python's match syntax is new with python version 3.10.  If the interpreter you're submitting this to is an earlier version you'll get a SyntaxError on line 59.
Note that version 3.10 just came out 2 months ago.  This is still bleeding-edge syntax.


text:
Q: How do I say "/" in a presentation? Do I say "Slash" or do I just ignore the / all together? I have a powerpoint presentation coming up and I can't figure out how to say / for my presentation.

A: In contexts where the virgule or "oblique stroke" mark is used to express a choice between two alternatives, it's standard in AmE to just say "slash":

slash ( / ) — technically known as a virgule but also called a slant, solidus, or stroke (the common name in British English)—serves a number of purposes in writing, essentially standing in for other words as a quick and clear way of showing the connection between two things. A slash is conventionally used without spaces between it and the words it connects (although it is also common to see spaces used, especially if one or both of the things being joined contain multiple words).

This kind of language is commonly employed in AmE business jargon. Consider "buyers/sellers" in written form:

The targets for buyers/sellers of the product will increase by 10% in 2020.

which is expressed orally as

The targets for buyers slash sellers of the product will increase by 10 percent in 2020.

A: I'd say "slash," but I've been known to say "or" or "and" when I deem either appropriate. (Articulating "or" and/or "and" is easier than "slash.") The irony that I'm using "and/or" in my answer is not lost on me.


text:
Q: Angular *ngFor over FormGroup in Template - Cannot find a differ supporting object error I'm trying to loop over a FormGroup of FormControls in the template. I want to display a checkbox for each.
This is how my component.ts looks like
tags = ["vegan","vegetarian","meat","fruit","vegetable","seafood","fish","nut"];

get tagsForForm() {
    return this.foodForm.get('tags') as FormGroup;
}

createTagsForForm(): {[key: string]: any} {
    let tagsForForm = {};
    for (let i = 0; i < this.tags.length; i++){
        tagsForForm[this.tags[i]]=false;
    }
    return tagsForForm;
}

ngOnInit(){
    this.foodForm = this.fb.group({
        foodName: [''],
        tags: this.fb.group(this.createTagsForForm())
    });
}

My template.html looks like this:

Tags

    <input *ngFor="let tag of tagsForForm" [formControlName]="tag" type="checkbox">

In the console I'm getting this error:
"Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

Is it not possible to loop over a FormGroup in the template or is only something missing?

A: You need to use keyvalue pipe to loop over objects. Try the following
<input *ngFor="let tag of tagsForForm | keyvalue" [formControlName]="tag.value" type="checkbox">

The value of the property is available in tag.value and the key of the property is available in tag.key.
Update
It appears this.foodForm.get('tags') as FormGroup doesn't return the correct object to loop over. You could try to replace it with this.foodForm.controls['tags']['controls'];. Try the following
Controller
export class AppComponent  {
  foodForm: FormGroup;
  tags = ["vegan", "vegetarian", "meat", "fruit", "vegetable", "seafood", "fish","nut"];

  get tagsForForm() {
    return this.foodForm.controls['tags']['controls'];
  }

  constructor(private fb: FormBuilder) {}

  createTagsForForm(): {[key: string]: any} {
    let tagsForForm = {};
    for (let i = 0; i < this.tags.length; i++){
      tagsForForm[this.tags[i]] = false;
    }
    return tagsForForm;
  }

  ngOnInit() {
    this.foodForm = this.fb.group({
      foodName: [''],
      tags: this.fb.group(this.createTagsForForm())
    });
  }
}

Template
<form [formGroup]="foodForm">
    Name:
    <input formControlName="foodName" />

    <ng-container *ngFor="let tag of tagsForForm | keyvalue">
      {{ tag.key | titlecase }}
      <input [formControlName]="tag.key" type="checkbox">

    </ng-container>

</form>

Alternatively if you're generating the nested form group using a member variable (tags here), you could loop over it to avoid the getter and some additional overhead. The following would also work
<form [formGroup]="foodForm">
    Name:
    <input formControlName="foodName" />

    <ng-container *ngFor="let tag of tags">
      {{ tag | titlecase }}
      <input [formControlName]="tag" type="checkbox">

    </ng-container>

</form>

Working example: Stackblitz

A: use keyvalue pipe as you are using object instead of array
<input *ngFor="let tag of tagsForForm| keyvalue" [formControlName]="tag.value" type="checkbox">

use this link for more info https://angular.io/api/common/KeyValuePipe


text:
Q: How do I implement popup dialog for login in Android that never pops up until logout? I am trying to do the code in android for first time showing the dialog popup for login screen and after login the popup will be removed and after that it will not open until you do not logout from the screen.

A: You can store a boolean variable i.e. True or False value in SQLite database or Shared Preference... Check its value whenever someone is opening your app If true than dont show Login screen otherwise Show login Screen :)
You can check boolean variable when your app is showing Splash Screen ...

A: For this, first set value in SharedPreference as false. Every time when you open the app, check value from SharedPreference. If it is false, then show the login popup.
Once login is successfully performed, set value as true in shared preference and again set it to  false on logout.

A: use SharedPreferences
SharedPreferences preferences =PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
//login success
preferences.edit().putBoolean("login",true).commit();
//logout success
preferences.edit().putBoolean("login",false).commit();
//Whether the display dialog
boolean isLogin = preferences.getBoolean("login",false);
if(!isLogin){
 showLoginDialog();
}else{
enterHome();
}

A: Storing shared preferences is probably not the best idea since after login you probably have some type of access token or something to use for request authorisation. By saving a boolean, you will have two variables stored that can be used to deduce the same thing. So you can just write a function that checks whether you have a valid token stored or what every it is you use to authorise requests after login.  If you are using the accountmanager or something then you should use that to verify the user is still logged in.


text:
Q: Function for ip reserved addresses checking I have a list of ip adrresses. I want to know if any of them is a reserved address (ref: http://en.wikipedia.org/wiki/Reserved_IP_addresses ). For my works I'm using awk so I'm wondering if there are some pre-made shell scripts or similar that could help me in identifyng such addresses.

A: Do you know about unix grep ?
You can have grep search for a list of target strings stored in a file, in your other files.
 fgrep -f reservedList.txt yourListOfIpsSavedToAfile

will print any lines in yourList* that matches any word found in reservedList.
If you are doing this inside a shell script, then you can make your actions conditional
 if fgrep -f reservedList.txt yourList > /dev/null 2>&1 ; then
    echo "found items in reserved List"
 else
    echo "no items found in reserved List"
 fi

You may need to use grep -F reservedList ..... Use the first example above to see that is working, and if not consult man grep to see which exact arguments to use in your OS/grep versions.
If you really need to do this in awk, you'll basically be remaking this functionality in awk.
I hope this helps.

A: If you feed your list of good old IPv4 addresses line by line as input to the script
while IFS=. read A B C D
do  ADDR=`printf %03d.%03d.%03d.%03d $A $B $C $D`
    [[ 000.255.255.255 < $ADDR && $ADDR < 010.000.000.000 ]] && continue
    [[ 010.255.255.255 < $ADDR && $ADDR < 100.064.000.000 ]] && continue
    [[ 100.127.255.255 < $ADDR && $ADDR < 127.000.000.000 ]] && continue
    [[ 127.255.255.255 < $ADDR && $ADDR < 169.254.000.000 ]] && continue
    [[ 169.254.255.255 < $ADDR && $ADDR < 172.016.000.000 ]] && continue
    [[ 172.031.255.255 < $ADDR && $ADDR < 192.000.000.000 ]] && continue
    [[ 192.000.000.007 < $ADDR && $ADDR < 192.000.002.000 ]] && continue
    [[ 192.000.002.255 < $ADDR && $ADDR < 192.088.099.000 ]] && continue
    [[ 192.088.099.255 < $ADDR && $ADDR < 192.168.000.000 ]] && continue
    [[ 192.168.255.255 < $ADDR && $ADDR < 198.018.000.000 ]] && continue
    [[ 198.019.255.255 < $ADDR && $ADDR < 198.051.100.000 ]] && continue
    [[ 198.051.100.255 < $ADDR && $ADDR < 203.000.113.000 ]] && continue
    [[ 203.000.113.255 < $ADDR && $ADDR < 224.000.000.000 ]] && continue
    echo $A.$B.$C.$D is reserved
done

, it will output any reserved addresses.


text:
Q: How to call Facebook Api to extract data and prefil a Form I am doing a registration form where I call the facebook API get some data and fill my form with the data needed. I am doing smth like this in my controller:
$scope.fbRegister = function () {

            facebookConnectPlugin.getLoginStatus(function (success) {

                if (!cordova) {
                    //this is for browser only
                    facebookConnectPlugin.browserInit(FACEBOOK_APP_ID);
                }
                alert(JSON.stringify(success, null, 3));
                if (success.status === 'connected') {
                    // the user is logged in and has authenticated your app, and response.authResponse supplies
                    // the user's ID, a valid access token, a signed request, and the time the access token
                    // and signed request each expire

                    facebookConnectPlugin.api("me/?fields=id,first_name,last_name,link,gender,email,birthday", ["public_profile", "email", "user_birthday"],
                        function(result) {
                            alert("Result: " + JSON.stringify(result));
                            alert(result.first_name);

        $scope.formData = {
            name: result.first_name,
            password: "",
            confirmPassword: "",
            email: '',
        };
        })
        }

However I don't get the prefiled data in   name: result.first_name,.
I make an alert for that and I get the data but I cant get it fill the form.
Thank you


text:
Q: So if my tv does not work well and the hdmi is still plugged in and I unplug the cord for the tv out of the wall frequently will it damage my xbox? So this is what happened my tv does not turn on very well but it will still turn on but if I keep on unplugging the cord connected to the wall since the hdmi is still plugged in will it damage my Xbox if I do this frequently and if it does how badly?

A: No.
If anything, your HDMI cable will be damaged long before your console.


text:
Q: Meaning of "bearing"
Knowledge having a bearing on human life was placed highest
Knowledge about human life was placed highest

A: From Wiktionary:

bearing (n., pl. bearings)
  1. A mechanical device that supports another part and/or reduces friction.
  2. (nautical) The horizontal angle between the direction of an object and that of true north; >subject to variation and deviation when taken by a magnetic compass
3. Relevance; a relationship or connection. "That has no bearing on this issue."
  4. One's posture, demeanor, or manner.

So, in your sentence, bearing uses the third definition that is given, which I rewrite as "to have a relationship or a relevance with."  That is, your sentence might be rephrased as the following: "Knowledge that has to do with, or has a connection with, human life was placed highest."

A: The meaning of bearing on is "relation or relevance" (bearing is a noun).
The meaning of about is (among others) "on the subject of; concerning."
The difference between the two sentences is that in the first the knowledge is related to human life, while in the second the knowledge topic is human life.
Bearing on is usually used in sentences such as "the case has no direct bearing on the issues."
If I should choose between the two sentences, I would choose the second one. Alternatively, I would rephrase the sentence, but I don't see any reason to not use about.


text:
Q: Boolean field values differ between the InfoPath form and the SP view. Why? I've got a 2010 SP list that tracks tickets about an application I own. It tracks various ticket attributes including'status' and 'type'. I want to create a view of 'open' tickets for my developers based on the value of 'status' and/or 'type'.  There are enough options for these fields that I've run out of filter options on the view.  So, I've added a calculated-column, boolean field, call it 'DevOpen', to the InfoPath form.  I've written a formula to determine this fields value as follows;
not((Status = "A") or (Status = "B") or (Type = "1"))
where the bold text are inserted fields and status A and B and type 1 are associated with 'closed' tickets.
When I open the form, the value of the Boolean field value is correct...either true or false...according to the formula.
My problems are two-fold.  First when I add this new field to a view, the values are wrong.  There are several variants; the InfoPath form properly shows 'true' but the view shows 'No', the InfoPath form rightly shows 'false' and the view shows nothing/blank, or the InfoPath form shows 'true' and view shows nothing/blank.
Secondly and likely related to the first point, when I try to use this new field to filter a view it doesn't work.  Again, I'm trying to get a view of open tickets.  I've tried all variants of the filter criteria (Yes/yes/true/True/etc. and No/no/False/false/etc.).  Nothing seems to work properly although if I set the 'DevOpen' field filter to 'No' I do get tickets shown but they're not the ones I want.  I want DevOpen=true/yes tickets to be shown.
What am I doing wrong?

A: SharePoint Formulas can not do operators like A OR B
SharePoint has logical functions
So the syntax for a Calculated Column Formula is:
NOT( OR(  OR([Status]="A",[Status]="B")  ,  [Type]="1"  ) )


text:
Q: Assigning specific dictionary values to variables I have a series of dictionaries which each contain the same keys but their values are different i.e Age in dictionary 1 = 2, Age in dictionary 2 = 4 etc etc but they are broadly identical in structure.
what I would like to do is to randomly select one of these dictionaries and then assign specific values with the dictionary to variables. i.e python randomly chooses Dictionary 1 and then I then want to fill the dictAge variable with the age value from Dictionary 1.
import random

dictList = ['myDict', 'otherDict']

mydict = {
    'age' : 10,
    'other': "dummy data"
    }
.
.
.

randomDict = random.choice(dictList)

dictAge = randomDict['age']

print(dictAge)

In the case of the code above what should happen is:
randomDict is assigned a random value from the distList variable (at the top). This sets which dictionary's values will be used going forward.
I next want the dictAge variable to then be assigned the age value from the selected dictionary. In this case (as mydict is was the only dictionary available) it should be assigned the age value of 10.
The error I am getting is:
TypeError: string indices must be integers
I know this is such a common error but my brain can't quite work out what the best solution is.
(Disclaimer: I haven't used python in ages so I know I am doing something really obviously silly but I can't quite work out what to do).

A: Right now, you are not actually using the definition of your dicts.
This is because dictList is comprised of strings: ['myDict', 'otherDict'].
So, when doing randomDict = random.choice(dictList), randomDict will either be the string 'myDict', or the string 'otherDict'.
Then you are doing randomDict['age'], which means you are trying to slice a string, with a string. As the error suggests, this can't be done and indices can only be ints.

What you want to do, is move the definition of the dictList to be after the definitions of your dicts, and include references to the dicts themselves, not strings. Something like:
mydict = {
    'age' : 10,
    'other': "dummy data"
    }
.
.
.
dictList = [myDict, otherDict]

A: In the following piece of code:
dictAge = randomDict['age']

You are trying to index the name of dictionary variable (a string) returned by random.choice function.
To make it work you would need to do it using locals:
locals()[randomDict]['age']

or rather correct the dictList to contain the dictionaries instead of their names:
dictList = [myDict, otherDict]

In the latter case please note that myDict and otherDict should be declared before dictList.


text:
Q: Force Xcode4 to use different themes for header and implementation files Is there some hack to force Xcode4 to use different themes for header and implementation files?

A: If you want to modify default header, you can modify file templates in: /Developer/Library/Xcode/Templates/File Templates/ directory.


text:
Q: Store Image NSData to varbinary SQl server using php I am using iPhone app which capture picture , I want to save this picture in sql server database using php. The formate for image store in sql server which I am using is VarBinary. I want to store my NSData of image in VarBinary so that Image can be saved in database.
Please see below the code which I am using to insert the image. Basically image is stored in image1 column with data type var
 <?php
           $Image1 = $_POST["Image1"];
           $Image2 = "0x";
           $Image3 = "0x";
           $Image4 = "0x";
           $Image5 = "0x";
           try
          {
         $stmt = $db->prepare("INSERT INTO TableM (Image1, Image2, Image3, Image4, Image5)
         VALUES ($Image1, convert(VARBINARY(max), $Image2), convert(VARBINARY(max), $Image3), convert(VARBINARY(max), $Image4), convert(VARBINARY(max), $Image5))");
         $stmt->execute();

        if($stmt->rowCount() > 0)
                 {
                  $response = new stdClass();
                                               $response->results = "Record added successfully";
                                               echo json_encode($response);
                               }
                               else
                               {

                                               $response = new
                                                          stdClass();
                                               $response->results =
               "No record added";
                                               echo
            json_encode($response);

                               }

                               $db = null;
       }
       catch(Exception $e)
       {
       echo($e->getMessage());
        }

   }    catch (PDOException $e) {
   print "Error!: " . $e->getMessage() . "<br/>";
               die();
   }

 ?>


text:
Q: z-index and CSS rotate I have made some flip cards using CSS and HTML and CSS transitions
When you hover over the card it flips and enlarges. How can I position the current card that is hovered over to put it on the top using z-index with position relative as its having a problem using css transform:rotate?
So I need the card that is hovered over to be on top.

/* The flip card container - set the width and height to whatever you want. We have added the border property to demonstrate that the flip itself goes out of the box on hover (remove perspective if you don't want the 3D effect */
.flip-card {
  background-color: transparent;
  width: 180px;
  height: 200px;
  border: 1px solid #f1f1f1;
  perspective: 1000px; /* Remove this if you don't want the 3D effect */
}

/* This container is needed to position the front and back side */
.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.8s;
  transform-style: preserve-3d;
}

/* Do an horizontal flip when you move the mouse over the flip box container */
.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg) scale(1.3);
}

/* Position the front and back side */
.flip-card-front, .flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

/* Style the front side (fallback if image is missing) */
.flip-card-front {
  background-color: #bbb;
  color: black;
    z-index:1;

}

/* Style the back side */
.flip-card-back {
    z-index:999;
  background-color: dodgerblue;
  color: white;
  transform: rotateY(180deg);
}

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

A: try by adding z-index to .flip-card:hover class.

/* The flip card container - set the width and height to whatever you want. We have added the border property to demonstrate that the flip itself goes out of the box on hover (remove perspective if you don't want the 3D effect */

.flip-card {
  background-color: transparent;
  width: 180px;
  height: 200px;
  border: 1px solid #f1f1f1;
  perspective: 1000px;
  /* Remove this if you don't want the 3D effect */
}

/* This container is needed to position the front and back side */

.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.8s;
  transform-style: preserve-3d;
}

/* Do an horizontal flip when you move the mouse over the flip box container */

.flip-card:hover {
  z-index: 10;
  position: relative;
}

.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg) scale(1.3);
}

/* Position the front and back side */

.flip-card-front,
.flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

/* Style the front side (fallback if image is missing) */

.flip-card-front {
  background-color: #bbb;
  color: black;
  z-index: 1;
}

/* Style the back side */

.flip-card-back {
  z-index: 999;
  background-color: dodgerblue;
  color: white;
  transform: rotateY(180deg);
}

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

A: Add position: relative in your .flip-card class and add z-index: 1 in hover case .flip-card:hover
The flip card container - set the width and height to whatever you want. We have added the border property to demonstrate that the flip itself goes out of the box on hover (remove perspective if you don't want the 3D effect

.flip-card {
  background-color: transparent;
  width: 180px;
  height: 200px;
  border: 1px solid #f1f1f1;
  perspective: 1000px; /* Remove this if you don't want the 3D effect */
  position: relative
}
.flip-card:hover {
  z-index: 1
}

/* This container is needed to position the front and back side */
.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.8s;
  transform-style: preserve-3d;
}

/* Do an horizontal flip when you move the mouse over the flip box container */
.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg) scale(1.3);
}

/* Position the front and back side */
.flip-card-front, .flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

/* Style the front side (fallback if image is missing) */
.flip-card-front {
  background-color: #bbb;
  color: black;
    z-index:1;

}

/* Style the back side */
.flip-card-back {
    z-index:999;
  background-color: dodgerblue;
  color: white;
  transform: rotateY(180deg);
}

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

A: You have to add z-index on flip-card:hover also add position:relative to card

/* The flip card container - set the width and height to whatever you want. We have added the border property to demonstrate that the flip itself goes out of the box on hover (remove perspective if you don't want the 3D effect */
.flip-card {
  background-color: transparent;
  width: 180px;
  height: 200px;
  border: 1px solid #f1f1f1;
  position: relative;
  perspective: 1000px; /* Remove this if you don't want the 3D effect */
}

/* This container is needed to position the front and back side */
.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.8s;
  transform-style: preserve-3d;
}

/* Do an horizontal flip when you move the mouse over the flip box container */
.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg) scale(1.3);
}

/* Position the front and back side */
.flip-card-front, .flip-card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

/* Style the front side (fallback if image is missing) */
.flip-card-front {
  background-color: #bbb;
  color: black;
    z-index:1;

}

/* Style the back side */
.flip-card-back {
    z-index:999;
  background-color: dodgerblue;
  color: white;
  transform: rotateY(180deg);
}
.flip-card:hover{
z-index: 9;
}

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy

John Doe

Architect & Engineer

We love that guy


text:
Q: Solving a non-linear congruence for $f\in \mathbb{F}_5[x]$ How can we find a solution $f\in \mathbb{F}_5[x]$ for the following non-linear congruence?
$ f\equiv 1\mod{x}+1,\ x\cdot f\equiv x+1\mod{x^2}+1,\ (x+1)\cdot f\equiv x+ 1\mod{x^3}+1  $

A: Hint
First you need to find inverse of $x$ modulo $x^2+1$. Then use the Chinese Remainder Theorem idea.
For the inverses observe:
$$x^2+ 1 \equiv 0 \pmod{x^2+1,5} \implies x(4x) \equiv 1 \pmod{x^2+1,5}.$$
Thus the second congruence can be written as
$$xf(x) \equiv x+1 \pmod{x^2+1} \implies \color{blue}{f(x) \equiv (4x)(x+1) \equiv 4x+1 \pmod{x^2+1,5}}.$$
Can you procced from here?