Q: Jquery validation with multi field I have a form with three select box and one hidden field. I want to validate a string that is created from three select box's value is included in hidden field.
Exampe.
<form>
    <select name="s1">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
    <select name="s2">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
    <select name="s3">
        <option value="1">1</option>
        <option value="2">1</option>
    </select>
    <input type="hidden" name="result" value="#123#245#" />
</form>

I want to valid join(s1.val, s2.val, s3.val) in result.val by jquery validation.
How can I do? I know that I need create custom rule.
Please help me.

A: As mention above in the comment
html code:
<form>
    <select name="s1">
         <option value="1">
         <option selected value="2">
    </select>

    <select name="s2">
        <option selected value="1">
        <option value="2">
    </select>

    <select name="s3">
    <option value="1">
    <option selected value="2">
  </select>
  <input type="hidden" name="result" id="hiddenVal" value="#212#" />
</form>

javaScript or jquery  code:
var str = "#";
$('form select').each(function(){
   str = str + $(this).val();
});

str +="#";
alert(str);
if($("#hiddenVal").val() == str){
   alert("yes value from select and value from hidden field is equal");
}

jsFiddle

A: var concate_string = "";
$('form select').each(function(){
concate_string = concate_string +"#"+$(this).val();
});

concate_string = concate_string +"#";
if($('[name="result"]:eq(0)')==concate_string){
//your action ?
}


Q: git branch -d : Fatal - Couldn't look up commit object for HEAD Say I am in a bare repository (a remote), if I try to delete a branch with git branch -d <branch_name> I get the following error:
fatal: Couldn't look up commit object for HEAD

Why? Is there a reason why I should be unable to delete branches from a  bare repository?

A: To avoid this confusion you can use

"git push origin --delete branch_name"

this deletes remote branch not local branch.

A: Make sure you use a capitol D in the command, in this case you would type git branch -D <branch_name>. Note that this will only delete the branch from your local computer
If you are trying to delete a remote branch, type git push origin :<branch_name> (remember to add the colon)

A: Find the file .git/refs/heads/branch_name in Windows Explorer and directly delete it.

A: This only happens when the default branch (the branch HEAD in the bare repository folder is pointing to - usually master) doesn't exist locally.
If it does exist - you would be able to delete the branch with branch -d even from a bare repository folder (-d assuming it was merged).
If you are working with git worktrees - issuing the command from the worktree may succeed (same condition regarding HEAD of the worktree should be met)

A: From Pyrocks's answer:

This only happens when the default branch (the branch HEAD in the bare repository folder is pointing to - usually master) doesn't exist locally

This case is addressed with Git 2.39 (Q4 2022), which fixes a bug where git branch -d(man) did not work on an orphaned HEAD.
See commit eb20e63 (02 Nov 2022) by Jeff King (peff).
(Merged by Taylor Blau -- ttaylorr -- in commit 26734da, 18 Nov 2022)

branch: gracefully handle '-d' on orphan HEAD
Reported-by: Martin von Zweigbergk
Signed-off-by: Jeff King
Signed-off-by: Taylor Blau

When deleting a branch, "git branch -d"(man) has a safety check that ensures the branch is merged to its upstream (if any), or to HEAD.
To do that, naturally we try to resolve HEAD to a commit object.
If we're on an orphan branch (i.e., HEAD points to a branch that does not yet exist), that will fail, and we'll bail with an error:
$ git branch -d to-delete
fatal: Couldn't look up commit object for HEAD

This usually isn't that big of a deal.
The deletion would fail anyway, since the branch isn't merged to HEAD, and you'd need to use "-D" (or "-f").

See "How do I delete a local git branch when it can't look up commit object in 'refs/heads'?", since Git 2.34 (Q4 2021) added the --force option to git branch -d.

And doing so skips the HEAD resolution, courtesy of 67affd5 ("git-branch -D(man): make it work even when on a yet-to-be-born branch", 2006-11-24, Git v1.5.0-rc0 -- merge).
But there are still two problems:

*

*The error message isn't very helpful.
We should give the usual "not fully merged" message, which points the user at "branch -D".
That was a problem even back in 67affd5.

*Even without a HEAD, these days it's still possible for the deletion to succeed.
After 67affd5, commit 99c419c (branch -d: base the , 2009-12-29, Git v1.7.0-rc0 -- merge) (branch -d: base the "already-merged" safety on the branch it merges with, 2009-12-29) made it OK to delete a branch if it is merged to its upstream.

We can fix both by removing the die() in delete_branches() completely, leaving head_rev NULL in this case.
It's tempting to stop there, as it appears at first glance that the rest of the code does the right thing with a NULL.
But sadly, it's not quite true.
We end up feeding the NULL to repo_is_descendant_of().
In the traditional code path there, we call repo_in_merge_bases_many().
It feeds the NULL to repo_parse_commit(), which is smart enough to return an error, and we immediately return "no, it's not a descendant".


Q: WSO2 P.PaaS : Access APIM Am new to WSO2. I have installed P.PaaS. How do I access APIM? Can you show me an example, please?
using phone. Pardon brevity.

A: You do not have to install WSO2 Private PaaS to have API Manager. From WSO2 site, you can download stand-alone API Manager or use the hosted version - WSO2 API Cloud.
Once you are familiar with API Manager or API Cloud, if you do decide that you want to spawn it within Private PaaS, you can follow this document to locate the corresponding cartridge and subscribe to it.

A: Before getting started with WSO2 Private PaaS, it is worth to watch these well-organized, 6-steps video tutorials on "Getting Started With WSO2 Private PaaS". After watching these, you will have a basic understanding, from there you can move forward without any issues.
Step 0 -  Finding the Documentation
Step 1 - Provisioning an EC2 Instance from WSO2 Private PaaS AMI
Step 2 - Provisioning the WSO2 Private Platform as a Service Environment
Step 3 - Configuring Private Platform as a Service with Tenants
Step 4 - Provisioning Application Platform Services
Step 5 - Deploying a Web Application on a Private Platform as a Service Environment running on Amazon EC2


Q: Apple Watch on react-native I want to get react-native working for the Apple Watch, but I'm not sure where to start
I started reading the code for the iOS implementation to figure out how they did it there.
My question is: are there any resources or guidelines for help to actually implement react-native (do they ever talk about this aspect of it) or do I need to just read through the code and figure it out on my own?
It would be nice if the react-native team made a document on how they got it up and running on iOS (or Android), though they may already have that out there which is what I'm looking for.
Thanks in advance for any advice and/or help

A: I was looking into this, too. I will share my findings.
According to this comment from the React Native team back in 2015, the team doesn't have resources to support it, yet.

Right now, we're focused on normal iOS and Android. We still a very small team and don't have the resources to target a different support right now. However, we open sourced React Native in the hope that we get help from the community to build those :)

Someone tried to build one with a lot of reverse engineering, but there are still unsolved issues causing crashes.


Q: How to disable all actions of hyperlink and submit form but can drag these elements I use JavaFx WebView to show a web page but I don't want to have any interaction(location change) on web page and web engine disabled Javascript also. Because of that reason, I tried to disable all actions of hyperlink and submit form by
a[style] {
    pointer-events: none !important;
    cursor: default;
}

input[style] {
    pointer-events: none !important;
    cursor: default;
}

So I can not drag them. Have another way for this issue? Solve it by CSS or JavaFx as better.

Thanks for advance.

A: Using Jquery:
$('input[type="submit"]').attr('disabled','disabled');
and
$('a').attr('disabled','disabled');
like this

A: You can attempt to prevent the default action on as many events as you like.  Note that browsers usually allow this, but do have the final say (I vaguley remember some issues with this not always working).
var events = ["keypress","click","submit","focus","blur","tab"];
events.forEach(function(eventName){
    window.addEventListener(eventName, function(e){
        // this is the list of tags we'd like to prevent events on
        // you may wish to remove this early return altogether, as even a div or span
        // can cause a form to submit with JavaScript
        if (["INPUT","A","FORM","BUTTON"].indexOf(e.tagName) === -1) {
            return;
        }

        // prevent the default action
        e.preventDefault();

        // stop other JavaScript listeners from firing
        e.stopPropagation();
        e.stopImediatePropagation();

        // if an input is somehow focused, unfocus it
        var target = e.target;
        setTimeout(function(){
          if (target.blur) target.blur();
        }, 50);
    // true as the third parameter signifies 'use capture' where available;
    // this means we get the event as it's going down, before it starts to bubble up
    // our propagation prevention will thus also prevent most delegated event handlers
    }, true);
});

You cannot solve this with CSS.  pointer-events doesn't allow you to specify which pointer events are okay.  For that, you do need JavaScript.


Q: CAShapeLayer strokeColor get mix with fillColor I have made a hexagonal View with border. The problem I am facing now is I am not able to set the desired color for border which I have made using strokeWidth (not borderWidth) and now my layer's strokeColor get mix with fill color of the layer.
Here is the code:
CAShapeLayer *hexagonMask = [CAShapeLayer layer];
CAShapeLayer *hexagonBorder = [CAShapeLayer layer];
hexagonMask.frame=self.layer.bounds;
hexagonBorder.frame = self.layer.bounds;

UIBezierPath* hexagonPath=[self makeHexagonalMaskPathWithSquareSide:side];     //making hexagon path

hexagonMask.path = hexagonPath.CGPath;                 //setting the mask path for hexagon
hexagonBorder.path = hexagonPath.CGPath;               //setting the maskpath for hexagon border
hexagonBorder.fillColor=[UIColor clearColor].CGColor; //setting by default color

hexagonBorder.lineWidth = self.customBorderWidth; //   setting border width

hexagonBorder.strokeColor = self.customBorderColor.CGColor;  //setting  color for hexagon border

hexagonBorder.fillColor = self.customFillColor.CGColor;    //setting fill color for hexagon

Any suggestions to solve this Problem?

A: Finally I found a way out to solve this problem.
I have added a CALayer as sublayer and the fill color is used to create as a UIImage which is used to set as contents for the sublayer.
Here is the code for someone who may face this problem in future
CAShapeLayer *hexagonMask = [CAShapeLayer layer];
CAShapeLayer *hexagonBorder = [CAShapeLayer layer];
hexagonMask.frame=self.layer.bounds;
hexagonBorder.frame = self.layer.bounds;

UIBezierPath* hexagonPath=[self makeHexagonalMaskPathWithSquareSide:side];       //making hexagon path

hexagonMask.path = hexagonPath.CGPath;                 //setting the mask path for   hexagon
hexagonBorder.path = hexagonPath.CGPath;               //setting the maskpath for hexagon border
hexagonBorder.fillColor=[UIColor clearColor].CGColor; //setting by default color

hexagonBorder.lineWidth = self.customBorderWidth; //   setting border width

hexagonBorder.strokeColor = self.customBorderColor.CGColor;  //setting  color for hexagon border

CGFloat coverImageSide=side-(_customBorderWidth);
            CGFloat backgroundLayerXY=_customBorderWidth/2.0;

            UIImage *coverImage=[UIImage ImageWithColor:_customFillColor width:coverImageSide height:coverImageSide];
            UIBezierPath* dpath=[self makeHexagonalMaskPathWithSquareSide:coverImageSide];

            CALayer *backgroundLayer=[CALayer layer];
            backgroundLayer.frame=CGRectMake(backgroundLayerXY, backgroundLayerXY, coverImageSide, coverImageSide);
            CAShapeLayer *backgroundMaskLayer=[CAShapeLayer layer];
            backgroundMaskLayer.path=dpath.CGPath;
            backgroundLayer.mask=backgroundMaskLayer;
            [backgroundLayer setContentsScale:[UIScreen mainScreen].scale];
            [backgroundLayer setContentsGravity:kCAGravityResizeAspectFill];
            [backgroundLayer setContents:(__bridge id)[UIImage maskImage:coverImage toPath:dpath].CGImage];

            [self.layer.sublayers[0] addSublayer:backgroundLayer];


Q: The following code works in my IDE but fails to work in the online editor provided at hackerrank.com
Input Format
Every line of input will contain a String followed by an integer. Each String will have a maximum of 10 alphabetic characters, and each
  integer will be in the inclusive range from 0 to 999.
Output Format
In each line of output there should be two columns: The first column contains the String and is left justified using exactly 15 characters.
  The second column contains the integer, expressed in exactly 3 digits;
  if the original input has less than three digits, you must pad your
  output's leading digits with zeroes.
Sample Input
java 100
cpp 65
python 50

Sample Output
================================
java           100
cpp            065
python         050
================================

import java.util.Scanner;

    public class Main {

        public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            StringBuilder sb=new StringBuilder();
            int x=0,len=0;

            System.out.println("================================");
            for(int i=0;i<3;i++)
            {
                boolean bool = true;

                while(bool){
                    sb=sb.append(sc.next());
                    len=sb.toString().length();
                    if(len>10) {
                        sb.delete(0,len);
                        System.out.println("Enter zero - ten character string");

                    }
                    else
                        bool = false;
                }

                bool= true;

                while(bool){
                    x=Integer.parseInt(sc.next());
                    sc.nextLine();
                    int l= Integer.toString(x).length();
                    if(l>3) {
                        System.out.println("Enter zero - three digit number");

                    }
                    else
                        bool = false;

                }

                System.out.printf("%1$-16s %2$03d\n",sb,x);
                sb=sb.delete(0,len);
            }

            System.out.println("================================");

        }
    }

A: You printed two extra space characters between each strings and numbers.
Try Replacing
System.out.printf("%1$-16s %2$03d\n",sb,x);

with
System.out.printf("%1$-15s%2$03d \n",sb,x);

Also you should remove the line sc.nextLine(); to avoid extra reading and causing an exceition.


Q: Java 8 thenApply() and thenAccept() I'm creating a demonstration example for chaining CompleteableFuture operations and I think I'm close but there's something I'm missing. Everything compiles except for the final "Build cakes in parallel" clause in main():
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.stream.*;
import java.time.*;

// Use decorator pattern to build up the cake:

interface Cake_ {
  String describe();
}

class Cake implements Cake_ {
  private int id;
  public Cake(int id) { this.id = id; }
  @Override
  public String describe() {
    return "Cake " + id;
  }
}

abstract class Decorator implements Cake_ {
  protected Cake_ cake;
  public Decorator(Cake_ cake) {
    this.cake = cake;
  }
  @Override
  public String describe() {
    return cake.describe();
  }
  @Override
  public String toString() {
    return describe();
  }
}

class Frosted extends Decorator {
  public Frosted(Cake_ cake) {
    super(cake);
  }
  @Override
  public String describe() {
    return cake.describe() + " Frosted";
  }
}

class Decorated extends Decorator {
  public Decorated(Cake_ cake) {
    super(cake);
  }
  @Override
  public String describe() {
    return cake.describe() + " Decorated";
  }
}

// For the cake-building assembly line:

class CreateCakes implements Supplier<Cake> {
  private int id;
  public CreateCakes(int id) {
    this.id = id;
  }
  @Override
  public Cake get() {
    return new Cake(id);
  }
}

class FrostCakes implements Function<Cake, Frosted> {
  @Override
  public Frosted apply(Cake cake) {
    return new Frosted(cake);
  }
}

class DecorateCakes implements Consumer<Frosted> {
  public Decorated result;
  @Override
  public void accept(Frosted fc) {
    result = new Decorated(fc);
  }
}

public class Test {
  public static int NUM_OF_CAKES = 20;
  public static void main(String[] args) {
    // Change from the default number of threads:
    System.setProperty(
      "java.util.concurrent.ForkJoinPool" +
      ".common.parallelism", "" + NUM_OF_CAKES);

    // Test/demonstrate the decorator pattern:
    List<Cake_> decorated =
      IntStream.range(0, NUM_OF_CAKES)
        .mapToObj(Cake::new)
        .map(Frosted::new)
        .map(Decorated::new)
        .collect(Collectors.toList());
    decorated.forEach(System.out::println);

    // Build cakes in parallel:
    List<CompletableFuture<?>> futures =
      IntStream.range(0, NUM_OF_CAKES)
        .mapToObj(id -> new CreateCakes(id))
        .map(CompletableFuture::supplyAsync)
        .thenApply(new FrostCakes())
        .thenAccept(new DecorateCakes())
        .collect(Collectors.toList());
    futures.forEach(CompletableFuture::join);
  }
}

I realize I'm missing some fundamental understanding in the definition of the futures list, but I've included it to show what I'm trying to accomplish here: a cake factory with portions of the cake-creation process running in parallel.

A: A quick answer to your question will be that the thenApply line doesn't compile because the result from the line above (map(CompletableFuture::supplyAsync)) returns Stream<CompletableFuture<Cake>> and not CompletableFuture<Cake>.
You'll need to do something like map(cakeFuture -> cakeFuture.thenApply(new FrostCakes())).
But I think there's a more important point that needs to be made.
If your examples are meant for educational purposes, I'd recommend investing another day or two in preparation, and more specifically in reading about the fundamentals of stream operations and CompletableFuture.
This way you'll feel much more confident when you get to present your material, but more importantly, you won't be presenting less than perfect code examples that can potentially harm your colleagues/students notion about how can streams and CompletableFutures (and even decorators) be used.
I'll point out some of the things that I think need to be redone in your examples.

*

*Manually setting the parallelism level of the common ForkJoinPool is not always a good idea. By default, it uses the number of processors, as returned by Runtime.availableProcessors() which is a pretty good default. You need to have a pretty good reason to change it to something more than that, because in most cases you'll just be introducing unnecessary overhead from scheduling and maintenance of redundant threads. And to change it to the number of tasks you're planning to fire is almost always a bad idea (explanation omitted).

*Your stream examples perform a couple of stream operations, then terminate with a collection, and then a stream operation is performed on the collected list. They can be rewritten without the collection to list, by directly applying the forEach on the stream returned by the last mapping, and arguably this will be a better demonstration of the fluent programming model using Java 8 streams.

*Your examples also don't perform their operations in parallel. You can fix that easily by adding .parallel() after IntStream.range(), but unless you remove the redundant collection to list from above, you won't be able to see that you've done something in parallel just by printing the list contents with forEach.

*Your classes implementing the java.util.function interfaces are not very idiomatic. I would argue that they should be replaced with the corresponding lambda expressions even though in your case this could result in a mouthful lambda in lambda, unless your second example is slightly rewritten.

*CompletableFuture.thenAccept returns a CompletableFuture<Void>, so in this stage of your stream processing you lose the references to the created, frosted and decorated cakes. This can be OK if you don't care about them, or if you log something about them in the decoration logic, but your example can easily mislead people that the finally collected list of CompletableFutures can be used to reach to the cakes (after all, who doesn't want to have his cake and eat it too).

So your first example can look something like
IntStream.range(0, NUM_OF_CAKES)
        .parallel()
        .mapToObj(Cake::new)
        .map(Frosted::new)
        .map(Decorated::new)
        .forEach(System.out::println);

Notice how the cake IDs are not ordered because of the parallel execution.


Q: Adding slide effect by anchor tag I want to open another searchpage.html html page with slide effects for which i used anchor tag.
Click

And js:
 $(document).ready(function () {
        $('.show_hide').click(function (e) {
            e.preventDefault(); //to prevent default action of link tag
            $(this).toggle('slide','left',100);
        });
 });

But its showing error:
TypeError: jQuery.easing[this.easing] is not a function

A: Try this one, this may help You..
HTML :
Click

JS:
$(document).ready(function () {
    $('.show_hide').click(function (e) {
        e.preventDefault(); //to prevent default action of link tag
        $('#add').slideToggle(1000);
    });
});

And Here is Demo.


Q: React Native - Sending text messages by phone i use fire base service. after wake up the app i need to send text message to users number by use device messaging, i install react-native-S M S but just work when on app and need to push user send button, can help me to send text message in background, thanks


Q: How to combine JSF togglePanel to trigger visibility of some other div/element/? I was looking through a number of websites, but i couldn't find out how to use a toggle panel to change the visibility of another element. Please see the example..
<rich:togglePanel switchType="client"
    stateOrder="panelOneOff, panelOneOn">
    <f:facet name="panelOneOff">
        <rich:toggleControl>
            <h:outputText value="Start"/>
        </rich:toggleControl>
    </f:facet>
    <f:facet name="panelOneOn">
        <rich:toggleControl switchToState="panelOneOff">
            <h:outputText value="Close"/>
        </rich:toggleControl>
    </f:facet>
</rich:togglePanel>

<rich:effect  name="hideDiv"  for="toggleAccordingToTheTogglePanel" type="Fade" />
<rich:effect  name="showDiv"  for="toggleAccordingToTheTogglePanel" type="Appear" />

<div id="toggleAccordingToTheTogglePanel">
    please show me on start and hide me on Close
</div>

What listeners will work to call the hideDiv() or showDiv() javascript functions so the DIV-Element at the end will appear or fade out?
update It be run on jboss 5.1 using richfaces 3.3.2

A: <rich:toggleControl onclick="hideDiv()">


Q: SQL delete multiple criteria duplicate records I have a table with duplicate records in all but one field (col4 for ex).  I just need to delete the duplicate entries where the t1.col4 field is blank.
ID  Col1   Col2   Col3   Col4
1   Joe     1      2      Yes
2   Sue     1      2
3   Joe     2      3
4   Joe     1      2

Goal: Delete only ID 4
I have tried both the inner join (I don't think msaccess allows this) and WHERE EXISTS/IN techniques with errors.
Exists technique deletes all records where t1.col4 is null (not just ones matched in subquery):
DELETE t1.*
  FROM t1
  WHERE Exists (
    SELECT t1.col1, t1.col2, t1.col3
      FROM t1
      Group by t1.col1, t1.col2, t1.col3
      HAVING Count(*) > 1
    )
    AND t1.col4 Is Null;

I've tried multiple iterations of the Inner Join technique but everything I've read here suggests it is not supported in Access. Happy to post what I've tried if it helps.  I've also tried writing the subquery to a temptable and then trying to delete records matched by the inner join.

A: You need a correlated subquery:
DELETE t1
  FROM t1
  WHERE EXISTS (SELECT t1.col1, t1.col2, t1.col3
                FROM t1 as tt1
                WHERE t1.col1 = tt1.col1 AND t1.col2 = tt1.col2 AND t1.col3 = tt1.col3 AND t1.id <> tt1.id
               ) AND
        t1.col4 Is Null;


Q: updating a notification service from activity I have a notification service that starts when application is started
and there are 2 buttons in main activity, I want to update notification by clicking on each buttons, foreample if I touch start button, the text view in notification service should show: you touched start button and ..
I want to update notification from my activity
how should I do that?
here is my code:
public class MainActivity extends AppCompatActivity {

Button btn_start,btn_end;

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

    btn_start = (Button) findViewById(R.id.btn_start);
    btn_end = (Button) findViewById(R.id.btn_end);

    Intent serviceIntent = new Intent(MainActivity.this, NotificationService.class);
    serviceIntent.setAction("startforeground");
    startService(serviceIntent);

}
public class NotificationService extends Service {
Notification status;
public static int FOREGROUND_SERVICE = 101;

@Override
public void onDestroy() {
    super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (intent.getAction().equals("startforeground")) {
        showNotification();
    }

    return START_STICKY;
}

private void showNotification() {
    RemoteViews views = new RemoteViews(getPackageName(), R.layout.status_bar);
    RemoteViews bigViews = new RemoteViews(getPackageName(), R.layout.status_bar_expanded);
    status = new Notification.Builder(this).build();
    status.contentView = views;
    status.bigContentView = bigViews;
    status.flags = Notification.FLAG_ONGOING_EVENT;
    status.icon = R.drawable.ic_launcher;
    startForeground(FOREGROUND_SERVICE, status);
}

}

A: You have to use same way as you create one and then update it with whatever you need by using this method:
NotificationManagerCompat.notify()
Read the details here:
https://developer.android.com/training/notify-user/build-notification
You need to use the same Notification id for when creating and when updating.


Q: Writing C# SDKs with dynamic responses and casting to a model For example;
I have a class called "User";
public class User
{
    public string Name { get; set; }
    public List<Job> Jobs { get; set; }
}

Awesome! Now, lets make a request to our REST API;
GET: api.com/users/123
RESPONSE:
{
    name : "Erik",
    jobs : [ { id : 1 }, { id: 2 } ]
}

Great! Now, lets do something fun with query strings and expand the jobs list.
GET: api.com/users/123?$expand=Jobs
RESPONSE:
{
    name : "Erik",
    jobs : [
        {
            id : 1,
            name : "My Job",
            address : "1515 My Street Rd. 20144, VA"
        },
        {
            id : 2,
            name : "My Job 2",
            address : "9595 My Street Rd. 20144, VA"
        }
    ]
}

But uh oh... We can't use the original User class. This is because the Job model looks like this;
public class Job
{
    public int Id { get; set; }
}

So naturally, the JSON serializer doesn't know how to cast it's "expanded" response.
What are my options?
Can I override the Jobs property in the User class? Like;
public class UserWithExpandingJobs : User
{
    public List<JobExpanded> Jobs { get; set; }
}

So that it is hides the initial inherited value and replaces it with a new Job model like this;
public class JobExpanded : Job
{
    public string Name { get; set; }
    public string Address { get; set; }
}

All this expanding is making my head hurt! It seems SO verbose.
Can anyone coach me through what I should be thinking or trying to do to minimize the SDK footprint.
Oh, btw... It's not letting me override Jobs because it is a different type. Thoughts?


Q: Maven build not exporting dependent library's for packaging type jar I need to create a runnable jar file that will be operated in Batch mode.
During development I need to use following api/frameworks apache-poi,hibernate,Spring etc.
So,I prefer to go with maven:
Please find below my maven file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>mypackage</groupId>
    <artifactId>myartifact</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <properties>
       <java.version>1.8</java.version>
    </properties>
   <dependencies>
      <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-core</artifactId>
         <version>5.2.17.Final</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>5.0.6.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-orm</artifactId>
         <version>5.0.6.RELEASE</version>
     </dependency>
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jms</artifactId>
         <version>5.0.6.RELEASE</version>
     </dependency>
     <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi</artifactId>
          <version>3.17</version>
      </dependency>
      <dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-lang3</artifactId>
         <version>3.8.1</version>
      </dependency>
     </dependencies>
    <build>
      <plugins>
         <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-jar-plugin</artifactId>
              <configuration>
                  <archive>
                      <manifest>
                          <addClasspath>true</addClasspath>
                       <mainClass>fully.qualified.classpath.Main</mainClass>
                       </manifest>
                       <manifestEntries>
                         <Class-Path>.</Class-Path>
                      </manifestEntries>
                   </archive>
              </configuration>
           </plugin>
       </plugins>
   </build>
 </project>

I am running the maven build from eclipse as clean package.
Build completes successfully.But in the generated jar all the dependent jar
is not present [spring/hibernate/poi] etc.
We need to run this jar as java -jar jarname from command prompt/console.

A: Consider using Maven Shade Plugin.

This plugin provides the capability to package the artifact in an uber-jar, including its dependencies

Spring framework can do similar thing for you. Generate sample project and check its pom file.

A: maven-jar-plugin provides the capability to build jars without dependencies.
To create jar with all it's dependencies you can use maven-assembly-plugin or maven-shade-plugin. Below is maven-assembly-plugin configuration in pom.xml:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>
                            fully.qualified.classpath.Main
                        </mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </execution>
    </executions>
</plugin>

More information: executable-jar-with-maven

A: Try this out inside your pom.xml file:
<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.8</version>
        <executions>
            <execution>
                <id>copy-dependencies</id>
                <phase>prepare-package</phase>
                <goals>
                    <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                    <outputDirectory>${project.build.directory}/classes/lib</outputDirectory>
                    <includeScope>runtime</includeScope>
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>


Q: A class rewritten with templates makes a program slower (in run-time) I have a class for a serial-memory 2D array that was initially an array of ints. Now that I need a similar array with another type, I've rewritten the class with templates; the only difference is in the type of stored objects:
template <class T>
class Serial2DArray
{
    ...
    T ** Content;
}

I have a few test functions that deal with Content, for example, a one that nullifies all elements in the array (they're not class members, they're outside functions working with Serial2DArray<int> objects. I've noticed that now it works 1-2% slower - all the other code in the class is untouched, the only difference is that earlier it was just a regular class with int ** Content and now it's a template.
A sort of similar question: Do c++ templates make programs slow? - has opinions that only compilation becomes slower (and I can see why, the compiler generates classes for each  that it finds in the code), but here I see the program becoming slower in run-time - is there any rational explanation?
Upd: issue narrowed down a little bit here: https://stackoverflow.com/a/11058672/1200000
Upd2: as mentioned in the comments, here's the function that became slower:
#include <windows.h>
#include <mmsystem.h>
...
int Size = G_Width * G_Height * sizeof(int);
DWORD StartTime = timeGetTime();
for(int i=0; i<100; ++i)
{
    FillMemory(TestArray.Content[0], Size, 0);
}
MeasuredTime = timeGetTime() - StartTime;

And here's the actual class template:
#include <malloc.h>

template <class T>
class Serial2DArray
{
    public:
    Serial2DArray()
    {
        Content = NULL;
        Width = 0;
        Height = 0;
    }
    Serial2DArray(int _Width, int _Height)
    {
        Initialize(_Width, _Height);
    }
    ~Serial2DArray()
    {
        Deinitialize();
    }
    T ** Content;
    int GetWidth()
    {
        return Width;
    }
    int GetHeight()
    {
        return Height;
    }
    int Initialize(int _Width, int _Height)
    {
        // creating pointers to the beginning of each line
        if((Content = (T **)malloc(_Height * sizeof(T *))) != NULL)
        {
            // allocating a single memory chunk for the whole array
            if((Content[0] = (T *)malloc(_Width * _Height * sizeof(T))) != NULL)
            {
                // setting up line pointers' values
                T * LineAddress = Content[0];
                for(int i=0; i<_Height; ++i)
                {
                    Content[i] = LineAddress; // faster than Content[i] =
                    LineAddress += _Width;    // Content[0] + i * _Width;
                }
                // everything went ok, setting Width and Height values now
                Width = _Width;
                Height = _Height;
                // success
                return 1;
            }
            else
            {
                // insufficient memory available
                // need to delete line pointers
                free(Content);
                return 0;
            }
        }
        else
        {
            // insufficient memory available
            return 0;
        }
    }
    int Resize(int _Width, int _Height)
    {
        // deallocating previous array
        Deinitialize();
        // initializing a new one
        return Initialize(_Width, _Height);
    }
    int Deinitialize()
    {
        // deleting the actual memory chunk of the array
        free(Content[0]);
        // deleting pointers to each line
        free(Content);
        // success
        return 1;
    }
    private:
    int Width;
    int Height;
};

As requested, binaries size comparison.
Code with the following:
Serial2DArray<int> TestArray;
Serial2DArray<int> ZeroArray;

*

*1 016 832 bytes.

Code with the following:
Serial2DArray TestArray; // NOT-template class with ints
Serial2DArray ZeroArray; // methods are in class declaration

*

*1 016 832 bytes

Code with the following:
Serial2DArray<int> TestArray;
Serial2DArray<int> ZeroArray;
Serial2DArray<double> AnotherArray;
Serial2DArray<double> YetAnotherArray;

*

*1 017 344 bytes

A: Yeah- random benchmark variability, not to mention the fact that the whole program is slower might have nothing at all to do with this specific class.

A: Using templates in your container class may lead to the known issue of template code bloat . Roughly it could lead to more page fault in your program decreasing performance.
So why would you ask ? Because a template would generate the classes for each class instance of your template instead of one, leading to more pages in your binary product, more code pages if you prefer. Which could statistically lead to more page fault, depending on your run-time execution.
Have a look to the size of your binary with one class template instance, and with two instances which must be the heaviest. It will give you a grasp of the new code size introduced with the new instance.
Here is the wikipedia article on that topic: Code bloat article. The issue could be the same when forcing the compiler to inline every functions and methods in your program, if only it could be available with your compiler. The standard tries to prevent that with making the inline keyword a "request" that the compiler must not follow everytime. For instance GCC produces your code in an intermediate langage in order to evaluate if the resulting binary won't be lead to code bloat, and may discard the inline request as a result.


Q: Why this functions duplicate data when scroll down to bottom page? Why this functions duplicate data when scroll down to bottom page ?
when scroll to bottom page sometime duplicate data.
<script type="text/javascript">
  $(document).ready(function(){
     $(window).scroll(function(){
       var height = $('#demoajax').height();
       var scroll_top = $(this).scrollTop();
           var isload = $('#demoajax').find('.isload').val();
           var page = $('#demoajax').find('.nextpage').val();
           document.getElementById('check').value = page++;
        if(($(window).scrollTop() + $(window).height() == $(document).height()) && (isload=='true')){
            $('#loading').show();
            $.ajax({
                url: 'aaa.php',
                type: 'POST',
                data: $('#fid').serialize(),
                cache: false,
                success: function(response){
                   $('#demoajax').find('.nextpage').remove();
                   $('#demoajax').find('.isload').remove();
                   $("#loading").fadeOut("slow");
                   $('#demoajax').append(response);
                    }
                });
    }
    return false;
    });
});
</script>

A: Did you mean sometimes the Ajax called more than one time, in that case you can busy flag. By default the busy flag set to false. Here is the code to do that
    var busy    =   false;

    if(($(window).scrollTop() + $(window).height() == $(document).height()) && (isload=='true'))
    {
        if(busy)
            return;

        busy = true;
        $('#loading').show();

        $.ajax({
            url: 'aaa.php',
            type: 'POST',
            data: $('#fid').serialize(),
            cache: false,
            success: function(response)
            {
                $('#demoajax').find('.nextpage').remove();
                $('#demoajax').find('.isload').remove();
                $("#loading").fadeOut("slow");
                $('#demoajax').append(response);
            },
            complete: function()
            {
                busy = false;
            }
        });
    }

    return false;
});

});
I think this should solve the problem.
Thank You.


Q: SSRS - 404 page not found I have a windows 2008 server running SSRS on SQL 2008. It is also a web server with Plesk installed.
I have been developing reports for this server for some time now on a development server. Everything is working fine on the development server. But I tried to move the reports to the live server and I get the error below:
Server Error
404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.
I am not sure why this is happening, because when I access the reports URL on its own it works fine. But as soon as I call the report in my web application hosted on the very same server I get this error. My application is written in c# and asp.net. Here is a section of code I use to access the report. Any help would be greatly appreciated:
        string ExpId1 = Convert.ToString(Request.QueryString["Id"]).Trim();
        string ExpId2 = ExpId1.Replace("@", "+");
        Int32 ExpId3 = Convert.ToInt32(qsc.decryptQueryString(ExpId2));
        string id=ExpId3.ToString();
        ReportViewer1.Width = 1050;
        ReportViewer1.Height = 600;
        ReportViewer1.Style.Add("Overflow", "Scroll");
        ReportViewer1.ProcessingMode = ProcessingMode.Remote;
        IReportServerCredentials irsc = new CustomReportCredentials("user", "password", "server");
        ReportViewer1.ServerReport.ReportServerCredentials = irsc;
        ReportParameter[] para = new ReportParameter[2];
        para[0] = new ReportParameter();
        para[0].Name = "ExpHearderId";
        para[0].Values.Add(id);//any value

        para[1] = new ReportParameter();
        para[1].Name = "ExpHeadreId";
        para[1].Values.Add(id);//any value

        ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://xxx.xxx.xxx.xxx/reportserver_TGO");
        string path=Server.MapPath("~/ReportingofUsers/ExpenseClaimReport");
        ReportViewer1.ServerReport.ReportPath = path;
        ReportViewer1.ServerReport.SetParameters(para);
        ReportViewer1.ShowParameterPrompts = false;
        ReportViewer1.ServerReport.Refresh();
        ReportViewer1.Visible = true;

A: This should help: http://otkfounder.blogspot.com/2007/11/solving-reportviewer-rendering-issue-on.html
EDIT: One more thing. I'm pretty sure that when you use Reports Server you should not use Server.MapPath. Just specify the path as you see it in Reports Server, in your case: /ReportingofUsers/ExpenseClaimReport. That is assuming that you publish reports to the server.


Q: Bypassing Controller in Rails Im using Rails 2.3.5 and I have a model, let's call it Post. I used named scopes to apply different kinds of sorts on Post. For example, in the Post model I have possibility to rank posts by its scores:
named_scope :order_by_acception_rate_desc,
Proc.new { |limit| { :limit => limit, :order => "acception_rate desc" } }

In the Post Controller I have:
def best
    @best_posts = Post.order_by_acception_rate_desc(10)
end

In the view I just render this collection @best_posts:
<%= render :partial => "post", :collection => @best_posts

Currently my application is working like that, but actually I do not need to have the method "best" in the Controller, and I could move it to the Model Post doing like:
def self.best
    self.order_by_acception_rate_desc(10)
end

and then in the view I would render the collection like:
<%= render :partial => "post", :collection => Post.best

I do not know which approach is better, but using the ranking methods in the Model, I could avoid to create routes for each one of ranking methods. What approach is better, is there any better approach than these?

A: with according to Rails conventions the logic should be separated,

*

*controllers handle permissions, auth/authorization, assign instance/class variables

*helpers handle html logic what to show/hide to user

*views should not provide any logic, permissions check. think about it from designer's point of view

*models handle data collection/manipulation over ORM

I'd like to ask you to try:
#helper
def self.best(limit)
  all(:limit => limit, :order => "acception_rate desc")
end

#controller
@best_posts = Post.best

#view
<%= render :partial => "post", :collection => @best_posts %>

A: You should not bypass the controller and include much logic in your view.
You could keep a single route and filter the Post model depending on one of the params.
You don't tell enough here to answer more clearly but you have the big picture.

A: You can leave just the view file and it should work.


Q: SQL Server Reporting Services 2008 R2 Express Edition "Report Builder" Button How do I enable the "Report Builder" button on SQL Server Reporting Services (Report Manager Web View).
I am using the 2008 R2 Express Edition.
Is this available in this edition ??
Thanks.

A: I don't believe that it's possible. If you compare Express to Standard, expand the Reporting node, you will see Model Support is unchecked for Express. Report Builder 1.0 only worked on prebuilt models so by extension, I'm assuming that bullet continues to address models and the report builder.
I never install Express so I can't dig around and verify it.
If the Report Builder button is not showing, verify the accessing account has Report Builder role or better.  Predefined SSRS Roles in 2008 R2

A: I can confirm that this feature is not available in the express edition - you will also not be able to create a report model.


Q: Using Formula Language to return column values I'm trying to return all values stored in the tNames variable.
Values exists in the field. The show multivalues as separate entries have been selected already but none of the names is returned.
Below is the sample code:
tNames := "";
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
tNames := tNames + ", " + @Implode(@GetField("ChecklistContact_" +
  @Text(n));",")
);
@Trim(tNames)

I dont know why its not returning anything, will appreciate your help.
The below returns only the contact with index 0, but I want to return all contacts in each document.
tCount := 0;
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
 tCount := tCount + @If(@GetField("ChecklistContact_" + @Text(n)) = ""; 0; 1)
);
@GetField("ChecklistContact_" + @Text(tCount))

Following comments from Richard the below return the required values, but will prefer not to hard code field name.
Is there any way of using for loop to return field names and values?
tNames := "";
tNames:= @GetField("ChecklistContact_1") : @GetField("ChecklistContact_2") : ... @GetField("ChecklistContact_7");
@Trim(tNames)

A: I don't believe that IBM's documentation says this explicitly, but I don't think @GetField works in column value formulas. The doc says that it works in the "current document", and there is no current document when the formula is executing in a view.
Assuming you know what the maximum number for N is, the way to do this is with a simple list:
ChecklistContact_1 : ChecklistContact_2 : ChecklistContact_3 : ... : ChecklistContact_N

If N is large, this will be a lot of typing, but you'll only have to do it once and copying and pasting and editing the numbers will make it go pretty quickly.

A: It might sound inelegant but, if you can, create a new computed field with your column formula in your form and then use that new field in your column. Also, from a performance standpoint you will be better off.

A: Maybe use your loop to create the list of fieldnames as Richard suggested, then display tNames


Q: Scala: expression's type is not compatible with formal parameter type trait Ingredient{}

case class Papperoni() extends Ingredient{}
case class Mushroom() extends Ingredient{}

trait ToppingDef[T] {
}

object PepperoniDef extends Serializable with ToppingDef[Papperoni] {
}

object MushroomDef extends Serializable with ToppingDef[Mushroom] {
}

class Oven[T <: Ingredient](val topping:ToppingDef[T]) {
}

class Pizza {
  def cook = {
    val topping =
      if(someCondition()) { PepperoniDef }
      else { MushroomDef}

    new Oven(topping) // <-- build error here
  }
}

I am using Scala 2.11.  This example is somewhat contrived but I’ve stripped out everything unrelated to the problem to provide a concise example.
The error I get on the last line is:
Error:(26, 5) no type parameters for constructor Oven: (topping: ToppingDef[T])Oven[T] exist so that it can be applied to arguments (Serializable with ToppingDef[_ >: Papperoni with Mushroom <: Product with Serializable with Ingredient])
 --- because ---
argument expression's type is not compatible with formal parameter type;
 found   : Serializable with ToppingDef[_ >: Papperoni with Mushroom <: Product with Serializable with Ingredient]
 required: ToppingDef[?T]
    new Oven(topping)

However changing the last line to this for example:
new Oven(PepperoniDef)

builds fine.  So the compiler has no problem finding the type when the parameter is passed explicitly like this.
Also, removing the Serializable trait from PepperoniDef and MushroomDef like this:
object PepperoniDef extends ToppingDef[Papperoni] {
}

object MushroomDef extends ToppingDef[Mushroom] {
}

also builds. However in my case I need the Serializable.
I think I can probably restructure the code to work around this if necessary but I would like to understand what's going on, I don't know why the type is ambiguous in the first case, or why the presence of the Serializable trait has any effect.  Thanks in advance for any insights.
EDIT: Thank you for the replies, very helpful.  I think the most concise fix is to change this:
val topping =

to this:
val topping:ToppingDef[_ <: Ingredient] =

Which cures the build error and does not require a change to the generic classes, which I would like to keep as simple an unannotated as possible so as to have Scala infer as much type information as possible.
This doesn't answer the question of why the presence of Serializable has any effect on this.

A: It seems that helping the compiler out with type annotation makes this compile:
val topping: ToppingDef[
    _ >: Papperoni with Mushroom <: Ingredient with Product with Serializable] =
    if (true) {
      PepperoniDef
    } else {
      MushroomDef
    }

I don't think this has to do with the Serializable class specifically, it seems like a compiler quirk to me since the produced type has a mixed in type including Product with Serializable anyway.
You can also "relax" the type signature by making T covariant, meaning Topping[Ingredient] will be inferred. This happens because the "is subtype of" relation Papperoni <: Ingredient on a covariant ToppingDef[+T] means ToppingDef[Papperoni] <: ToppingDef[Ingredient], thus allowing the common supertype for T:
trait ToppingDef[+T]
val topping: ToppingDef[Ingredient with Product with Serializable] =
  if (true) {
    PepperoniDef
  } else {
    MushroomDef
  }

And this also compiles without type annotation.
Edit:
Making Ovens type parameter an existential instead of a universally quantified type seems to work as well with the Serializable trait:
class Oven[_ <: Ingredient](val topping: ToppingDef[_])

val topping: Serializable with ToppingDef[_ <: Ingredient] =
  if (true) {
    PepperoniDef
  } else {
    MushroomDef
  }

new Oven(topping)

A: You need to add some type information to your trait:
trait ToppingDef[+T <: Ingredient] {}

Right now the topping variable is not able to figure out that T is supposed to be an Ingredient so you need to tell it.


Q: Pass string array to PHP script as POST I am trying to pass a string array to a PHP script as POST data in an Android app but i have an issue.
this is my client side code:
ArrayList<NameValuePair> querySend = new ArrayList<NameValuePair>();
for (Stop s : stops) {
                querySend.add(new BasicNameValuePair("stop_data[]", s.getNumber()));
            }
HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.myURL/myPHPScript.php");
                httppost.setEntity(new UrlEncodedFormEntity(querySend));
                HttpResponse response = httpclient.execute(httppost);

and this is my PHP script code:
foreach($_GET['stop_data'] as $stop) {
  // do something
}

If i run my java code i will get this response error from php script:
Warning: Invalid argument supplied for foreach() in /web/htdocs/www.myURL/myPHPScript.php on line 6
null

otherwise if i will put the request on my browser manully in this way:
http://www.myURL/myPHPScript.php?stop_data[]=768&stop_data[]=1283

i will give the correct answer!
if i try the same code, but if i POST not an array but a single string passing and receiving stop_data variables without [] it works!
I can't understand where is the mistake!! It is possible that the [] in BasicNameValuePair String name are doing some codification mistaken? I need to pass an array, how i have to do?

A: you use POST method and in php code you should use $_POST
try this
foreach($_POST['stop_data'] as $stop) {
  // do something
}

this way is using GET method
http://www.myURL/myPHPScript.php?stop_data[]=768&stop_data[]=1283


Q: Create a .htaccess file with the code for clean url I want to create clean url, so I tried many configurations.  I also created an .htaccess file but it does not work.  Anyone can help me?
My .htaccess code
Options +FollowSymLinks
RewriteEngine on
RewriteRule single-post/id/(.*)/title/(.*)/ single-post.php?id=$1&title=$2
RewriteRule single-post/id/(.*)/title/(.*) single-post.php?id=$1&title=$2

Present url
http://localhost/just2minute/story/single-post/id/2590/title/%E0%A4%95%E0%A5%87%E0%A4%B0%E0%A4%B2%20%E0%A4%AE%E0%A5%87%E0%A4%82%20%E0%A4%AC%E0%A4%BE%E0%A4%B0%E0%A4%BF%E0%A4%B6%20%E0%A4%94%E0%A4%B0%20%E0%A4%B2%E0%A5%88%E0%A4%82%E0%A4%A1%E0%A4%B8%E0%A4%B2%E0%A4%BE%E0%A4%87%E0%A4%A1%20%E0%A4%B8%E0%A5%87%2018%20%E0%A4%B2%E0%A5%8B%E0%A4%97%E0%A5%8B%E0%A4%82%20%E0%A4%95%E0%A5%80%20%E0%A4%AE%E0%A5%8C%E0%A4%A4/

I want to create"
http://localhost/just2minute/story/single-post/id/(Any Value)/title/(Any Value)/

A: You do not need two rules. You can achieve the goal using one rewrite rule, for example,
RewriteRule ^story/single-post/id/([0-9]+)/title/([0-9a-zA-Z-]+)/?$ single-post.php?id=$1&title=$2

After that you can access with the URL like this
https://localhost/just2minute/story/single-post/id/51835322/title/create-a-htaccess-file-with-the-code-for-clean-url

Then you want to do something like explained in this article:
https://www.tinywebhut.com/remove-duplicate-urls-from-your-website-38


Q: Modify path name when saving with PIL I am extracting RGB channels  from images and saving them as grayscale png files, but I have trouble saving them. Here is my code:
listing = os.listdir(path1)
for f in listing:
    im = Image.open(path1 + f)
    red, green, blue = im.split()
    red = red.convert('LA')
    green = green.convert('LA')
    blue = blue.convert('LA')
    red.save(path2 + f + 'r', 'png')
    green.save(path2 + f + 'g', 'png')
    blue.save(path2 + f + 'b','png')

Where path1 and path2 are image folder and save destinations respectively. What I want to do is to save the b&w version of color channel of img.png to
imgr.png, imgg.png, imgb.png, but what I get with this code is img.pngr, img.pngg, img.pngb. Any help would be appreciated.

A: You first need to split the filename from the extension.
import os
filename = path2 + f # Consider using os.path.join(path2, f) instead
root, ext = os.path.splitext(filename)

Then you can combine them correctly again doing:
filename = root + "r" + ext

Now filename would be imgr.png instead of img.pngr.

A: You could do this as follows:
import os

listing = os.listdir(path1)

for f in listing:
    im = Image.open(os.path.join(path1, f))

    red, green, blue = im.split()
    red = red.convert('LA')
    green = green.convert('LA')
    blue = blue.convert('LA')

    file_name, file_ext = os.path.splitext(f)

    red.save(os.path.join(path2, "{}r.png".format(file_name))
    green.save(os.path.join(path2, "{}g.png".format(file_name))
    blue.save(os.path.join(path2, "{}b.png".format(file_name))

I would recommend you make use of the os.path.split() and os.path.join() functions when working with paths and filenames.


Q: Putting $scope in Cytoscape click event I have created a network graph using Cytoscapejs. I am trying to unhide a div, and load more things after the user click on edge of the graph.
I have the following in my controller:
CytoscapeService.getGraph().on('tap', 'edge[id = "123"]', function (event) {

console.log("Hi")
//Above console printout works.

  //The below does not work on index.html
  $scope.testMessage = "Hello World";
  $scope.showMe = function () {
    $scope.show = true;
  }

  $scope.showMe();

});

// This works though.
//$scope.testMessage = "Hi from outside";

And in Index.html:

  {{testMessage}}

The console.log does get print out but the $scope.showMe with function inside isn't being called. However, if I move the scope outside of this clause, into the main clause of the Controller, it works.
Any there alternatives on how I can achieve this?

A: This is common with angular when you are  using jquery events to update a $scope value. You will have to manually triger a $scope apply:
$scope.$apply(function(){
    $scope.show = true;
});

Another solution would be to use Angular's $timeout
$timeout(function () {
    $scope.show = true;
});

See the documentation for $scope.apply() and more scope information.


Q: Flex how to format a date string when it could be two different formats I have a date field in flex and have the format set to YYYY-MM-DD.  As long as the user clicks the calendar pop-up it set's it that way.
However, I need to allow the field to be human enter-able so they can type in a date.
The problem is, most users want to type the format  MM/DD/YYYY.   I have a tool tip that shows the format, but how can I check the format and change it to the YYYY-MM-DD format, or do something else appropriate (alert?)?

A: Easy enough:
DateFormatter.parseDate(yourString);

As long as your string is somewhat of a standard format, it should work.


Q: how to use for loop in a JButton  public void init(GUI gui){
    // the class extends Jframe
   gui.setSize(1024, 700);
   gui.setPreferredSize(new Dimension(1024, 700));
   gui.setResizable(false);
   gui.setLocationRelativeTo(null);
   gui.setTitle("Student Management System");
   gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
   Admin_AllStudents_pnl=new JLayeredPane();
   Admin_AllStudents_pnl.setSize(1024,700);
   Admin_AllStudents_pnl.setLayout(null);
   Admin_AllStudents_pnl.setVisible(false);
   Admin_AllStudents_pnl.setOpaque(true);
  // Admin_AllStudents_pnl.setBackground(Color.white);

   String col[]={"ID","Name","Password","Cell","Adress"};
   DefaultTableModel tablemodel=new DefaultTableModel(col,0);
   All_Students=new JTable(tablemodel);

   view_all=new JButton("View_All");
   Admin_AllStudents_pnl.add(view_all);
   view_all.setBorder(null);
   view_all.setBounds(10,10,view_all.getPreferredSize().width,view_all.getPreferredSize().height);

   view_all.addActionListener(new ActionListener(){
       @Override

// Student and admin are both classes s gets an array list from the admin of all //the students.
//i need to display them in a table format so using for loop.
       public void actionPerformed(ActionEvent ae) {
        ArrayList<Student> s=new ArrayList<>();
        s=admin.AllStudent();
        System.out.println("size of s arraylist"+s.size());

       for(int i=0;i<s.size();i++)
       {
       String Ids=s.get(i).getId();
       String names=s.get(i).getName();
       String passwords=s.get(i).getPass();
       String cells=s.get(i).getCell();
       String adresss=s.get(i).getAdress();
       Object[] data={Ids,names,passwords,cells,adresss};
       tablemodel.addRow(data);
       }
       }

   });

  Admin_AllStudents_pnl.add(All_Students);

   gui.add(Admin_AllStudents_pnl);

only the for loop is not working whole code works fine without for loop every variable is already declared the code is about of 1000 lines so i cant upload all of it.


Q: System.Net.WebException on YoutubeExtractor when downloading a video Environment

*

*Windows 8.1

*Visual Studio 2017 Community

*C#

*WPF application

Issue

*

*YoutubeExtractor throws System.Net.WebException when downloading a video.

I got YoutubeExtractor by Nuget and it doesn't work. The VideoInfo object isn't null. I tried several videos on Youtube and the same exceptions popped up. I googled the issue and it didn't give me much help.
Here's the code.
var videos = DownloadUrlResolver.GetDownloadUrls(@"https://www.youtube.com/watch?v=M1wLtAXDgqg");
VideoInfo video = videos
    .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);

if (video.RequiresDecryption)
    DownloadUrlResolver.DecryptDownloadUrl(video);

var videoDownloader = new VideoDownloader(video, System.IO.Path.Combine("D:", video.Title + video.VideoExtension));

videoDownloader.DownloadProgressChanged += (sender_, args) => Console.WriteLine(args.ProgressPercentage);

videoDownloader.Execute(); // I got the exception here.

How can I solve this issue? Thanks.
EDIT : 2017/10/26 13:42 GMT
Alexey 'Tyrrrz' Golub's answer helped so much! I corrected his original code and here it is.
using YoutubeExplode;
using YoutubeExplode.Models.MediaStreams;

var client = new YoutubeClient();
var video = await client.GetVideoAsync("bHzHlSLhtmM");
// double equal signs after s.VideoQuality instead of one
var streamInfo = video.MuxedStreamInfos.First(s => s.Container == Container.Mp4 && s.VideoQuality == VideoQuality.Medium360);
// "D:\\" instead of "D:"
var pathWithoutExtension = System.IO.Path.Combine("D:\\", video.Title);
// streamInfo.Container.GetFileExtension() instead of video.VideoExtension (video doesn't have the property)
var path = System.IO.Path.ChangeExtension(pathWithoutExtension, streamInfo.Container.GetFileExtension());
// new Progress<double>() instead of new Progress()
await client.DownloadMediaStreamAsync(streamInfo, path, new Progress<double>(d => Console.WriteLine(d.ToString("p2"))));


Q: kotlin whereNotEqualTo doesn't work for a field that has null value in firestore

BJ document has a null value of the capital field which should have not taken by  whereNotEqualTo
 val citiesRef = db.collection("cities").whereNotEqualTo("capital", true)
    try {
        val documents = citiesRef.get().await()
        for (document in documents){
            Log.d(TAG,"${document.data}")
        }
    }catch (e:Throwable){
        Log.d(TAG,e.message.toString())
    }

This code is not working despite the documentation saying that

Note that null field values do not match != clauses, because x != null evaluates to undefined.

but after I altered the null value with true or false doesn't matter which one is chosen, the code works well. can somebody explain to me what is the problem I encountered?

A: When you are using the following query:
val citiesRef = db.collection("cities").whereNotEqualTo("capital", true)

It means that you are trying to get all documents in the cities collection where the capital field holds the opposite value of the Boolean true, which is false. So you'll only get the documents where the capital field holds the value of false. The above query is the same with:
val citiesRef = db.collection("cities").whereEqualTo("capital", false)

Since null, is not the negation of true, the documents that have the capital field set to null, won't be returned. And it makes sense since null is not a boolean type, not a string type, nor any other supported data types. Null represents "none" or "undefined" and it's a distinct data type and cannot be considered "not equal" to any other data type.
That's the same as the docs states:

Note that null field values do not match != clauses


Q: How to create mobile, tablet, desktop viewable web template I want to create same category two templates. First one for tablet, laptop and desktop viewable to any screen size and second one for mobile viewable to any screen size.
How can I create all device (mobile, tablet, laptop and desktop any screen size) viewable template?
I searched last two week in google to find out the above question answer but I unfortunately I don’t find any useful link. So please, anyone can help me giving above question answer (any useful link or details description). Thanks

A: Those kind of templates are really hard to find unless u pay fo them.
Just have a look on this :
http://mobile.smashingmagazine.com/2010/07/19/how-to-use-css3-media-queries-to-create-a-mobile-version-of-your-website/


Q: Get all changed files in a changest I want to get all the changed file in a changeset but without having the letter that specify the change type.
I know this command
hg status --change changeset

However, this return result like,
A /path/to/file
M /path/to/file

I want the result to be
/path/to/file

without "A" or "M". I tried to do it with regular expression and it used to work but I don't know it didn't work in one scenario.
The regular expression,
/(?<=[MA]\s).+/

This the scenario that did not work
arwa/Documents/Projects/firefox/M db << notice M here.

Any thought?

A: You should add ^ (start of line) to your regex:
/(?<=^[MA]\s).+/

If you don't do that, (?<=[MA]\s) will lookabehind the M part and .+ will catch db.

A: As of Mercurial 3.5, you can use templates (still an experimental feature, you can see it with hg help status -v). Namely:
hg status --change <rev> --template '{path}\n'

A: Why not use log with template?
hg log -r CSET -T "{files % '{file}\n'}"

will produce clean output
lang/UTF-8/serendipity_lang_ru.inc.php
plugins/serendipity_event_bbcode/UTF-8/lang_ru.inc.php
plugins/serendipity_event_emoticate/UTF-8/lang_ru.inc.php
plugins/serendipity_event_karma/UTF-8/lang_ru.inc.php
plugins/serendipity_event_s9ymarkup/UTF-8/lang_ru.inc.php
plugins/serendipity_plugin_shoutbox/UTF-8/lang_ru.inc.php

contrary to templated status
'lang\UTF-8\serendipity_lang_ru.inc.php
''plugins\serendipity_event_bbcode\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_emoticate\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_karma\UTF-8\lang_ru.inc.php
''plugins\serendipity_event_s9ymarkup\UTF-8\lang_ru.inc.php
''plugins\serendipity_plugin_shoutbox\UTF-8\lang_ru.inc.php
'


Q: App closes upon using BACKSPACE or SHIFT button in an EditText view When using the BACKSPACE or SHIFT of the onscreen keyboard to edit text in EditText views, my app closes (didn't have this problem before). It is possible to type in text, but as soon as I use BACKSPACE or SHIFT, the app closes.
Logcat gives the following alerts:
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)

Line 106 of Handler.java reads as follows;
handleMessage(msg);

Line 214 of Looper.java reads as follows;
if (logSlowDispatch) {
     showSlowLog(slowDispatchThresholdMs, dispatchStart,
     dispatchEnd, "dispatch", msg);
}

What action should I take to remedy this? Here is the full Logcat
    2019-09-09 16:46:12.416 13560-13560/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-09-09 16:46:12.417 13560-13560/? E/Zygote: accessInfo : 1
2019-09-09 16:46:23.608 13560-13560/com.commonsense.android.doorway E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.commonsense.android.doorway, PID: 13560
    java.lang.NoSuchMethodError: No static method dispatchUnhandledKeyEventPre(Landroid/view/View;Landroid/view/KeyEvent;)Z in class Landroid/support/v4/view/ViewCompat; or its super classes (declaration of 'android.support.v4.view.ViewCompat' appears in /data/app/com.commonsense.android.doorway-4nmhQXtmyOPwFjuoPHsunQ==/base.apk)
        at android.support.v7.app.AppCompatDelegateImpl.dispatchKeyEvent(AppCompatDelegateImpl.java:1162)
        at android.support.v7.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2529)
        at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:590)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:6094)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5949)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5402)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5455)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5421)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:5580)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:5429)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5637)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5402)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5455)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5421)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:5429)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5402)
        at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:8467)
        at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:8387)
        at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:8340)
        at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:5039)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7094)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)

And this is the build.gradle file. Android Studio says that mixing versions (like 28.0.0) in the dependencies can lead to bugs. Apparently they schould all be the same version. Could this be the problem source?
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.commonsense.android.doorway"
        minSdkVersion 25
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
    implementation 'com.google.code.gson:gson:2.8.2'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.android.support:wear:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:design:28.0.0-alpha3'
    compileOnly 'com.google.android.wearable:wearable:2.4.0'
}

When I detach the EditText views from their editText = findViewBy(R.id.editText), the error stops. But then of course the EditText views have become useless.

A: In the build.gradle file, I deleted implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'. Android Studio had warned in uncertain terms (as usual) that putting different versions in the dependencies "might produce some bugs". The said dependency was the first that could be deleted without causing any compile errors. And waddayou know, the backspace/shift bug disappeared immediately...


Q: Default Value Containing Special Characters in HTML Form I was trying to get a symbol like ® to be a default value for a text field,
I am trying to set the default by a javascript , but all i get is ® or &® in the text box, i am doing this from script as i am using drupal , so i dont have html files , i even trie ddefault value option in hook_form()

A: I'm not clear on what exactly you're trying to do; maybe something like this?
// set the default value of yourTextField
yourTextField.defaultValue = '\u00AE';

// or set the actual value of yourTextField
yourTextField.Value = '\u00AE';


Q: Make a table in ebook file I wanna make a book with parallel translation. It supposed to have table with to columns - one have text on source language, the other on target language.
I found, that I can do it easy with fb2, just write a xml code by python script. But my ebook read it ugly - the first column much wider than the second. (see picture)
Code example:

         Lang1
         Lang2

       ... the same ...

I don't work with web design, and maybe dont understand some simple thing. How can I set size of columns? Or maybe I should use some other format (epub)
It essential, that I need format, which I can read on ebook comfortable. Books in PDF format are bad for this, cause I can't change font and don't want zoom.
Thanks for you answers!

A: FB2 Supports reflow by design which is the reason for poor table support in many ebook readers as two column is contra the basic reflow principle.
Thus HTML can support tables but are not always "expected" nor supported well in many ebook readers.
Daisy epubtest "basic" did not include tables ! But they are tested in Accessibility: Non-visual Reading. Adobe fails the visual display by not adjusting the 4 cell contents to fit device, and fails on navigation.
MuPDF show the table as one column with cells reflowing to fit the page width, Calibre uses varying width columns but can also have issues.

If you need a fixed layout, then PDF was designed to maintain page layout, Thus the answer is probably use PDF with a page column and font size targeted to suit a pocket book such as A6, two column, no margins, 6pt.
If it is for your own use only, then ebook format targeted for your device, may well work if the columns are fixed to half screen width.


Q: Java Enumeration vs Iterator Enumeration doesn't throw ConcurrentModificationException , why?
See below code .
public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Enumeration<String> en=v.elements();

    while(en.hasMoreElements())
    {
        String value=(String) en.nextElement();
        System.out.println(value);
        v.remove(value);

    }

}

It only prints :

Amit
Pathak
Aron

Why is this such behavior . Can we say that Enumerator is thread safe.
Edit: When working with Iterator it throws ConcurrentModificationException in single thread application.
public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Iterator<String> it=v.iterator();
    while(it.hasNext())
    {
        String value=(String) it.next();
        System.out.println(value);
        v.remove(value);
    }
}

Please check.

A:
Enumeration doesn't throw ConcurrentModificationException , why?

Because there is no path in the code being invoked which throws this exception. Edit: I am referring to the implementation provided by the Vector class, not about the Enumeration interface in general.

Why is this such behavior . Can we say that Enumerator is thread safe.

It is thread-safe in a sense that the code executed is properly synchronized. However, I don't think the result your loop yields is what you would except.
The reason for your output is that the Enumeration object maintains a counter, which is incremented after every invokation of nextElement(). This counter is not aware of your invokation of remove().

A: the fail-fast behaviour which throws the ConcurrentModificationException is only implemented for the Iterator as you can read in
http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html

A: Concurrent modification here has nothing to do with threads.
Concurrency here simply means that you are modifying the collection while you are iterating over it. (In your example this happens in the same thread.)
Iterators and enumerations of collections can throw ConcurrentModificationException in this case, but don't have to. The ones that do exhibit fail-fast behaviour. Apparently, the enumeration of Vector isn't fail-fast.
Thread-safety obviously involves multiple threads somehow. Vector is thread-safe only in the sense that its operations (like add, get, etc.) are synchronized. This is to avoid non-deterministic behaviour when one thread is adding an element while at the same time another thread is trying to remove one for example.
Now, when one thread is structurally modifying your collection while another thread is iterating over it, you have to deal with both thread-safety and concurrent modification issues. In this case, and probably in general, it is safest not to rely on ConcurrentModificationException being thrown. It is best to choose the appropriate collection implementation (a thread-safe one for example) and avoid/disallow concurrent modification yourself.
Some iterators allow adding/setting/removing elements through the iterator itself. This can be a good alternative if you really need concurrent modification.

A: Note that ConcurrentModificationException has nothing to do with concurrency in the sense of multithreading or thread safety. Some collections allow concurrent modifications, some don't. Normally you can find the answer in the docs. But concurrent doesn't mean concurrently by different threads. It means you can modify the collection while you iterate.
ConcurrentHashMap is a special case, as it is explicitly defined to be thread-safe AND editable while iterated (which I think is true for all thread-safe collections).
Anyway, as long as you're using a single thread to iterate and modify the collection, ConcurrentHashMap is the wrong solution to your problem. You are using the API wrongly. You should use Iterator.remove() to remove items. Alternatively, you can make a copy of the collection before you iterate and modify the original.
EDIT:
I don't know of any Enumeration that throws a ConcurrentModificationException. However, the behavior in case of a concurrent modification might not be what you expect it to be. As you see in you example, the enumeration skips every second element in the list. This is due to it's internal index being incremented regardless of removes. So this is what happens:

*

*en.nextElement() - returns first element from Vector, increments index to 1

*v.remove(value) - removes first element from Vector, shifts all elements left

*en.nextElement() - returns second element from Vector, which now is "Pathak"

The fail-fast behavior of Iterator protects you from this kind of things, which is why it is generally preferable to Enumberation. Instead, you should do the following:
Iterator<String> it=v.iterator();
while(it.hasNext())
{
    String value=(String) it.next();
    System.out.println(value);
    it.remove(); // not v.remove(value); !!
}

Alternatively:
for(String value : new Vector<String>(v)) // make a copy
{
    String value=(String) it.next();
    System.out.println(value);
    v.remove(value);
}

The first one is certainly preferable, as you don't really need the copy as long as you use the API as it is intended.

A: Short answer: It's a bonus feature that was invented after enumeration was already there, so the fact that the enumerator does not throw it does not suggest anything particular.
Long answer:
From wikipedia:

Collection implementations in pre-JDK 1.2 [...] did not contain a
  collections framework. The standard methods for grouping Java
  objects were via the array, the Vector, and the Hashtable classes,
  which unfortunately were not easy to extend, and did not implement a
  standard member interface. To address the need for reusable
  collection data structures [...] The
  collections framework was designed and developed primarily by Joshua
  Bloch, and was introduced in JDK 1.2.

When the Bloch team did that, they thought it was a good idea to put in a new mechanism that sends out an alarm (ConcurrentModificationException) when their collections were not synchronized properly in a multi-threaded program. There are two important things to note about this mechanism: 1) it's not guaranteed to catch concurrency bugs -- the exception is only thrown if you are lucky. 2) The exception is also thrown if you misuse the collection using a single thread (as in your example).
So, a collection not throwing an  ConcurrentModificationException when accessed by multiple threads does not imply it's thread-safe either.

A: It depends on how you get the Enumeration. See the following example, it does throw ConcurrentModificationException:
import java.util.*;

public class ConcurrencyTest {
    public static void main(String[] args) {

        Vector<String> v=new Vector<String>();
        v.add("Amit");
        v.add("Raj");
        v.add("Pathak");
        v.add("Sumit");
        v.add("Aron");
        v.add("Trek");

        Enumeration<String> en=Collections.enumeration(v);//v.elements();

        while(en.hasMoreElements())
        {
            String value=(String) en.nextElement();
            System.out.println(value);
            v.remove(value);
        }

        System.out.println("************************************");

        Iterator<String> iter = v.iterator();
           while(iter.hasNext()){
              System.out.println(iter.next());
              iter.remove();
              System.out.println(v.size());
        }
    }
}

Enumeration is just an interface, it's actual behavior is implementation-dependent. The Enumeration from the Collections.enumeration() call wraps the iterator in someway, so it's indeed fail-fast, but the Enumeration obtained from calling the Vector.elements() is not.
The not-fail-fast Enumeration could introduce arbitrary, non-deterministic behavior at an undetermined time in the future. For example: if you write the main method as this, it will throw java.util.NoSuchElementException after the first iteration.
public static void main(String[] args) {

        Vector<String> v=new Vector<String>();
        v.add("Amit");
        v.add("Raj");
        v.add("Pathak");

        Enumeration<String> en = v.elements(); //Collections.enumeration(v);

        while(en.hasMoreElements())
        {
            v.remove(0);
            String value=(String) en.nextElement();
            System.out.println(value);
        }
    }

A: remove the v.remove(value) and everything will work as expected
Edit: sorry, misread the question there
This has nothing to do with threadsafety though. You're not even multithreading so there is no reason Java would throw an exception for this.
If you want exceptions when you are changing the vector make it Unmodifiable


Q: Access DataGridTemplateColumn content I have a WPF DataGrid templatecolumn that has a DataTemplate for an AutoCompleteBox from the wpf toolkit.  During RowEditEnding event and validation procedures, I am not able to see the content in the templatecolumn.
<DataGridTemplateColumn Header="Account Type" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <toolkit:AutoCompleteBox Text="{Binding Path='Account Type'}" Populating="PopulateAccountTypesACB" IsTextCompletionEnabled="True" BorderThickness="0" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        if ((value as BindingGroup).Items.Count == 0)
            return new ValidationResult(true, null);

        DataRowView row = (value as BindingGroup).Items[0] as DataRowView;

        if (row != null)
        {
            if (ValidateAccountName(row.Row.ItemArray[0].ToString()))
            {
                return new ValidationResult(true, null);
            }
            else
            {
                return new ValidationResult(false,
                    "Account Name must be between 1 and 100 Characters.");
            }
        }
        else
            return new ValidationResult(true, null);
    }

When I put a break point in my validation function after I create the DataRowView, the template column is empty.  How would I get its content?

A: For a start you have a space in the Path of your Binding for the AutoCompleteBox.Text property which I don't think is allowed.

A: After looking into this, it seems like it doesn't have anything to do with the DataGridTemplateColumn, but rather with the AutoCompleteBox from the Wpf Toolkit.  The AutoCompleteBox has been nothing but trouble for me ever since I started using it.  As a result, I decided to scrap it and use an Editable ComboBox instead.  The combobox is much cleaner and more simple to implement. Here is how my code now looks and the datarowview is able to see what the user types in the box:
<DataGridTemplateColumn Header="Account Type">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path='Account Type'}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox IsEditable="True" LostFocus="LostFocusAccountTypes" ItemsSource="{DynamicResource types}" Height="23" IsTextSearchEnabled="True"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

Code Behind (this.Types is an observable collection of strings)
    private void PopulateAccountTypes()
    {
        try
        {
            string accountQuery = "SELECT AccountType FROM AccountType WHERE UserID = " + MyAccountant.DbProperties.currentUserID + "";

            SqlDataReader accountType = null;
            SqlCommand query = new SqlCommand(accountQuery, MyAccountant.DbProperties.dbConnection);

            accountType = query.ExecuteReader();

            while (accountType.Read())
            {
                this.Types.Add(accountType["AccountType"].ToString());
            }

            accountType.Close();
            Resources["types"] = this.Types;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


Q: Wait for nested async calls to finish I have a series of nested async calls that need to finish before my code continues. Function save_part1 calls the sqlite database and returns the rows of interest. For each of those rows, I make an ajax call to a save them remotely.
From what I have read about promises and deferred, I have only seen them being used in the context of ajax calls. And on top of that, it makes my brain hurt.
Question: how do I wait until all the ajax calls have completed before starting save_part2?
function save()
{
    save_part1();
    //this should only happen after all the ajax calls from save_part1 are complete
    save_part2();
}
function save_part1()
{
    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM TABLE1", [],
            function (transaction, results) {
                for (var i = 0; i < results.rows.length; i++)
                {
                    var row = results.rows.item(i);

                    ajaxCall_item1(row);

                }
            }, errorHandler)
    });
}

function save_part2()
{
    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM TABLE2", [],
            function (transaction, results) {
                for (var i = 0; i < results.rows.length; i++)
                {
                    var row = results.rows.item(i);

                    ajaxCall_item2(row);

                }
            }, errorHandler)
    });
}

A: As long as you have ajaxCall_item returning the jQuery deferred object, you can have save_part1 return a deferred object, collect the returned promises into an array, call them with $.when and resolve the "promise" once all of the requests have completed. Then you will be able to write: save_part1().then(save_part2);. Here is an untested example:
function save() {
    save_part1().then(save_part2).fail(function(err) {
      // ohno
    });
}

function ajaxCall_item1(row) {
  return $.ajax({ ... });
}

function save_part1()
{
  var dfd = jQuery.Deferred();
  var promises = [];
  db.transaction(function (tx) {
    tx.executeSql("SELECT * FROM TABLE1", [],
      function (transaction, results) {
        for (var i = 0; i < results.rows.length; i++) {
            var row = results.rows.item(i);
            promises.push(ajaxCall_item1(row));
        }

        $.when.apply($, promises).then(function() {
          dfd.resolve.apply(dfd, arguments);
        });
      }, function(err) {
        dfd.reject(err);
      });
  });
  return dfd;
}


Q: How to find the list of indices of NaN values of a given column of a dataframe in python Say I have the following dataframe and I want to get the indices of NaN values in Column 'b'.
Input:
df = pd.DataFrame(np.array([[1, 2, 3 ], [ np.nan, 5, 6], [7, np.nan, 9], [7, np.nan, 9]]),
                   columns=['a', 'b', 'c'])

Output:
[2,3]

How can I do this? I would like to get the indices as a list.


Q: Show ActionBar with Centred Logo In ListActivity Trying to show an ActionBar with the app logo to the left, title of the screen centred and  menu icons to the right. The class below extends a ListActivity how can i go about doing this:
The method i have created was centerlogo(); See code extract below:
public class NewsActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        ListView list;
        String[] itemname = { "Bafana crash out of Afcon",
                "Mali and Guinea face ultimate lottery",
                "Orlando Pirates eye cup glory",
                "Ivory Coast advance to Afcon quarters",
                "Algeria qualify for Afcon quarter-finals",
                "Reflect on Afcon lessons - Mbalula",
                "Tovey preaches patience with Bafana",
                "SuperSport's Brockie harbours lofty goals" };
        Integer[] imgid = { R.drawable.bafana, R.drawable.mailguinea,
                R.drawable.orlando, R.drawable.ivorycoast, R.drawable.algeria,
                R.drawable.reflection, R.drawable.tovey, R.drawable.supersport, };

        CustomListAdapter adapter = new CustomListAdapter(this, itemname, imgid);
        setListAdapter(adapter);

         centreLogo();
    }

    private void centreLogo() {
        // TODO Auto-generated method stub
                 Drawable d = getResources().getDrawable(R.drawable.banner);
     android.app.ActionBar bar = getActionBar();
     bar.setBackgroundDrawable(d);
     bar.setDisplayShowTitleEnabled(false);
     bar.setDisplayShowCustomEnabled(true);
     // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
     bar.setCustomView(R.layout.news_view);
     bar.setDisplayShowHomeEnabled(true);
     bar.setIcon(R.drawable.icon);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public void readMore(View view) {
        Intent read = new Intent(NewsActivity.this, ReadMoreActivity.class);
        startActivity(read);
    }

}

I get the following error:
01-29 13:45:40.093: E/AndroidRuntime(15402): FATAL EXCEPTION: main
01-29 13:45:40.093: E/AndroidRuntime(15402): java.lang.RuntimeException: Unable to start activity ComponentInfo{platinum.platinumstars/platinumnews.NewsActivity}: java.lang.NullPointerException
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.app.ActivityThread.access$700(ActivityThread.java:150)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.os.Looper.loop(Looper.java:176)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at android.app.ActivityThread.main(ActivityThread.java:5279)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at java.lang.reflect.Method.invokeNative(Native Method)
01-29 13:45:40.093: E/AndroidRuntime(15402):    at java.lang.reflect.Method.invoke(Method.java:511)

A: I decided to go with  GareginSargsyan suggestion. The main problem was that i was trying to inflate the default android list, so i instantiated a new ListView ,
set the ContentView of the list view and the rest is history.
public class NewsActivity extends ActionBarActivity {
        ListView list;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_platinum_news_list);
            String[] itemname = { "Bafana crash out of Afcon",
                    "Mali and Guinea face ultimate lottery",
                    "Orlando Pirates eye cup glory",
                    "Ivory Coast advance to Afcon quarters",
                    "Algeria qualify for Afcon quarter-finals",
                    "Reflect on Afcon lessons - Mbalula",
                    "Tovey preaches patience with Bafana",
                    "SuperSport's Brockie harbours lofty goals" };
            Integer[] imgid = { R.drawable.bafana, R.drawable.mailguinea,
                    R.drawable.orlando, R.drawable.ivorycoast, R.drawable.algeria,
                    R.drawable.reflection, R.drawable.tovey, R.drawable.supersport, };

    //      CustomListAdapter adapter = new CustomListAdapter(this, itemname, imgid);
    //      setListAdapter(adapter);
            CustomListAdapter test = new CustomListAdapter(this, itemname, imgid);
            list = (ListView) findViewById(R.id.list);
            list.setAdapter(test);

             centreLogo();
        }

        private void centreLogo() {
            // TODO Auto-generated method stub
            Drawable d = getResources().getDrawable(R.drawable.banner);
            getSupportActionBar().setBackgroundDrawable(d);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            getSupportActionBar().setDisplayShowCustomEnabled(true);
            // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setCustomView(R.layout.news_view);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setIcon(R.drawable.icon);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu items for use in the action bar

             getMenuInflater().inflate(R.menu.newsmenu, menu);
                return true;
        }

        public void readMore(View view) {
            Intent read = new Intent(NewsActivity.this, ReadMoreActivity.class);
            startActivity(read);
        }

    }

A: Most likely, getActionBar() is causing the exception. Try using getSupportActionBar() instead.


Q: Prove device enrollment with MDM from an iOS App We want to make an iOS enterprise app that communicates with a server A - we also have our own MDM server as a separate solution which could communicate with the A server if needed. Q: How can the app securely prove to its server, with every request, that it is coming from a device that is enrolled with the MDM?
I thought there would be some UUID that the app could send together with a signed challenge to A. A would then comunicate with MDM server to validate. But seems impossible.

A: The MDM is supposed to handle this. You should not be required to check every request in the API to make sure it is secure. Airwatch, for instance, makes all of your applications downloadable only through their catalog and the agent or vpn system connects when the application is opened. If the user were to attempt to circumvent these limits it unenrolls their device and disallows access until a new enrollment code is issued by your tech department.


Q: Can I split compressed sql file using split linux command? If not, then any other method to do? I have a 30 GB compressed sql file (with extension .sql.bz2) and if I unzip it will become 300 GB. However due to disk space issue, I can't do the same.
Could I split the compressed sql file something like using split linux command?
I tried but with no success. Any other approach?
Thanks!

A: You might take a look at this question: split-files-using-tar-gz-zip-or-bzip2
I assume the reason you want to split it is to move it? And that you know you probably wont be able to import a small slice of the file into a database?


Q: how to switch image on slidepanellayout in android how to use image to show more & less in slidepanellayout in android.i am using demo application from this link,check this layout.xml
https://github.com/umano/AndroidSlidingUpPanel/blob/master/demo/res/layout/activity_demo.xml
if data hidden it has to show down icon & and when it expanded it has to show up icon