Q: GCC finding errors in MinGW's stdio.h I'm trying to compile some example C code with GCC/MinGW on Windows 7. The example code includes some local header files which ultimately include stdio.h, and I get this error when I try to compile:
c:\mingw\include\stdio.h:345:12: error: expected '=', ',', ';', 'asm' or '__attribute__' before '__mingw__snprintf'
extern int __mingw_stdio_redirect__(snprintf)(char*, size_t, const char*, ...);

This is a weird one to me. How could there possibly be errors in stdio.h?

A: regarding:
if (i == 0)
{
    printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
    return 0;
}
pcap_freealldevs(alldevs);

since the variable i is initialized to 0 and never modified, this if() statement will always be true.  One result is the call to: pcap_freealldev() will never be called.
the scope of variables should be limited as much as reasonable.
Code should never depend on the OS to clean up after itself.  suggest
#include <stdio.h>
#include <stdlib.h>
#include "pcap.h"

int main( void )
{
    pcap_if_t *alldevs = NULL;
    char errbuf[PCAP_ERRBUF_SIZE];

    /* Retrieve the device list from the local machine */
    if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL /* auth is not needed */, &alldevs, errbuf) == -1)
    {
        fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf);
        exit(1);
    }

    /* Print the list */
    for( pcap_if_t *d = alldevs; d != NULL; d= d->next)
    {
        printf("%d. %s", ++i, d->name);
        if (d->description)
            printf(" (%s)\n", d->description);
        else
            printf(" (No description available)\n");
    }

    if ( ! alldevs )
    {
        printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
    }

    /* We don't need any more the device list. Free it */
    pcap_freealldevs(alldevs);
}


Q: What does !! mean in ruby? Just wondering what !! is in Ruby.

A: Note that this idiom exists in other programming languages as well.  C didn't have an intrinsic bool type, so all booleans were typed as int instead, with canonical values of 0 or 1.  Takes this example (parentheses added for clarity):
!(1234) == 0
!(0) == 1
!(!(1234)) == 1

The "not-not" syntax converts any non-zero integer to 1, the canonical boolean true value.
In general, though, I find it much better to put in a reasonable comparison than to use this uncommon idiom:
int x = 1234;
if (!!x); // wtf mate
if (x != 0); // obvious

A: It returns true if the object on the right is not nil and not false, false if it is nil or false
def logged_in?
  !!@current_user
end

A: It's useful if you need to do an exclusive or. Copying from Matt Van Horn's answer with slight modifications:
1 ^ true
TypeError: can't convert true into Integer

!!1 ^ !!true
=> false

I used it to ensure two variables were either both nil, or both not nil.
raise "Inconsistency" if !!a ^ !!b

A: It is "double-negative", but the practice is being discouraged.  If you're using rubocop, you'll see it complain on such code with a Style/DoubleNegation violation.
The rationale states:

As this is both cryptic and usually redundant, it should be avoided
  [then paraphrasing:] Change !!something to !something.nil?

A: Not not.
It's used to convert a value to a boolean:
!!nil   #=> false
!!"abc" #=> true
!!false #=> false

It's usually not necessary to use though since the only false values to Ruby are nil and false, so it's usually best to let that convention stand.
Think of it as
!(!some_val)

One thing that is it used for legitimately is preventing a huge chunk of data from being returned.  For example you probably don't want to return 3MB of image data in your has_image? method, or you may not want to return your entire user object in the logged_in? method.  Using !! converts these objects to a simple true/false.

A: ! means negate boolean state, two !s is nothing special, other than a double negation.
!true == false
# => true

It is commonly used to force a method to return a boolean. It will detect any kind of truthiness, such as string, integers and what not, and turn it into a boolean.
!"wtf"
# => false

!!"wtf"
# => true

A more real use case:
def title
  "I return a string."
end

def title_exists?
  !!title
end

This is useful when you want to make sure that a boolean is returned. IMHO it's kind of pointless, though, seeing that both if 'some string' and if true is the exact same flow, but some people find it useful to explicitly return a boolean.

A: Understanding how it works can be useful if you need to convert, say, an enumeration into a boolean. I have code that does exactly that, using the classy_enum gem:
class LinkStatus < ClassyEnum::Base
  def !
    return true
  end
end

class LinkStatus::No < LinkStatus
end

class LinkStatus::Claimed < LinkStatus
  def !
    return false
  end
end

class LinkStatus::Confirmed < LinkStatus
  def !
    return false
  end
end

class LinkStatus::Denied < LinkStatus
end

Then in service code I have, for example:
raise Application::Error unless !!object.link_status   # => raises exception for "No" and "Denied" states.

Effectively the bangbang operator has become what I might otherwise have written as a method called to_bool.

A: Other answers have discussed what !! does and whether it is good practice or not.
However, none of the answers give the "standard Ruby way" of casting a value into a boolean.
true & variable

TrueClass, the class of the Ruby value true, implements a method &, which is documented as follows:

Returns false if obj is nil or false, true otherwise.

Why use a dirty double-negation when the standard library has you covered?


Q: Setting up a Sensu-Go cluster - cluster is not synchronizing I'm having an issue setting up my cluster according to the documents, as seen here: https://docs.sensu.io/sensu-go/5.5/guides/clustering/
This is a non-https setup to get my feet wet, I'm not concerned with that at the moment. I just want a running cluster to begin with.
I've set up sensu-backend on my three nodes, and have configured the backend configuration (backend.yml) accordingly on all three nodes through an ansible playbook. However, my cluster does not discover the other two nodes. It simply shows the following:
For backend1:
=== Etcd Cluster ID: 3b0efc7b379f89be
         ID                Name                Peer URLs              Client URLs
 ────────────────── ─────────────────── ─────────────────────── ───────────────────────
  8927110dc66458af   backend1   http://127.0.0.1:2380   http://localhost:2379

For backend2 and backend3, it's the same, except it shows those individual nodes as the only nodes in their cluster.
I've tried both the configuration in the docs, as well as the configuration in this git issue: https://github.com/sensu/sensu-go/issues/1890
None of these have panned out for me. I've ensured all the ports are open, so that's not an issue.
When I do a manual sensuctl cluster member-add X X, I get an error message and it results in the sensu-backend process failing. I can't remove the member, either, because it causes the entire process to not be able to start. I have to revert to an earlier snapshot to fix it.
The configs on all machines are the same, except the IP's and names are appropriated for each machine
etcd-advertise-client-urls: "http://XX.XX.XX.20:2379"
etcd-listen-client-urls: "http://XX.XX.XX.20:2379"
etcd-listen-peer-urls: "http://0.0.0.0:2380"
etcd-initial-cluster: "backend1=http://XX.XX.XX.20:2380,backend2=http://XX.XX.XX.31:2380,backend3=http://XX.XX.XX.32:2380"
etcd-initial-advertise-peer-urls: "http://XX.XX.XX.20:2380"
etcd-initial-cluster-state: "new" # have also tried existing
etcd-initial-cluster-token: ""
etcd-name: "backend1"

A: Did you find the answer to your question? I saw that you posted over on the Sensu forums as well.
In any case, the easiest thing to do in this case would be to stop the cluster, blow out /var/lib/sensu/sensu-backend/etcd/ and reconfigure the cluster. As it stands, the behavior you're seeing seems like the cluster members were started individually first, which is what is potentially causing the issue and would be the reason for blowing the etcd dir away.


Q: How to get Spring MVC Controller to load lazily? I am not able to get Spring MVC Controllers to lazy load.
I have tried the solution mentioned in Does Spring MVC initialize all controllers on start up??
Here is my code:
app-servlet.xml
<context:component-scan base-package="com.mvc.controller">

AssetController.java
@Lazy(value=true)
@Controller
@RequestMapping("/api/asset")
public class AssetController{

  @Autowired
  private AssetService assetService;

What am I missing here?
Spring v3.0.7

A: @RequestMapping annotation makes controller to be initialized eagerly despite the fact that it is also annotated with @Lazy(value=true).
In your case, removing @RequestMapping annotation should make the controller initialize lazily. Though I do not know if it is possible to use @RequestMapping annotation and have that controller load lazily, I did not manage to achieve it (solved my issue without making the controller load lazily, but that is out of scope of this question).


Q: AngularJS: format element text with a function I have an element
Link

And a function getDomain(url) that returns domain.
I want the '.linkCol' element to have text returned by getDomain(ad.url).
It's all inside an ng-repeat.
How do I do this?

A: getDomain() needs to be added to the scope in the controller...
$scope.getDomain = function(url) {
    // ...
    return domain;
};

Then you can use it in your view...

    {{ getDomain(ad.url) }}


Q: how to retrieve only current date data from SQLite database? I'm storing the date and time in SQLite Db. I want to retrieve only data of current data. I have search internet for a solution but I couldn't find any answers.
My code:
Creating Table
  public void onCreate(SQLiteDatabase sqLiteDatabase) {
        final String query = "CREATE TABLE " + Db_Contract.Db_Fieds.TABLE_NAME +" ("
                + Db_Contract.Db_Fieds._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + Db_Contract.Db_Fieds.MONEY+ " REAL NOT NULL,"
                + Db_Contract.Db_Fieds.CAT+" TEXT NOT NULL,"
                + Db_Contract.Db_Fieds.TIMESTAMP+" TIMESTAMP DEFAULT CURRENT_TIMESTAMP"+"); " ;
        sqLiteDatabase.execSQL(query);
    }

Retrieving all data :
   private Cursor getAllData()
    {
        return db.query(Db_Contract.Db_Fieds.TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                Db_Contract.Db_Fieds.TIMESTAMP);
    }

Here I want to retrieve  only the data of current date


Q: Narrowing conversions and initializer lists, which compiler is right? Considering the following piece of code:
#include <iostream>

auto main() -> int {
  double x(7.0);
  int i{x};
  std::cout << "i = " << x << std::endl;

  return 0;
}

*

*When compiled in GCC4.9 it compiles fine with only a warning:

warning: narrowing conversion of ‘x’ from ‘double’ to ‘int’ inside { }

*

*Compiling with either Clang3.3 or VC++2013 gives a compile error:

error: type 'double' cannot be narrowed to 'int' in initializer list
error C2397: conversion from 'double' to 'int' requires a narrowing

Questions:

*

*Which of the compilers is right according to the standard?

*Is there any reason why the compilers mentioned above should exhibit such diverse behaviour?

A: The answer
Both compilers are correct!

Explanation
The Standard doesn't distinguish between an error and a warning, both go under the category of Diagnostics.

1.3.6 diagnostic message [defns.diagnostic]

message belonging to an implementation-defined subset of the implementation's output messages

Since the Standard says that a diagnostic is required in case a program is ill-formed, such as when a narrowing-conversion takes place inside a braced-initializer, both compilers are confirming.
Even if the program is ill-formed from the Standards point of view, it doesn't mandate that a compiler halts compilation because of that; an implementation is free to do whatever it wants, as long as it issues a diagnostic.

The reason for gcc's behavior?
Helpful information was provided by @Jonathan Wakely through comments on this post, below are a merge of the two comments;

he exact reason is that GCC made it an error at one point and it broke ALL THE PROGRAMS so it got turned into a warning instead. Several people who turned on the -std=c++0x option for large C++03 codebases found harmless narrowing conversions to cause most of the porting work to go to C++11See e.g. PR 50810 where Alisdair reports narrowing errors were >95% of the problems in Bloomberg's code base.In that same PR you can see that unfortunately it wasn't a case of "let's just issue a warning and be done with it" because it took a lot of fiddling to get the right behaviour.


Q: banshee: How would I set the rating for a specific track on Banshee through DBus? I'd like to set the 'rating' of a specific track (i.e. not only the one currently playing) on Banshee through the DBus interface?

A: Banshee does not expose rating functions via DBus.
You can quickly view all functions that it exposes, using applications like d-feet[1]. Make sure that an instance of the application you are interested in (like Banshee in this case) is running.
There is a bug report already requesting to add rating functionality[2] to DBus interface. You might want to subscribe to it.

*

*https://fedorahosted.org/d-feet/

*https://bugzilla.gnome.org/show_bug.cgi?id=579754

A: Banshee does support rating via commandline since last year.
banshee --set-rating={1;2;3;4;5}

See the bug report for more options:
Add item rating to DBus interface

A: Sadly the developer have not implemented a GET method, so there is no common way to execute "rate current track 1 star up/down"-command, much less than a specific track.
Does anyone has written a script which provide this feature?
Yet, I haven't found any solution to modify the D-Bus Property via command line.
Finally here is my Workaround for rate the current played Track.
#!/bin/bash

#read current TrackRating
R=$(qdbus org.mpris.MediaPlayer2.banshee /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get org.mpris.MediaPlayer2.Player Metadata | grep 'userRating' | tr -d '/xesam:userRating: ')

case $R in
 '' )    R=0 ;;
 '0.2' ) R=1 ;;
 '0.4' ) R=2 ;;
 '0.6' ) R=3 ;;
 '0.8' ) R=4 ;;
 '1'   ) R=5 ;;
esac

case $1 in
 'inc' )    [ $R -lt 5 ]
            banshee --set-rating=$(($R+1)) ;;
 'dec' )    [ $R -gt 0 ]
            banshee --set-rating=$(($R-1)) ;;
 'res' ) banshee --set-rating=3 ;;
 'min' ) banshee --set-rating=0 ;;
 'max' ) banshee --set-rating=5 ;;
esac

Options:

*

*inc -> increase rating by one if possible

*dec -> decrease rating by one if possible

*res -> reset rating to three stars

*min -> set rating to zero stars

*max -> set rating to five stars

As far Banshee will not provide manipulating data of a specific Track this is my best bet.


Q: python : recognising if a list has no duplicate numbers Im currently working on a game which uses lists and gives users choices depending on if there is/isnt duplicates in a list (really basic text based game), however i cant seem to code something that recognises if there is no duplicates without looping through and checking if the count for each number is greater than 1. I really just need something that would check if the list contains no duplicates so that i can then write the rest of the program.
so the psuedocode would look something like this
numbers = [1, 3, 5, 6]
check list for duplicates
if no duplicates:
do x

A: Use set function with sorted:
if sorted(set(y)) == sorted(y):
    pass

Set remove duplicates from given list so its easy to check if your list has duplicates. Sorted its optional but if you give user option to input numbers in other order this will be helpful then.
set()
sorted()
Simpler solution if you don't need sorted use:
len(y) != len(set(y))

Its faster because u dont need use sort on both lists. Its return True of False.
Check for duplicates in a flat list

A: You can check the length of the set of the list and compare with its regular length:
l = [1, 3, 32, 4]
if len(set(l)) == len(l):
   pass


Q: Less number of levels for a categorical variable in decision tree output I am presently fitting a model using decision tree and the data set contains both numeric and categorical variables. One of the variable is a categorical variable A having 3 levels: Good, Bad and Medium. Now, when I fit the model using 'tree' package, it gave the tree output with A as my root node but with only 2 levels and the significant level, Good is not included in the tree. To experiment, I have increased the Good values in the input dataset to more than 200 in a dataset of 400 but still it did not included it in the tree output. Why is that so?. And what to do force it to include Good in the tree?.


Q: How to make a rollback in functions with transactions annotation in case if save operation returns null? I use Spring Boot 5 and MongoDB in my project. When I save a user in users collection I also need to save authority of the user in another collection. In case if an error has happened and one of the items did not saved I have to rollback the operation to prevent the saving
of the another item in case if it saved.
For this purpose I use Transaction annotation above my create method:
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService{

    @Autowired
    public AutoMapper autoMapper;

    private final UserRepository userRepository;
    private final AdminUserRepository adminUserRepository;

    @Override
    @Transactional
    public SaveBuilderResponse create(UserDto newUser){

        AdminUser adminUser = autoMapper.map(newUser, AdminUser.class);
        User userToSave = autoMapper.map(newUser, User.class);

        AdminUser savedAdminUser = adminUserRepository.save(adminUser);
        User savedUser = userRepository.save(builderToSave);

        return new SaveUserResponse(savedUser);
    }
}

As you can see in function above I have two rows that saves items:
        AdminUser savedAdminUser = adminUserRepository.save(adminUser);
        User savedBuilder = userRepository.save(userToSave);

After the the row above executed I need to check that returned value not null and proceed. In case if savedAdminUser or savedBuilder variables is null I need to do a rollabck to prevent the saving operation of the another item in case if it saved.
My question is how can I do rollback in case if savedAdminUser or savedUser variables is null?

A: you used, @Transactional annotation can rollback in case if savedAdminUser or savedUser variables is null.  Also you Should throw an exception like below.
@Override
@Transactional
public SaveBuilderResponse create(UserDto newUser) throws Exception {
    try {
        AdminUser adminUser = autoMapper.map(newUser, AdminUser.class);
        User userToSave = autoMapper.map(newUser, User.class);

        AdminUser savedAdminUser = adminUserRepository.save(adminUser);
        User savedUser = userRepository.save(builderToSave);

        return new SaveUserResponse(savedUser);
    } catch (Exception ex) {
        throw ex;
    }
}

A: If you don't want to engage with custom exception you can simply do (before the last return statement)  :
if (adminUser == null || savedBuilder == null) {
   //do whatever you want
   return null;

}


Q: Calling @CacheEvict and @Cacheable annotation on a single method? I'm trying to call @CacheEvict and @Cacheable annotation on a single method.
@CacheEvict(value = "tripDetailsDashboardCache", key = "#userId")
@Cacheable(value ="tripDetailsDashboardCache", key="#userId")
public  List<DashBoardObject> getAllDetailsForDashBoard(Integer userId){
    List<Master> masters = tripDetailsService.getTripDetailsForCaching(userId);
    List<DashBoardObject> dashBoardObject = tripDetailsService.getMasterDetailsForDashBoard(userId, masters);
    return dashBoardObject;
}

On call of @CacheEvict, I want to delete the cached data for the particular key and again i want to cache the fresh data of the method response. But it is not caching the fresh data ?. And also it is not giving any error ?.

A: I think you want to update the cache, so try to use @CachePut, method will be executed in all cases, if the key is new, new record will be added in the cache, if the record is old, old value will be updated by new value (refresh the value).
@CachePut(value = "tripDetailsDashboardCache", key = "#userId")
public  List<DashBoardObject> getAllDetailsForDashBoard(Integer userId){
    List<Master> masters = tripDetailsService.getTripDetailsForCaching(userId);
    List<DashBoardObject> dashBoardObject = tripDetailsService.getMasterDetailsForDashBoard(userId, masters);
    return dashBoardObject;
}

A: @CacheEvict runs by default after the method invocation. So the method above does the caching the list with  key #userId and then clear the cache completely .
it makes the code unclear I’d recommend creating separate cacheable and cache-evict methods

A: Look at docs. There are @Caching annotation where you can define your @Cacheable, @CachePut and @CacheEvict


Q: show line in screen (read file j2me)? i want to read a file in j2me and show it in screen i try very a lot , exactly i try all code exist in web but no one worked. this is just one of them :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package file;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.file.*;
import javax.microedition.io.*;
import java.io.*;
 /**
 * @author ZARA-T
 */
public class ReadMidlet extends MIDlet implements CommandListener {

  private Display display;
  private Form form;
  private Command read, exit;
  StringBuffer buff;

  public void startApp(){
    display = Display.getDisplay(this);
    read = new Command("Read", Command.EXIT, 1);
    exit = new Command("Exit", Command.EXIT, 1);
    form = new Form("Read File");
    form.addCommand(exit);
    form.addCommand(read);
    form.setCommandListener(this);
    display.setCurrent(form);
  }

  public void pauseApp(){}

  public void destroyApp(boolean unconditional){
    notifyDestroyed();
  }

  public void commandAction(Command c, Displayable s){
      if (c==read) {
          try {
              String SS;
              SS=ReadFile("file:///root1//hello.txt");
              TextBox input = new TextBox("Enter Some Text:", "", 5, TextField.ANY);
              input.setString(SS);
              display.setCurrent(input);
          } catch (IOException ex) {
              ex.printStackTrace();
          }
    }
    if (c==exit)  destroyApp(false);

  }
 private String ReadFile(String url) throws IOException {
        FileConnection fc = (FileConnection) Connector.open(url,Connector.READ);
        AlertType.ERROR.playSound(display);
        StringBuffer sb = new StringBuffer();
        try {
          InputStream in = fc.openInputStream();
          try {
            int i;
            while ((i = in.read()) != -1) {
              sb.append((char) i);
            }
          } finally {
            in.close();
          }
        } finally {
          fc.close();
        }
       form.append(sb.toString());
    return sb.toString();
    }
}

I put this CODE line to test which line cause error.
AlertType.ERROR.playSound(display);

it seems this line can't be run.also i read the POSTS here (stackOverflow) but i could not solve my problem. tnx for ur helping.

A: Here is my version of an OpenFileDialog for Java ME.
public class OpenFileDialog extends List
  implements CommandListener
{
  public static final String PREFIX = "file:///";
  private static final String UP = "[ .. ]";
  private static final String DIR = " + ";
  private Stack stack = new Stack();
  private OpenFileListener listener;
  private CommandListener commandListener;
  private String extension;

  public OpenFileDialog (OpenFileListener listener,
     String title, String extension)
  {
    super(title, List.IMPLICIT);
    super.setCommandListener(this);
    this.listener = listener;
    this.extension = extension;
    addRoots();
  }

  public void setCommandListener(CommandListener l) {
    this.commandListener = l;
  }

  public void commandAction(Command c, Displayable d) {
    if (c == List.SELECT_COMMAND) {
      this.changeSelection();
    } else {
      if (this.commandListener != null) {
        this.commandListener.commandAction(c, d);
      }
    }
  }

  private String getSelectedText () {
    int index = getSelectedIndex();
    if (index < 0 || index >= this.size()) {
      return "";
    }
    return this.getString(index);
  }

  private void changeSelection () {
    String target = this.getSelectedText();
    String parent = null;
    boolean goingUp = false;

    if (UP.equals(target)) {
      goingUp = true;
      stack.pop();
      if (stack.isEmpty() == false) {
        target = (String) stack.peek();
      } else {
        super.deleteAll();
        addRoots();
        this.setTicker(null);
        return;
      }
    } else {
      if (stack.isEmpty() == false) {
        parent = stack.peek().toString();
      }
    }

    try {
      if (target.startsWith(DIR)) {
        target = target.substring(3);
      }
      if (parent != null) {
        target = parent + target;
      }
      this.setTicker(new Ticker(target));
      FileConnection fc = (FileConnection)
          Connector.open(PREFIX + target, Connector.READ);
      if (fc.isDirectory()) {
        super.deleteAll();
        if (goingUp == false) {
          stack.push(target);
        }
        super.append(UP, null);

        Enumeration entries = fc.list();

        while (entries.hasMoreElements()) {
          String entry = (String) entries.nextElement();
          FileConnection fc2 = (FileConnection)
              Connector.open(PREFIX + target + entry,
              Connector.READ);
          if (fc2.isDirectory()) {
            super.append(DIR + entry, null);
          } else if (entry.toLowerCase().endsWith(extension)) {
            super.append(entry, null);
          }
          fc2.close();
        }
        fc.close();
      } else {
        this.listener.fileSelected(fc);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

  private void addRoots() {
    Enumeration roots = FileSystemRegistry.listRoots();
    while (roots.hasMoreElements()) {
      super.append(DIR + roots.nextElement().toString(), null);
    }
  }

}

interface OpenFileListener {
  void fileSelected(FileConnection fc);
}

It was first presented at http://smallandadaptive.blogspot.com.br/2009/08/open-file-dialog.html

A: i find my problem, maybe this is your problem too, i just Use thread in commandAction function and it works. here is the code that changed:
if (c==read) {

        new Thread(new Runnable() {

              public void run() {
                  try {
                      ReadFile(path);
                      } catch (IOException ex) {
                          ex.printStackTrace();
                      }
              }
        }).start();
    }


Q: Is it possible to distinguish cookies with the same name by domain?
*

*User gets cookie named X from site a.com.

*User gets cookie named X from sub.a.com (a subdomain of a.com).

*Both of the cookies X use their respective domains.

Given the assumptions above, can JavaScript identify one cookie X out of the two by using domain info, then update it?


Q: WatchKit see if crown is pressed or screen flipped/tilted I have made an app that uses the AppleWatch.
I want to call NSObject cancelPreviousPerformRequestsWithTarget when the user goes to the home screen, but continue if they put down their wrist
Is there any way I can see the difference in -(void)didDeactivate?
Kim


Q: $.Post() cross-domain request works in chrome console but not in html page request I'm trying to send a $.post() cross-domain request.
This is what I'm doing:
$.post(
    "http://mysite.com/call.aspx/record",
    { Enroll : enroll, Item : item, usu : user, version :
        version, video : flv64String },
    function(data){ console.log(data); return data; },
    "json"
)

This is what I have in the calling Webservice button function.
I'have configured my web.config with
 <add name="Access-Control-Allow-Origin" value="*" />

So, when I click in the webservice caller button, the post is called and nothing happens. But when I paste the same $.post() method in Chrome console and properly change the variables with working values and execute, it works fine!
Now  I'm wondering, why the $.post works in Google Chrome console and in my site doesn't ?
I hope some one could answer me.


Q: Smarty loop count I am new to smarty concepts. I have used section loop in my tpl page to show the user data, in this page i need the section count.
For example:
{section name=i loop=$getFriends start=0 step=1}

{/section}

I need to check the  section count for the array values($getFriends) to display some messages for the users. so please guide me on how to make the section count.

A: To get the total count use {$smarty.section.customer.total}

A: By 'count' do you mean the current index of the loop?
If so you can use this
{section name=customer loop=$custid}
  {$smarty.section.customer.index} id: {$custid[customer]}<br />
{/section}

http://www.smarty.net/docsv2/en/language.function.section.tpl#section.property.index

A: Try {counter} http://www.smarty.net/docsv2/en/language.function.counter.tpl
Exapmle:
{counter start=0 print=false name=bla}
{section name=i loop=$getFriends start=0 step=1}
   {counter}
{/section}

A: {assign var=val value=0}
{section name=i loop=$data}
         {assign var=val value=$val+1}
{/section}


Q: How to extract json api through go to extract stargazers_count of a repo? stargazers_count of https://api.github.com/repos/openebs/openebs using go language by extracting it through json

A: Here is an example (completely neglecting error handling):
request, _ := http.Get("https://api.github.com/repos/openebs/openebs")
defer request.Body.Close()
bytes, _ := ioutil.ReadAll(request.Body)

var apiResponse struct {
    StargazersCount int `json:"stargazers_count"`
}
json.Unmarshal(bytes, &apiResponse)

fmt.Println(apiResponse.StargazersCount)

Playground


Q: EMR spark job from aws-cli I am trying to run an spark job on EMR using the aws cli.
What I want is to have the server startup, run the job, and terminate.
I am able to do it as a two step process (first fire up the server, then run the job), but when I send one command I get an error.
error:
Error: Cannot load main class from JAR file:/home/hadoop/spark/bin/spark-submit
Run with --help for usage help or --verbose for debug output
Command exiting with ret '1'

So it looks like it can't find the jar (or the main class). I have set the master to yarn-cluster so that it should lookup the jars on s3, and I am 100% sure that the classpath of main class is correct.
Command
aws emr create-cluster --name "Test auto run" --release-label emr-5.4.0 \
--applications Name=Spark --ec2-attributes KeyName=key-emr --instance-type m3.xlarge --instance-count 2 \
--log-uri s3://test/emr --steps Type=Spark,Name="Spark Program",ActionOnFailure=CONTINUE,,\
Args=[/home/hadoop/spark/bin/spark-submit,--verbose,--master,yarn-cluster,--class,co.path.test.TestJob,s3://test/test-0.0.1-SNAPSHOT-jar-with-dependencies.jar,\
's3://test/test-messages/1998*','d','s3://test/loaded'] \
--use-default-roles --auto-terminate

The controller says this is being executed:
/usr/lib/hadoop/bin/hadoop jar /var/lib/aws/emr/step-runner/hadoop-jars/command-runner.jar spark-submit
/home/hadoop/spark/bin/spark-submit --verbose --master yarn-cluster --class,co.path.test.TestJob s3://test/test-0.0.1-SNAPSHOT-jar-with-dependencies.jar s3://test/test-messages/1998* d s3://test/loaded

Any ideas what am I messing up?

A: If the EMR step type is Spark which you mentioned on the step API --steps Type=Spark , as you identified on Step's controller logs, EMR will add the spark-submit command and you do not need to pass the  /home/hadoop/spark/bin/spark-submit as arguments of the STEP API.
The error was because of two spark-submit's , where it was taking the second one /home/hadoop/spark/bin/spark-submit as argument.
Please see : http://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-submit-step.html


Q: Django Filter timestamp data GROUP BY day, week, month, year I have an django(DRF) app in which I storing periodic timeseries data based on API response. Here is my
model.py
# Model to store the Alexa API Data
class Alexa(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    extra = jsonfield.JSONField(null=True)
    rank =  models.PositiveIntegerField(default=0, null=True)

I am using django-filters to query data based on a range (__lte, __gte).
Like /api/alexa/?created_at__lte=2020-02-14T09:15:52.329641Z return all the data created before 2020-02-14T09:15:52.329641Z
[
    {
        "id": 1,
        "created_at": "2020-02-03T19:30:57.868588Z",
        "extra": "{'load_time': 00, 'backlink': 0}",
        "rank": 0
    },
    ...
 ]

Is there a way to build an endpoint to return aggregated data grouped by day, week, month and year based on the query params I pass. For example,
/api/alexa/?created_at__lte=2020-02-14T09:15:52.329641Z&group_by=month would return
[
    {
        "created_at": "2020-01-01T00:00:00.000000Z",
        "extra": "{'load_time': 00, 'backlink': 0}", <- Aggregated Data
        "rank": 0                                    <- Aggregated Data
    },
    {
        "created_at": "2020-02-01T00:00:00.000000Z",
        "extra": "{'load_time': 00, 'backlink': 0}", <- Aggregated Data
        "rank": 0                                    <- Aggregated Data
    },
 ]

Here's my current views.py
class AlexaViewSet(viewsets.ModelViewSet):
    queryset = Alexa.objects.all()
    filter_fields = {'created_at' : ['iexact', 'lte', 'gte']}
    http_method_names = ['get', 'post', 'head']

I have seen several snippets doing aggregation but none completely fulfilling my requirements nor giving me a complete idea about the topic.
I am new to Django and building analytics dashboards in general, if there are any other way of representing such timeseries data for consumption in front-end graphs, I would appreciate your suggestions to that as well.
EDIT :
Here is my serializer.py
class AlexaSerializer(serializers.ModelSerializer):
     class Meta:
         model = Alexa
         fields = '__all__'

A: First of all, the class AlexaViewSet is not a serializer but a ViewSet. You didn't specify the serializer class on that ViewSet so I you need to specify that.
On the other side, if you want to pass a custom query param on the URL then you should override the list method of this ViewSet and parse the query string passed in the request object to retrieve the value of group_by, validate it, and then perfom the aggregation youself.
Another problem that I see is that you also need to define what is to aggregate a JSON field, which is not supported in SQL and it's very relative, so you may want to consider redesigning how you store the information of this JSON field if you want to perfom aggregations on fields inside it. I would suggest extracting the fields you want to aggregate from the JSON (when storing them in the database) and put them in a SQL column separately so you could perform aggregations later.
The client could also pass the agregation operation as a query parameter, for example aggregation=sum or aggregation=avg.
In a simple case, where you just need the average of the ranks this should be useful as an example (you could add TruncQuarter, etc.):
class AlexaViewSet(viewsets.ModelViewSet):
    serializer_class = AlexaSerializer
    queryset = Alexa.objects.all()
    filter_fields = {'created_at': ['iexact', 'lte', 'gte']}
    http_method_names = ['get', 'post', 'head']

    GROUP_CASTING_MAP = {  # Used for outputing the reset datetime when grouping
        'day': Cast(TruncDate('created_at'), output_field=DateTimeField()),
        'month': Cast(TruncMonth('created_at'), output_field=DateTimeField()),
        'week': Cast(TruncWeek('created_at'), output_field=DateTimeField()),
        'year': Cast(TruncYear('created_at'), output_field=DateTimeField()),
    }

    GROUP_ANNOTATIONS_MAP = {  # Defines the fields used for grouping
        'day': {
            'day': TruncDay('created_at'),
            'month': TruncMonth('created_at'),
            'year': TruncYear('created_at'),
        },
        'week': {
            'week': TruncWeek('created_at')
        },
        'month': {
            'month': TruncMonth('created_at'),
            'year': TruncYear('created_at'),
        },
        'year': {
            'year': TruncYear('created_at'),
        },
    }

    def list(self, request, *args, **kwargs):
        group_by_field = request.GET.get('group_by', None)
        if group_by_field and group_by_field not in self.GROUP_CASTING_MAP.keys():  # validate possible values
            return Response(status=status.HTTP_400_BAD_REQUEST)

        queryset = self.filter_queryset(self.get_queryset())

        if group_by_field:
            queryset = queryset.annotate(**self.GROUP_ANNOTATIONS_MAP[group_by_field]) \
                .values(*self.GROUP_ANNOTATIONS_MAP[group_by_field]) \
                .annotate(rank=Avg('rank'), created_at=self.GROUP_CASTING_MAP[group_by_field]) \
                .values('rank', 'created_at')

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

For these values:
GET /alexa
[
    {
        "id": 1,
        "created_at": "2020-03-16T12:04:59.096098Z",
        "extra": "{}",
        "rank": 2
    },
    {
        "id": 2,
        "created_at": "2020-02-15T12:05:01.907920Z",
        "extra": "{}",
        "rank": 64
    },
    {
        "id": 3,
        "created_at": "2020-02-15T12:05:03.890150Z",
        "extra": "{}",
        "rank": 232
    },
    {
        "id": 4,
        "created_at": "2020-02-15T12:05:06.357748Z",
        "extra": "{}",
        "rank": 12
    }
]

GET /alexa/?group_by=day
[
    {
        "created_at": "2020-02-15T00:00:00Z",
        "extra": null,
        "rank": 102
    },
    {
        "created_at": "2020-03-16T00:00:00Z",
        "extra": null,
        "rank": 2
    }
]

GET /alexa/?group_by=week
[
    {
        "created_at": "2020-02-10T00:00:00Z",
        "extra": null,
        "rank": 102
    },
    {
        "created_at": "2020-03-16T00:00:00Z",
        "extra": null,
        "rank": 2
    }
]

GET /alexa/?group_by=month
[
    {
        "created_at": "2020-02-01T00:00:00Z",
        "extra": null,
        "rank": 102
    },
    {
        "created_at": "2020-03-01T00:00:00Z",
        "extra": null,
        "rank": 2
    }
]

GET /alexa/?group_by=year
[
    {
        "created_at": "2020-01-01T00:00:00Z",
        "extra": null,
        "rank": 77
    }
]


Q: What is the fastest way to compare two strings in C? For clarity I'm only talking about null terminated strings.
I'm familiar with the standard way of doing string comparisons in C with the usage of strcmp. But I feel like it's slow and inefficient.
I'm not necessarily looking for the easiest method but the most efficient.
Can the current comparison method (strcmp) be optimized further while the underlying code remains cross platform?
If strcmp can't be optimized further, what is the fastest way which I could perform the string comparison without strcmp?
Current use case:

*

*Determine if two arbitrary strings match

*Strings will not exceed 4096 bytes, nor be less than 1 byte in size

*Strings are allocated/deallocated and compared within the same code/library

*Once comparison is complete I do pass the string to another C library which needs the format to be in a standard null terminated format

*System memory limits are not a huge concern, but I will have tens of thousands of such strings queued up for comparison

*Strings may contain high-ascii character set or UTF-8 characters but for my purposes I only need to know if they match, content is not a concern

*Application runs on x86 but should also run on x64

Reference to current strcmp() implementation:

*

*How does strcmp work?

*What does strcmp actually do?

*GLIBC strcmp() source code
Edit: Clarified the solution does not need to be a modification of strcmp.
Edit 2: Added specific examples for this use case.

A: I'm afraid your reference imlementation for strcmp() is both inaccurate and irrelevant:

*

*it is inaccurate because it compares characters using the char type instead of the unsigned char type as specified in the C11 Standard:

7.24.4 Comparison functions
The sign of a nonzero value returned by the comparison functions memcmp, strcmp, and strncmp is determined by the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char) that differ in the objects being compared.

*It is irrelevant because the actual implementation used by modern compilers is much more sophisticated, expanded inline using hand-coded assembly language.
Any generic implementation is likely to be less optimal, especially if coded to remain portable across platforms.
Here are a few directions to explore if your program's bottleneck is comparing strings.

*

*Analyze your algorithms, try and find ways to reduce the number of comparisons: for example if you search for a string in an array, sorting that array and using a binary search with drastically reduce the number of comparisons.

*If your strings are tokens used in many different places, allocate unique copies of these tokens and use those as scalar values.  The strings will be equal if and only if the pointers are equal. I use this trick in compilers and interpreters all the time with a hash table.

*If your strings have the same known length, you can use memcmp() instead of strcmp(). memcmp() is simpler than strcmp() and can be implemented even more efficiently in places where the strings are known to be properly aligned.

EDIT: with the extra information provided, you could use a structure like this for your strings:
typedef struct string_t {
    size_t len;
    size_t hash;  // optional
    char str[];   // flexible array, use [1] for pre-c99 compilers
} string_t;

You allocate this structure this way:
string_t *create_str(const char *s) {
    size_t len = strlen(s);
    string_t *str = malloc(sizeof(*str) + len + 1;
    str->len = len;
    str->hash = hash_str(s, len);
    memcpy(str->str, s, len + 1);
    return str;
}

If you can use these str things for all your strings, you can greatly improve the efficiency of the matching by first comparing the lengths or the hashes.  You can still pass the str member to your library function, it is properly null terminated.


Q: Unlocking the condition variable mutex twice? I'm looking at the following snippets:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cvar;
char buf[25];
void*thread_f(void *);

int main(){

    pthread_t thr;
    pthread_cond_init(&cvar,NULL);
    pthread_mutex_lock(&mtx);
    pthread_create(&thr,NULL,thread_f,NULL);
    pthread_cond_wait(&cvar,&mtx);
    pthread_mutex_unlock(&mtx);
    ...join and destroy thread...
}

and thread_f:
void* thread_f(void* argp){

    pthread_mutex_lock(&mtx);
    strcpy(buf,"test");
    pthread_cond_signal(&cvar);
    pthread_mutex_unlock(&mtx); //why?
    pthread_exit(NULL);
}

My understanding of the above code is, that main grabs the lock, creates the thread and runs thread_f which blocks. Then, main signals the wait on the condition variable cvar and unlocks the mutex. Then, thread_f unblocks, strcpys and signals cvar to wake up. Then, both main and thread_f unlock the mutex.
Is this the actual behaviour, or am I missing something somewhere? If it's the actual behaviour, isn't unlocking the already unlocked mutex UB, therefore should one of he mutex unlocks in the end be removed?
Thanks.

A: The pthread_cond_wait() in the main thread unlocks the mutex and waits for the condition to be signalled — and relocks the mutex before returning.
The child thread is able to lock the mutex, manipulate the buffer, signal the condition and then unlock the mutex, letting the main thread reacquire the lock.
Consequently, the code is well-behaved — give or take the need to worry about 'spurious wakeups' in more general situations with multiple child threads.  I don't think you can get a spurious wakeup here.

A: What this code is doing is valid.
When the thread calls pthread_cond_signal it doesn't immediately cause the main thread to grab the mutex, but wakes up the main thread so it can attempt to lock it.  Then once the thread releases the mutex, the main thread is able to lock it and return from pthread_cond_wait.


Q: bash if variable set by function I have limited experience with BASH and I am looking for some guidance about how to proceed so please bear with me.
I am trying to change the command prompt when I am inside a git repo, which I can do using this post I found on google, but I also would like to add color depending on the current state of the repo (clean, untracked files, modified files).
Currently I have this at the end of my .bashrc file:
parse_git_branch () {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/[\1]/'
}

modified () {
  git status 2> /dev/null | grep -q modified
}

untracked () {
  git status 2> /dev/null | grep -q Untracked
}

clean () {
  git status 2> /dev/null | grep -q clean
}

NO_COLOR="\[\033[0m\]"
GREEN="\[\033[0;32m\]"
YELLOW="\[\033[0;33m\]"
RED="\[\033[0;31m\]"

set_color () {

  if untracked ; then
    echo $RED
  elif modified ; then
    echo $YELLOW
  elif clean ; then
    echo $GREEN
  else
    echo $NO_COLOR
  fi
}

PS1="\u:\w\$(set_color)\$(parse_git_branch)$NO_COLOR> "

The command prompt changes but does not change the color like I think it should.
Here is what I get instead:
outside git repo arod:~\[\033[0m\]>
inside a git repo arod:~/tos\[\033[0;32m\][dev]>
I am unsure how to get the color to evaluate I think, just looking for some guidance from someone with more BASH experience than I have.

A: If anyone is looking for an answer; or at least the solution that I used:
parse_git_branch () {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/[\1]/'
}

modified () {
  git status 2> /dev/null | grep -q modified
}

untracked () {
  git status 2> /dev/null | grep -q Untracked
}

clean () {
  git status 2> /dev/null | grep -q clean
}

NO_COLOR="\033[0m"
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
RED="\033[0;31m"

set_color () {

  if untracked ; then
    echo -e $RED
  elif modified ; then
    echo -e $YELLOW
  elif clean ; then
    echo -e $GREEN
  else
    echo -e $NO_COLOR
  fi
}

PS1="\u:\w\$(set_color)\$(parse_git_branch)$NO_COLOR> "

The main difference between the code in the question and this one is that I did add the -e flag to echo, and removed the \'s from the color variables.
Hope this helps someone
EDIT
After receiving a bit more feedback, here is what this looks like now:
parse_git_branch () {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/[\1]/'
}

no_color="\033[0m"
green="\033[0;32m"
yellow="\033[0;33m"
red="\033[0;31m"

set_color () {

  case "$(git status 2> /dev/null)" in
    *Untracked*)
      printf '%b' "$red";;
    *modified*)
      printf '%b' "$yellow";;
    *clean*)
      printf '%b' "$green";;
    *)
      printf '%b' "$no_color";;
  esac

}

PS1="\u:\w\$(set_color)\$(parse_git_branch)$no_color> "

All of this came from @Charles Duffy.
The only thing I did not incorporate was using tput to get the color escape sequences.


Q: Oracle: how to check either two polygon are overlapping or not I have measured a land area (plot) and captured its 4 corner's GPS co-ordinates using a GPS device.
Now I have two Questions

*

*How to save this is Oracle Database.
(it seems answer of first point. is it?)

*After saving it I wanna check whether any plot is overlapping
(partially or full) to another existing plot in database or not?

A: I got very helpful comments by Rene and Ben.
and based on i have solved my issues..
    ---------------------------  CREATING TABLE --------------------------

create table tbl_location(
id int constraint id_pk primary key,
unit_code char(2) not null,
plot_id number(15) not null,
season_cntrl number(2),
Ryot_code varchar2(9),
share_or_perc_val number(2) not null,
plot_no varchar2(18) not null,
total_area decimal(5,5),
a1 varchar2(15),
b1 varchar2(15),
a2 varchar2(15),
b2 varchar2(15),
a3 varchar2(15),
b3 varchar2(15),
a4 varchar2(15),
b4 varchar2(15),
location sdo_geometry
);

--------------------------- CREATING SEQUENCE FOR ID ---------------------------
create sequence location_sequence
start with 1
increment by 1
nocache
nocycle;
/

--- createing a trigger for auto-incrementation of ID ------------------------------
Create or replace trigger id_increment
before insert on tbl_location
for each row
begin
select location_sequence.nextval into :new.id from dual;
end;

for column location data
update tbl_location set location =  SDO_GEOMETRY(2003,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( '80.16181','27.8682866666666','80.1616516666666','27.8681266666666','80.161215','27.867975','80.1613933333333','27.8685933333333','80.16181','27.8682866666666' )) where id =2;
update tbl_location set location =  SDO_GEOMETRY(2003,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( '80.1538483333333','27.88376','80.15354','27.8841166666666','80.1529499999999','27.8834933333333','80.1532','27.8832566666666','80.1538483333333','27.88376' )) where id =3;

To get plots (polygon) which are intersecting each other
select a.id as id1, b.id as id2,a.unit_code, a.ryot_code,a.share_or_perc_val,
sdo_geom.sdo_intersection(a.location, b.location, 0.005) location,
a.plot_no, a.total_area
from tbl_location a
Inner Join tbl_location b on
a.id < b.id and sdo_geom.sdo_intersection(a.location, b.location,0.005) is not null  ;

A: Well, you can just call the SDO_GEOM.SDO_AREA() on the result of the SDO_GEOM.SDO_INTERSECTION() function.
However that will not give you meaningful results: your geometries are (so it seems) in geodetic WGS84 coordinates (i.e. in decimal degrees), but you load them without specifying any coordinate system. As a result, any area calculation will return a result in square degrees, a meaningless and unusable result.
You should load your two geometries like this:
update tbl_location set location =  SDO_GEOMETRY(2003,4326,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( 80.16181,27.8682866666666,80.1616516666666,27.8681266666666,80.161215,27.867975,80.1613933333333,27.8685933333333,80.16181,27.8682866666666 )) where id =2;
update tbl_location set location =  SDO_GEOMETRY(2003,4326,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( 80.1538483333333,27.88376,80.15354,27.8841166666666,80.1529499999999,27.8834933333333,80.1532,27.8832566666666,80.1538483333333,27.88376 )) where id =3;

Finally your approach only works because you only play with two geometries. As soon as you start dealing with real data, the query will perform very badly: it requires computing the intersection between each shape and all the others. For a set of 10,000 shapes, that means 100,000,000 computations (well actually 99,990,000 since you avoid intersecting a geometry with itself).
The proper approach is to detect the shapes that intersect by taking advantage of spatial indexing. The appropriate approach is to use the SDO_JOIN() procedure for that.

A: There is a much more simple way to do that.
Your Problem seems to use the SDO_GEOM.RELATE function.
This function Returns the relationship between two or more Polygons.
In the following example all relations to the other polygons in your table are shown to the polygon with the 1
SELECT c.id,
SDO_GEOM.RELATE(c.polygon, 'determine', c_b.polygon, 0.005) relationship
FROM my_polygon_table c, my_polygon_talbe c_b WHERE c_b.id = 1;

The result is one of the opsibile relationships:
ANYINTERACT; CONTAINS; COVEREDBY; COVERS; DISJOINT; EQUAL; INSIDE; ON; OVERLAPBDYDISJOINT; OVERLAPBDYINTERSECT; TOUCH;
Care also about the Right Keyword:
If you pass the DETERMINE keyword in mask, the function returns the one relationship keyword that best matches the geometries.
If you pass the ANYINTERACT keyword in mask, the function returns TRUE if the two geometries are not disjoint.


Q: javascript find matching variables between two nested arrays I have two nested arrays.
arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]]
arr2 = [["image1","blue"],["image2","red"]]

The desired output is : If the image names (image) match, I want to return the color from the second array to a variable.
I have tried using two for loops:
var color = for (var i = 0; i < arr1.length; i++ ) {
for (var j = 0; j < arr2.length; j++ ) {
if (arr1[i][0] === arr2[j][0]) {
return arr2[j][1]
}
}

Since this is a larger part of a program, The first loop gets executed much before the second loop...however both are nested into each other in the order that I have specified.....I am trying to using the variable to color some html elements, but my entire program gets halted.  I am not sure if my approach is right.

A: Feels like you're trying to use the second array as a lookup into the first. Here's a way to do this by transforming it into an object:
 function toLookupTable(shirtColors) {

     //keys will be image names, values will be colors
     const lookupTable = {};

     shirtColors.forEach(shirtColor => {
         //use array destructuring
         const [ image, color ] = shirtColor;
         lookupTable[image] = color;
     });
     return lookupTable;
 }

 const colorLookup = toLookupTable( [["image1","blue"],["image2","red"]] );

 console.log(colorLookup["image2"]); //outputs "red"

A: Use Array#reduce and Array#findIndex

I want to return the color from the second array to a variable.

const arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]]
const arr2 = [["image1", "blue"],["image2","red"]]

const res = arr2.reduce((a,[image,color])=>{
   if(arr1.findIndex(([n])=>n===image) > -1) a.push(color);
   return a;
}, []);

console.log(res);

A: You can use reduce

let arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]];
let arr2 = [["image1","blue"],["image2","red"]];

let op = arr1.reduce((out,inp,index)=>{
  if(arr2[index].includes(inp[0])){
    out.push(arr2[index][1])
  }
  return out
},[] )

console.log(op)


Q: Windows screensaver from HTML/JS I've an html page without any external includes with some inline CSS3 animations and JS timers.
Is it possible to convert a simple html file to a screensaver file, which can be further used as a screensaver on my windows and mac desktops?
I mean a real screensaver, which boots once desktop goes to a sleep mode, not the one that  works in the browser.
I know there're some tools available to export swf as a screensaver file, are there any tools available for exporting the HTML? At least, for Windows 8.
Any ideas are respected.


Q: Checkboxes not working in WiX generated windows installer I've used WiXEdit in conjunction with Wix to reverse engineer an MSI installation in order to move my main solution up to VS2013 from VS2010.
The error Im getting is that when the MSI is run, the checkboxes and text box I've placed in a dialog act as if they're disabled. I need the checkboxes as in my main application they allow the user to select a feature set.
I've generated a simple solution that demonstrates the same error.
The solution has 2(3) projects, windowsformsapplication12 will always be installed, windowsformsapplication1 will only be installed if conditional CHECKBOX1A=1 (SetupProject2 is the wix project and the wix script is found here as setup1.wxs)
(Wix toolkit is necessary to be installed into visual studio to compile the Wix setup project if necessary, but if somebody with installer expertise checks the script setup1.wxs they may see what's wrong with it.)
NB
On attempting to compile the reverse engineered file, I received error message "Error 5 The Control element must have a value for exactly one of the Property or CheckBoxPropertyRef attributes." on lines 491,492,493,494. So I added Property="CHECKBOXA1" (or as appropriate) to the end of the control descriptor xml as can be seen if you unrar the source.
I assume I'm missing adding extra code elsewhere or I assume it would work.
This is the first time I've ever encountered a Wix script and the source code doesn't really resemble Wix tutorial code I've seen so I've not been able to debug it.

A: Converting VS2010 setup project to a Wix script
Please find instructions for anybody else who'd find it useful
1) Install WixToolkit and WixEdit
2) Build VS2010 setup project
3) Create new Wix project within the solution.
4) Remove the default product.wxs file from the Wix project
5) Copy the setup MSI file to the root directory of the Wix project
6) Run WixEdit application
7) Open the setup MSI file in WixEdit
(This should generate files and directories)
7) Add directories and files generated by WixEdit to the Wix project
8) Compile Wix Setup Project and fix errors
9) Delete the original msi file from the wix project
Re Check boxes not working
"Error 5 The Control element must have a value for exactly one of the Property or CheckBoxPropertyRef attributes"
Go to the error line in the script
<Control Id="Checkbox1" Type="CheckBox" X="18" Y="108" Width="348" Height="12" Text="{\VSI_MS_Shell_Dlg13.0_0_0}Install Main Application" TabSkip="no"/>

Change it so it reads (or appropriate changes)
<Control Id="Checkbox1" Type="CheckBox" X="18" Y="108" Width="348" Height="12" Text="{\VSI_MS_Shell_Dlg13.0_0_0}Install Main Application" TabSkip="no" Property="CHECKBOXA1" CheckBoxValue="1" />

CheckBoxValue="1" was the missing attribute that caused my checkboxes to be disabled


Q: Android Annotations @AfterViews called 3 times I'm using Android Annotations and my method annotated with @AfterViews is called 3 times. I debugged the generated class and i figure that these 3 methods are invoked but i dont know why.
@Override
public void setContentView(int layoutResID) {
    super.setContentView(layoutResID);
    afterSetContentView_();
}

@Override
public void setContentView(View view, LayoutParams params) {
    super.setContentView(view, params);
    afterSetContentView_();
}

@Override
public void setContentView(View view) {
    super.setContentView(view);
    afterSetContentView_();
}

-- edit 1 --
My activity declaration is the only place where I set a layout:
@EActivity(R.layout.real_estate_customer_leads_list)
public class RealEstateCustomerLeadsListActivity extends
    SlidingFragmentActivity implements FilterResponseHandler {

}

A: that's probably because one super is calling the other. Something like this:
 // super.setContentView(layoutResID); code is:
 View v = LayoutInflater.from(getContext()).inflate(layoutResId);
 setContentView(v);

// then super.setContentView(view); code is:
setContentView(view, null);

// then super.setContentView(view, params);
this one now actually do real work. Hence, 3 calls!


Q: sort values a data frame with duplicates values I have a dataframe with a format like this:
d = {'col1': ['PC', 'PO', 'PC', 'XY', 'XY', 'AB', 'AB', 'PC', 'PO'], 'col2':
[1,2,3,4,5,6,7,8,9]}
df = pd.DataFrame(data=d)

df.sort_values(by = 'col1')

This gives me the result like this:

I want to sort the values based on col1 values with desired order, keep the duplicates. The result I expect would be like this:

Any idea?
Thanks in advance!

A: You can create an order beforehand and then sort values as below.
order = ['PO','XY','AB','PC']
df['col1'] = pd.CategoricalIndex(df['col1'], ordered=True, categories=order)

df = df.sort_values(by = 'col1')
df

    col1    col2
1   PO      2
8   PO      9
3   XY      4
4   XY      5
5   AB      6
6   AB      7
0   PC      1
2   PC      3
7   PC      8


Q: arduino yun to parse.com starter project not working I'm trying to run the arduino starter project from parse.com and like other people i have found the object id blank Parse.com Arduino Yun SDK Quickstart tutorial not working
in the serial monitor i get this response
Parse Starter Project
Response for saving a TestObject:
Test object id:
However i've tried everything i can think of, updated the bridge library, tried various different versions of the IDE and of the bridge library. I'm running windows. I've tried 1.6.1, 1.6.3, 1.6.5 and i've tried several versions of the bridge library. I'm at a loss. Anyone else encountered this issue and have an ideas?

A: So i managed to fix it!
The issue was with the embedded SDK. If anyone struggles with the same probelm here are the steps i took:

*

*Download WinSCP.

*Connect to the arduino using SSH in WinSCP (username root)

*copy across the two embedded parse.com arduino files (make sure they are in the correct root folder

*Download PuTTY and use this to open the arduino command line

*call opkg install *.ipk to install the SDK files

That seems to have sorted the problem, they weren't installed properly before


Q: Invoking a controller method without having a route defined for it I have several routes, and do not want to add another due to the difficulty in setting permissions, etc. I have a controller method, which isn't invoked on any route. Is there any way I can do this in my blade template?
My controller method is as follows:
public static function editROA(){
//do stuff
}

and in my blade template, I would like to refer this:
Edit

However, this throws an error, and says that there is no method named editROA. Is there any solution to this problem?

A: Since you cannot have more than five routes, I would suggest you use only one wild-carded route. So you run an if else on the wild card to call the appropriate method.
Route::get('{uri?}',function($uri){
    if($uri == "/edit")
    {
        return app()->call('App\Http\Controllers\HomeController@editROA');
    }else if($uri == "something else"){
        return app()->call('App\Http\Controllers\SomeController@someMethod');
    }
    // add statements for other routes
});

view
Edit


Q: How to prevent a page from resubmitting? in grails 2.2.0 When once form is submitted successfully....
but When I click on "BACK" button and trying submit same form
its gives me an error
Source:
<g:form action="addData" name="addValues" controller="emp" method="Post">
</g:form>

Controller Source:-
def editProfile (Long id,Long version){
        withForm {
        // code
            }.invalidToken {
            response.status = 405

        }
    }

A: Its hard to infer the cause of the error with what you have posted. However, you asked about how to prevent a page from resubmitting in Grails. Take a look at documentation. Grails has a build in support for that.
Basically you define a form with a token and using withForm you will check if the token still is valid or not.
<g:form useToken="true" ...>

/
withForm {
   // good request
}.invalidToken {
   // bad request
}


Q: Backbone Undefined is not a function error I'm learning backbone and I'm trying to execute this sample code to get the feel.

http://backbonetutorials.com/what-is-a-view/

My code:
  <!DOCTYPE html>
  <html>
  <head>
    <meta charset="utf-8">
    <title>hello-backbonejs</title>
  </head>
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
    <script src="http://backbonejs.org/backbone.js"></script>
    <script type="text/javascript">
Rocky = Backbone.Model.extend({
  initialize: function(){
    console.log('hello world');
  }
});
</script>
  </body>
  </html>

I get this error.
Uncaught type error: Undefined is not a function!
What did I do wrong? I was just trying to print and see if it's printed on my console!
Thanks,
R

A: Your underscore.js version is too old. Try to use the new version (1.7):
<script src="http://underscorejs.org/underscore.js"></script>


Q: Why is infinite loop needed when using threading and a queue in Python I'm trying to understand how to use threading and I came across this nice example at http://www.ibm.com/developerworks/aix/library/au-threadingpython/
      #!/usr/bin/env python
      import Queue
      import threading
      import urllib2
      import time

      hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
      "http://ibm.com", "http://apple.com"]

      queue = Queue.Queue()

      class ThreadUrl(threading.Thread):
      """Threaded Url Grab"""
        def __init__(self, queue):
          threading.Thread.__init__(self)
          self.queue = queue

        def run(self):
          while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and prints first 1024 bytes of page
            url = urllib2.urlopen(host)
            print url.read(1024)

            #signals to queue job is done
            self.queue.task_done()

      start = time.time()
      def main():

        #spawn a pool of threads, and pass them queue instance
        for i in range(5):
          t = ThreadUrl(queue)
          t.setDaemon(True)
          t.start()

       #populate queue with data
          for host in hosts:
            queue.put(host)

       #wait on the queue until everything has been processed
       queue.join()

      main()
      print "Elapsed Time: %s" % (time.time() - start)

The part I don't understand is why the run method has an infinite loop:
        def run(self):
          while True:
            ... etc ...

Just for laughs I ran the program without the loop and it looks like it runs fine!
So can someone explain why this loop is needed?
Also how is the loop exited as there is no break statement?

A: Do you want the thread to perform more than one job?  If not, you don't need the loop.  If so, you need something that's going to make it do that.  A loop is a common solution.  Your sample data contains five job, and the program starts five threads.  So you don't need any thread to do more than one job here.  Try adding one more URL to your workload, though, and see what changes.

A: The loop is required as without it each worker thread terminates as soon as it completes its first task. What you want is to have the worker take another task when it finishes.
In the code above, you create 5 worker threads, which just happens to be sufficient to cover the 5 URL's you are working with. If you had >5 URL's you would find only the first 5 were processed.


Q: Azure Function ignoring https.request I have an azure function with this line of code.

var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();

But my code seems to just skip this part of code, with no errors. I am new to Azure and node.js so I might have missed some basic parts in setting this up.
Any ideas?
Edit:
Here is my full code

const https = require('https');
const querystring = require('querystring');

module.exports = async function (context, req) {

    if (req.query.accessCode || (req.body && req.body.accessCode)) {
        context.log('JavaScript HTTP trigger function processed a request.');
        var options = {
            host: 'httpbin.org',
            port: 80,
            path: '/post',
            method: 'POST'
        };

        var postData = querystring.stringify({
            client_id : '1234',
            client_secret: 'xyz',
            code: req.query.accessCode
        });

        var body = "";
        var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();
        context.log("help");
        context.res = {
            status: 200,
            body: "Hello " + (body)
        };
    } else {
       context.res = {
            status: 400,
           body: "Please pass a name on the query string or in the request body"
      };
    }
};

A: Ideally it should work. You can also try using request module like below
const request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.error('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

Try and see if it helps.

A: Solved by doing await properly. Used this as guide.

var https = require('https');
var util = require('util');
const querystring = require('querystring');
var request = require('request')

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    /*if (req.query.name || (req.body && req.body.name)) {*/
    var getOptions = {
        contentType: 'application/json',
        headers: {
            'Authorization': <bearer_token>
         },
    };
    var postData = {
        "key": "value"
    };
    var postOptions = {
        method: 'post',
        body: postData,
        json: true,
        url: <post_url>,
        headers: {
            'Authorization': <bearer_token>
         },
    };
    try{
        var httpPost = await HttpPostFunction(context, postOptions);
        var httpGet = await HttpGetFunction(context, <get_url>, getOptions);
        return {
            res: httpPost
        };
    }catch(err){
       //handle errr
       console.log(err);
    };
};

async function HttpPostFunction(context, options) {
    context.log("Starting HTTP Post Call");
    return new Promise((resolve, reject) => {
        var data = '';
        request(options, function (err, res, body) {
            if (err) {
              console.error('error posting json: ', err)
              reject(err)
            }
            var headers = res.headers;
            var statusCode = res.statusCode;
            //context.log('headers: ', headers);
            //context.log('statusCode: ', statusCode);
            //context.log('body: ', body);
            resolve(body);
          })
    });
};

async function HttpGetFunction(context, url, options) {
    context.log("Starting HTTP Get Call");
    return new Promise((resolve, reject) => {
        var data = '';
        https.get(url, options, (resp) => {
            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            })
            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(JSON.parse(data));
            });
        }).on("error", (err) => {
            console.log("Error: " + err.message);
            reject(err.message);
        });
    });
};


Q: How to run regasm.exe from a C++ program (.NET 4) I need to register a .NET COM dll from a C++ program that is using it. For .NET versions older then .NET 4 this is explained in How to run regasm.exe from a C++ program?. Following is the minimal code (no checks) that provides the path to an older version of the CLR.
CComBSTR mscoreeName("mscoree.dll");
HINSTANCE hMscoree = CoLoadLibrary(mscoreeName, FALSE);
typedef HRESULT (WINAPI *LPFNGETCORSYSDIR)(LPWSTR, DWORD, DWORD*);
LPFNGETCORSYSDIR lpfunc = (LPFNGETCORSYSDIR)GetProcAddress(hMscoree,_T("GetCORSystemDirectory"));

DWORD bufferSize = 256;
DWORD bufferUsed;
LPWSTR pwzBuffer = new WCHAR[bufferSize];
(*lpfunc)(pwzBuffer, bufferSize, &bufferUsed);

However since I use .NET 4 the method GetCORSystemDirectory is superseded by the ICLRRuntimeInfo::GetRuntimeDirectory which is not an entry point in mscoree.dll (checked with depends). According the documentation on MSDN the method is included as a resource in MSCorEE.dll.
Question is how to get access to this method from C++?
Besides that I'm wondering if there is no easier way...

A: The problem with the way of working in the question is in finding the correct location of RegAsm. Thanks to the comment of Hans Passant to use RegistrationService.RegisterAssembly I changed the ClassLibrary into a self-registering executable.
static void Main(string[] args)
{
    if (args.Length != 1)
    {
        ShowHelpMessage();
        return;
    }

    if (args[0].CompareTo("/register") == 0)
    {
        Assembly currAssembly = Assembly.GetExecutingAssembly();
        var rs = new RegistrationServices();
        if (rs.RegisterAssembly(currAssembly, AssemblyRegistrationFlags.SetCodeBase))
        {
            Console.WriteLine("Succesfully registered " + currAssembly.GetName());
        } else
        {
            Console.WriteLine("Failed to register " + currAssembly.GetName());
        }
        return;
    }

    if (args[0].CompareTo("/remove") == 0)
    {
        Assembly currAssembly = Assembly.GetExecutingAssembly();
        var rs = new RegistrationServices();
        if (rs.UnregisterAssembly(currAssembly))
        {
            Console.WriteLine("Succesfully removed " + currAssembly.GetName());
        }
        else
        {
            Console.WriteLine("Failed to remove " + currAssembly.GetName());
        }
        return;
    }

    ShowHelpMessage();
}


Q: Unable to understand where argv[1] and arg [2] command are pointing in this program Here is someone's program, which i need for my project to collect data. I'm unable to understand where is the command #define IMAGE argv[1] #define IFS argv[2] pointing to and what are the values being defined in the IMAGE and IFS. These two command are necessary as they are later on required to for reading a file name.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <alloc.h>

#define IMAGE argv[1]
#define IFS argv[2]

get_image(FILE *ifs_file, unsigned int *assumed_width_of_image, unsigned int
*assumed_height_of_image, unsigned int *width_of_image, unsigned int *height_of_image, char *argv[]);

unsigned int *image;

main(int argc, char *argv[])
{
unsigned char dom[4][4], d1[4][4], ran[8][8], lowest_error, sym, bestsym,         domain_whites,range_whites;
unsigned int assumed_width_of_image, assumed_height_of_image, width_of_image,
    height_of_image;
unsigned long int count, domx, domy, ranx, rany, bestranx;
time_t start_time;
FILE *ifs_file;

start_time = time(NULL);
if (argc != 3) {
    printf("\nUse the following format:\n\ncompress [image_file] [ifs_file]\n\n");
    exit
}
if ((ifs_file = fopen(IFS, "wb")) == NULL) {
    fprintf(stderr, "\nError opening file %s\n", IFS);
    exit(1);
}
get_image(ifs_file, &assumed_width_of_image, &assumed_height_of_image,   &width_of_image, &height_of_image, argv);

    get_image(FILE *ifs_file, unsigned int *assumed_width_of_image, unsigned int
   *assumed_height_of_image, unsigned int *width_of_image, unsigned int *height_of_image,    char *argv[])
   {
 FILE *image_file;
unsigned int buf[24], *header, size_of_header, extra_height;
unsigned long size_of_file, size_of_image;

if ((image_file = fopen(IMAGE, "rb")) == NULL) {
    fprintf(stderr, "\nCannot open file %s\n", IMAGE);
    exit(1);
}
if (fread(buf, sizeof(unsigned int), 24, image_file) != 24) {
    fprintf(stderr, "\nError reading file %s\n", IMAGE);
    exit(1);
}
if (buf[0] != 19778) {
    printf("%s is not a .BMP file", IMAGE);
    exit(0);
}
if (buf[23] != 2) {
    printf("%s is not a black and white image", IMAGE);
    exit(0);
}

A: argc and argv refer to command line inputs. When the program is run they are specified by the user.
myprogram.exe --input1 fred
See this: What does int argc, char *argv[] mean?


Q: How get list of days in a week that exist in some date range (Javascript) Hello I need to define existing days in some date range.
I don't wont to make loop from start to end dates and use like here http://www.w3schools.com/jsref/jsref_getday.asp
Is it possible to calculate it some how ?

A: function getDays(earlierDate, laterDate) {
  var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
  var elapsedDays = (laterDate - earlierDate) / 1000 / 60 / 60 / 24;
  if (elapsedDays < 7) {
    var dayArray = [];
    for (i = 0; i <= elapsedDays; i++) {
        dayArray.push(dayNames[(earlierDate.getDay()+i) % 7]);
    }
    return dayArray;
  }
  return dayNames;
}

And testing in the js console:
> getDays(new Date("03-01-2012"), new Date("03-01-2012"));
["Thursday"]
> getDays(new Date("03-01-2012"), new Date("03-05-2012"));
["Thursday", "Friday", "Saturday", "Sunday", "Monday"]
> getDays(new Date("03-01-2012"), new Date("03-05-2013"));
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

A:  var sevenDaysInMS = 604800000;
    if (new Date(dTo - dFrom).getTime() >= sevenDaysInMS) {
        $('.day_hid').attr(attrUnaviableDay, "true");
    } else {
        var dt = dFrom;
        do {
            var day = dt.getDay();
            ActivateDaySelector(day);
            dt.setDate(dt.getDate() + 1);
        } while (dt <= dTo);
    }

I think it is ok. What do you think ?


Q: mgwt / gwtphonegap advices, feedback, tips I have to develop an application on Android, iOS and Windows Phone by using Phonegap.
I would like to know if someone has already used mgwt / gwtphonegap and have your feedback / advices on these technologies, if you have encountered some blocking issues for example.
I have already developed a Phonegap application in javascript (jquery / jquery mobile) html / css, but now I would know if I could start another one by using only GWT. However I would like to avoid to begin the development and realize 3 weeks later that I'm blocked because of mgwt / gwtphonegap.
Note that I have never developed with GWT but often in Java
Thanks

A: I've been using mgwt/phonegap only a few months, so I'm definitely not an expert, but so far no major stumbling blocks. I like GWT, as it is well documented, robust and supported, although mgwt is a bit less so. There's an active google forum at https://groups.google.com/forum/?fromgroups#!forum/mgwt. Maybe if you have some more specific question, I or someone on that forum could answer it.


Q: If two random numbers generated at exactly same time using Math.random(), would they be same or different? I want to predict the random number generated with Math.random() function.
I studied an article that the algorithm behind random number generator function takes the time in mili seconds an input, and generate a random number.
So, is this possible to predict the next random number?
I am playing a game named as dragon/tiger. Each dragon and tiger has 13 numbers. The numbers for both are both randomly generated after every 15 seconds. The side having higher number wins. Is there any way to predict which side will win(what number would be generated next)?


Q: Warning: Error: dyld: lazy symbol binding failed: Symbol not found: _objc_autoreleasePoolPush I'm getting an error when imagemin is run on png : Warning: Error: dyld: lazy symbol binding failed: Symbol not found: _objc_autoreleasePoolPush
i'm on a macbook pro 10.6.8
I installed grunt today along with the plugin's
Any help would be wonderful as google is pointing me to IOS development issues.

A: The binary is compiled for a newer version of the OS (you're now 4 major releases behind — upgrade if you can!)


Q: How to use org.apache.logging.log4j.jul.LogManager in an eclipse-rcp application? I am trying to use the log4j2 LogManager in an eclipse rcp application.
I have

-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager

set as start parameter. Starting the rcp application from within my eclipse IDE everything works as expected. But as soon as I start it as a standalone application logging won't work.
A possible hint may be the following stacktrace from the client console:
Could not load Logmanager "org.apache.logging.log4j.jul.LogManager"
java.lang.ClassNotFoundException: org.apache.logging.log4j.jul.LogManager
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at org.eclipse.core.runtime.internal.adaptor.ContextFinder.loadClass(ContextFinder.java:131)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.util.logging.LogManager$1.run(Unknown Source)
        at java.util.logging.LogManager$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.util.logging.LogManager.<clinit>(Unknown Source)
        at java.util.logging.Logger.demandLogger(Unknown Source)
        at java.util.logging.Logger.getLogger(Unknown Source)
        at org.apache.felix.gogo.runtime.threadio.ThreadIOImpl.<clinit>(ThreadIOImpl.java:30)
        at org.apache.felix.gogo.runtime.activator.Activator.start(Activator.java:75)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683)
        at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:300)
        at org.eclipse.equinox.console.command.adapter.Activator.startBundle(Activator.java:248)
        at org.eclipse.equinox.console.command.adapter.Activator.start(Activator.java:237)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702)
        at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683)
        at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:381)
        at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:300)
        at org.eclipse.osgi.framework.internal.core.ConsoleManager.checkForConsoleBundle(ConsoleManager.java:215)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.startup(EclipseStarter.java:297)
        at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:176)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
        at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
        at org.eclipse.equinox.launcher.Main.run(Main.java:1438)

What do I need to do to get logging running in the RCP application without starting it from within my IDE?

A: It sounds like eclipse is aware of your dependency on this class and is able to add it to the classpath for you. What you need is a way to add the dependency to the classpath when you run it outside of eclipse. To fix this, ensure the class org.apache.logging.log4j.jul.LogManager is on the classpath. This can be done with -cp and the path to the jar file. For example if you have a class com.org.Main you are trying to run.
java -cp your.jar:log4j-jul-2.3.jar com.org.Main

your.jar is the jar containing your application and log4j-jul-2.3.jar is the jar containing the missing class.


Q: Creating HK2 modules I'm trying to leverage the Hundred Kilobyte Kernel (HK2) framework, however I can't find any tutorials or working examples of it. I have installed Maven, as it is required, but I can't find the archetypes to work with. I'm working with Eclipse, and I have only found this Netbeans guide but even the example source files are non existent.
Under Eclipse, I managed to install the m2e maven plugin and I have tried to start a new project, however when I try to search for the hk2 archetype to create my customization of it I can't find the required resources. I try to create a new project, and then add an archetype, I specify com.sun.enterprise as the group id, the artifact id as hk2 (and hk2-maven-plugin as per some instructions), the latest version I could find (1.6.9) and the remote location as http://download.java.net/maven/glassfish/, but even when the jar files are there, there is no archetype catalog file that I can find. I have also tried adding this location as a Remote Catalog, but since there is no xml file to point to, it says the catalog is empty.
My question is, does anyone have any updated resources or startup steps to create an hk2 module? or can tell me how to use what I have? Inside the jars there are pom.xml files, however if I import those to Eclipse, it has errors that I don't know how to fix. Development on the project seems almost completely halted (last updates are from jul 2011) but maybe someone already familiar with Glassfish plugin development can point me in the right direction? or maybe could someone recommend an alternative to HK2? If anyone has any good OSGi tutorials that would be nice too, or any other similar framework.
Thanks!

A: Sounds like you're better off with OSGi ... The HK2 (which would surprise me if it was still 100k) was an attempt to not depend on OSGi directly for Glassfish. I do not think it has a well maintained API.
Since OSGi is a well defined and maintained API, that it runs on Glassfish, and that you also get portability to other environments seems to indicate that the choice for OSGi is smarter. The easiest way to get started is http://bndtools.org/

A: If you want to do Glassfish module development I can recommend you following tutorials and one example taken from the Glassfish trunk. Just have a look there how they do it. I tried it once, but since HK2 is not really OSGi as Peter already mentioned, I let it be after some time :) But maybe you can take advantages of these information now ;)

*

*http://kalali.me/glassfish-modularity-system-how-extend-glassfish-cli-and-web-administration-console-part-2-developing-sample-modules/

*http://java.net/projects/glassfish-samples/sources/svn/show/trunk/v3/plugin/adminconsole/console-sample-ip/


Q: Android loadLabel giving very laggy/slow performance, any solutions? I'm trying to create a launcher app in which I fetch all app names with loadLabel, but it's taking almost 3 second to load the names, and is very slow!!! I tried removing that text and now it works very fast! But I want app labels, Can we use any alternative method? Here's the code:
TextView label = (TextView) grid.findViewById(R.id.label);
            Typeface tf_label = Typeface.createFromAsset(getAssets(),
                    "fonts/RobotoC-Regular.ttf");
            label.setTypeface(tf_label);
            label.setText(info.activityInfo.loadLabel(getPackageManager())
                    .toString());

A: similiar problem here. I load the list of all apps and add them to a recyclerview, i had to wait some seconds before it was loaded so i timed the loading time. What i noticed is that loading icons and labels with 70 apps i needed around 2.6 seconds to load the apps, without loading icons and label ... an astonishing 61ms! YEAH milliseconds!
For now i am using a temporary solution, i will probably improve it in the future. What i did is create a model object that loads labels and icons in a background thread.
public class AppModel {
    ComponentName componentName;

    Drawable icon = null;
    String appName = "";

    public AppModel(ComponentName componentName) {
        this.componentName = componentName;
    }

    public void init(ActivityInfo ai, PackageManager pm) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                appName = (String) ai.loadLabel(pm);
                icon = ai.loadIcon(pm);
            }
        }).start();

    }
    ...
    ...
}

when i load the apps i do the following:
AppModel appModel = new AppModel(componentName);
appModel.init(ai, pm);
// other stuff

I needed a fast and working hotfix, in this way while the app is added to the recyclerview the labels and icons get loaded in background, cutting down the loading time by a lot!
A future solution i am considering is to load those icons and labels in multithreading.
Hope it helps.


Q: Capturing IR Data using VB.NET Just found an old IR reciever (Microsoft eHome Infared Transceiver) and i'm trying to write an application that can use data it captures...
Any examples or jumping off points for this are appreciated.

A: Looks like it's a USB HID device. As such, you should be able to use Win32 API to talk to it - similar to other USB HID devices.

A: I think the Microsoft eHome Infared Transceiver is a Human Interface Device (HID), so I'd start with The HID Page.
This has a VB.NET sample on it.


Q: PHP displaying arrays having duplicate with color=red I have a array that i want to check if has duplicates using PHP
$i=array('One','Two','Two','Three','Four','Five','Five','Six');

I was able to achieve it by using below function
  function array_not_unique($input) {
       $duplicates=array();
       $processed=array();
       foreach($input as $i) {
           if(in_array($i,$processed)) {
               $duplicates[]=$i;
           } else {
               $processed[]=$i;
           }
       }
       return $duplicates;

   }

I got below output
Array ( [0] => Two [1] => Five )

Now how can i display the previous arrays and mark values with duplicates referencing the array_not_unique function return values to a HTML table.
My goal is to display the duplicated values with red font color.

A: Try this piece of code... simplest and shortest :)
$i=array('One','Two','Two','Three','Four','Five','Five','Six');

$arrayValueCounts  = array_count_values($i);

foreach($i as $value){

    if($arrayValueCounts[$value]>1){

        echo ''.$value.'';
    }
    else{

        echo ''.$value.'';
   }
}

A: Here is optimized way that will print exact expected output.
<?php

$i=array('One','Two','Two','Three','Four','Five','Five','Six');

$dups = array_count_values($i);
print_r($dups);

foreach($i as $v)
{
    $colorStyle = ($dups[$v] > 1) ? 'style="color:red"' : '';
    echo "$v";
}

?>

A: Try this,
function array_not_unique($input) {
       $duplicates=array();
       $processed=array();
       foreach($input as $key => $i) {
           if(in_array($i,$processed)) {
               $duplicates[$key]=$i; // fetching only duplicates here and its key and value
           }
       }
       return $duplicates;
}
foreach($processed as $k => $V){
    if(!empty($duplicates[$k])){ // if duplicate found then red
        echo ''.$duplicates[$k].'';
    }else{
        echo ''.$duplicates[$k].''; // normal string
    }
}

A: Like this :
PHP
function array_duplicate_css($input) {

   $output = $processed = array();

   foreach($input as $key => $i) {
       $output[$key]['value'] = $i;
       if(in_array($i, $processed)) {
           $output[$key]['class'] = 'duplicate';
       } else {
           $output[$key]['class'] = '';
           $processed[] = $i;
       }
   }

   return $output;
}

foreach(array_duplicate_css($input) as $row) {
    echo '
' . $row['value'] . '
';
}

CSS
.duplicate {
    color: #ff0000;
}

A: Simple use array_count_values.
$array=array('One','Two','Two','Three','Four','Five','Five','Six');

$new_array= array_count_values($array);

foreach($new_array as $key=>$val){

  if($val>1){

     for($j=0;$j<$val;$j++){

         echo "".$key."";
     }

   }else{

     echo "".$key."";

   }

}

A: It can be done in several ways. This is just a one method. Step one maintain 2 arrays. Then store the duplicated indexes in one array. When you iterating use a if condition to check whether the index is available in the "duplicated indexes" array. If so add the neccessary css.


Q: Abbreviating numbers in Android, locale sensitive In my Android project, I am hoping to find a way to abbreviate numbers that is sensitive to various locales. If the number is less than 1000, it is to remain as is; otherwise, I would like the number divided by the largest possible power of 1000 and rounded to two decimal places. So far, I have the below code, which correctly produces the desired results as stated under Output.
public void formatNumbers() {
    //Output:
    //842 => 842
    //24,567 => 24.57k
    //356,915 => 356.92k
    //7,841,234 => 7.84M
    //1,982,452,873 => 1.98B
    int[] i = new int[] {842, 24567, 356915, 7841234, 1982452873};
    String[] abbr = new String[] {"", "k", "M", "B"};
    DecimalFormat df = new DecimalFormat("0.00");
    df.setRoundingMode(RoundingMode.HALF_UP);
    for (long i1 : i) {
        int thousands = thousands(i1);
        String result;
        if(thousands == 0) {
            result = String.valueOf(i1);
        } else {
            double d = (double) i1 / Math.pow(1000.0, thousands);
            result = df.format(d)+abbr[thousands];
        }
        System.out.println(i1 + " => " + result);
    }
}
public int thousands(double num) {
    //returns the number of times the number can be divided by 1000
    int n=0;
    double comp=1000.0;
    while(num>comp) {
        n++;
        comp*=1000.0;
    }
    return n;
}

My concern is that I want a way to ensure that the output is sensitive to locale. If I understand correctly, DecimalFormat should take care of conventions such as commas instead of decimals where applicable; this leaves my concern with the suffix. While my output would be generally be understood in the United States for casual purposes (despite the fact that "M" is used to mean "thousands" in some industries, such as finance) and, from my understanding, many areas in Europe which have languages based on Latin, there are many locales that this would not be understood well. Perhaps there is a built-in function that handles this that I have not been able to find. Thank you in advance for your attention to and input on this task.


Q: Play audio when app is not in foreground or app is inactive I do not want any code but want to get reference that how can we play audio in background in multitasking devices when application is running in background not in foreground...
Please help me to solve this question.
Thanks in advance..

A: There is developer documentation available here:

*

*Executing Code in the Background

*Playing Background Audio

*Audio Session Programming Guide

A: I had solved this question by referring iOS Application Background tasks
and make some changes in .plist file of our application..
Happy coding...


Q: Regex: Match string from set of characters, but need to have exactly X count of a specific character I have a very specific regex match and I can't seem to figure it out.
I need to find full strings matches for /^[aple]+$/i but MUST match exactly two "p's" and exactly one of the other characters.
Any other characters are not allowed. Case insensitive.
So, for example, these will successfully match:
Apple
ppleA
APPLE
apple
ppale

These would not match:
foo
appple
aple
bar
test

I've tried to set the explicit count of p using {brackets} but I think I have the syntax completely wrong. Such as: /^([p]{2})([ale]{1}+$)/i -- not working at all. This one ^(([a]{1})([p]{2})([l]{1})([e]{1}))+$ matches "apple" but it doesn't match "pplea"
Assume I can do this in two sets of matches, run it first to get the set of matches that may have any # of p's and then do a second run to test for exactly two, but there has got to be a one-liner?
Thanks for any help.

A: Something like this would work:
/^(?=.*a)(?=.*p.*p)(?=.*l)(?=.*e)[aple]{5}$/i

*

*/^ - start the regex and use a start string anchor

*(?=.*a) - ensure that an a exists anywhere in the string

*(?=.*p.*p) - ensure that two ps exist anywhere in the string

*(?=.*l) - ensure that an l exists anywhere in the string

*(?=.*e) - ensure that an e exists anywhere in the string

*[aple]{5} - get 5 chars of a, p, l, or e

*$ - end string anchor

*/i - case-insensitive modifier

https://regex101.com/r/DJlWAL/1/
You can ignore the /gm in the demo as they are used just for show with all the words at one time.

A: You can assert a single instance of a l and e by using a character class and optionally matching all allowed chars except the one that you want to assert, preventing unnecessary backtracking.
Then match 2 times a p char between optionally matching the other chars  (as they are already asserted for).
^(?=[ple]*a[ple]*$)(?=[ape]*l[ape]*$)(?=[apl]*e[apl]*$)[ale]*p[ale]*p[ale]*$

Explanation

*

*^ Start of string

*(?=[ple]*a[ple]*$) Assert an a

*(?=[ape]*l[ape]*$) Assert an l

*(?=[apl]*e[apl]*$) Assert an e

*[ale]*p[ale]*p[ale]* Match 2 times a p

*$ End of string

Regex demo
Or a shorter version using a quantifier based of the answer of @MonkeyZeus.
^(?=[ple]*a)(?=[ape]*l)(?=[apl]*e)(?=[ale]*p[ale]*p)[aple]{5}$

Regex demo

A: ^(?=^[^a]*a[^a]*$)(?=^[^l]*l[^l]*$)(?=^[^e]*e[^e]*$)[aple]{5}$
This works by restricting the number of a, l, and e characters to exactly 1 of each, and then restricting the overall string to exactly 5 characters to enforce 2 p characters.
You asked about regex, but in case it helps, an algorithmic version would be to sort the characters of APPLE and compare to the upper-cased version of your string sorted as above.