Q:

Efficient and fair way to evenly distribute multiple items with various quantities

I am developing small lottery games where the participant can win one of many gifts, each having various quantities. (The code is in PHP)
Simple scenario:
I have 5 types of gifts, 1000 in total, and am expecting 1000 participations.
What algorithm can I use to ensure that these 1000 gifts are distributed somewhat evenly. The time period doesn't matter.
Uneven: 2 drones given away first, then 10 tablets, etc...
| Title     | Quantity |
|-----------|----------|
| Drone     | 5        |
| Tablet    | 10       |
| Hotel     | 100      |
| Gift card | 200      |
| Coupon    | 685      |

More complex scenario:
I have the same gifts and gift quantities, but I anticipate 600 participations.
I wish for the drone, tablet, and hotel nights to be all given out by the 600th participation.
So there should be 400 (gift cards + coupons) left, and better if there's the same percentage left: 116 gift cards (200/685=29%) and 284 coupons (71%).
What I tried:
For the first scenario, I tried using these probabilities, and looping through the 5 gifts sequentially:
- Each gift has its own counter
- The gift's counter increases every time the gift is considered
- The gift is given if the gift's counter == originalQuantity
- The loop starts back from the drone when a gift is given
| Title     | Quantity | Probability                   |
|-----------|----------|-------------------------------|
| Drone     | 5        | 5/1000                        |
| Tablet    | 10       | 10/(1000-5)                   |
| Hotel     | 100      | 100/(1000-5-10)               |
| Gift card | 200      | 200/(1000-5-10-100)           |
| Coupon    | 685      | 685/(1000-5-10-100-200) = 1/1 |

This solution works, and by adding a coefficient to each gift (Drone, table and hotel must have 20% more chance to come out, and gift card and coupon 30% less chance), I could also handle the more complex scenario.
My question is: are there better, fairer, simpler ways to distribute these gifts ?
Edit 1: Even distribution would mean random, and have for example, after 20% of participation, have approximately 20% of each gifts given out (1 drone, 2 tablets, etc...)

A:

You can just do it like the lottery: shuffle and pick. It is possible that the same kind of item is picked two or more times, just as it is possible that sequential rolls with dice yield the same number, that's how random works :-)
For the case where a number of prizes should be drawn until the 600th draw, put all of these prizes in a list together with enough of the other prizes to make 600, then shuffle that list. Shuffle the remaining 400 and concatenate the shuffled lists.


Q:

AttachEvent of 0 is undefined

I want to automatically resize parts of my Website with the onchange-Event. But as always I got a little problem to solve.
Console gives this error:
The property undefined or a null reference can not be retrieved".
function Resize() {
    var winHeight = window.innerHeight;
    var winWidth = window.innerWidth;
    var startElements = document.getElementsByClassName('start');
    for (var i = 1; i <= startElements.length; i++) {
        document.startElements[i].attachEvent('onchange', function StartResize() {
        startElements[i].style.paddingLeft = winWidth * 0.1;
        startElements[i].style.paddingRight = winWidth * 0.1;
        });
    };
};

<body onload="Resize">

Last Thing. I already wrote the script-tag in my html document at the end of the body-tag.

A:

Remove document from document.startElements.
You are probably looking for Resize(). You forgot the () to invoke your function.
<body onload="Resize()">

However, inline JS (like onload in your html) has never been a good practice. Check out some of these results: Why is inline JS bad?
Instead, you should attach the event listener with JavaScript like this:
window.addEventListener('load', function() {
  //code here
});

Unless you want your code to only work in IE5-8, you need to use addEventListener not attachEvent, so that should be addEventListener('change',
I also wonder if you meant to start your loop on 1 rather than 0. The first element will be item 0. If you only have one item on the page, you are skipping it and starting with an item that doesn't exist.
So, also try:
for (var i = 0;


Q:

Use of the session parameter in shiny apps

As described in RStudio reference docs,
shiny server functions can optionally include session as a parameter (e.g. function(input, output, session)). The session object is an environment that can be used to access information and functionality relating to the session.
I never use this parameter in my apps and could be missing something.
What are the practical uses of the session parameter?

A:

Here is my attempt for an overview:
List of use cases:

Customised user interfaces
chat room
games
Javascript communication
Trigger a function when session is ended
global reactive values for modularised shiny apps
updating inputs

Trigger a function when session is ended
E.g. close a database connection, see
How to implement a cleanup routine in R Shiny?.
Stopping a shiny app when browser / session is closed:
How to stop running shiny app by closing the browser window?
Customising the user interface
The user interface will be dependent on the device from which its called.
Is it a mobile or pc, which screen resolution is used etc.
Using fluid pages in the ui will help, but certainly has there limits as well.
With session$clientData$output_{OUTPUT_ID}_height and session$clientData$output_{OUTPUT_ID}_width
you can track how your outputs are rendered for your user.
You could make live adjustments (dont insert my huge title if the plot is too small). Or you can track
the data and adjust your ui after finding the most common ui settings of your users.
User interactions
You can create a local/secret reactiveValue() within that session / for that user and you can set
reactiveValues() outside the server function for "global infos" that are accessible across users/sessions.
That way you can share infos across sessions, but also hide specific values for certain users.
Use Case example: Chat room
https://shiny.rstudio.com/gallery/chat-room.html
Use Case example: Games
Can R Shiny display different views for two simultaneous users, interacting with one another?
Share data between modules
As mentioned in the comment, there is a current open bounty where it is asked to have
global reactive values for modularised shiny apps.
See Shiny modules: Destroy module ui if server-function fails
and
https://appsilon.com/super-solutions-for-shiny-architecture-1-of-5-using-session-data/?nabe=4634331497365504:0.
Finally, there is Some functionality you indirectly use, since there are good wrapper functions / packages for that.
Sending messages to Javascript
(There are good wrappers for this. E.g. shinyjs package).
If you want to integrate javascript in your app and send a message from shiny to javascript you can do it with
session:sendCustomMessage().
See, e.g.
http://www.blog.rdata.lu/post/2017-09-16-communication-between-r-and-d3js/ and
https://shiny.rstudio.com/articles/js-send-message.html.
Updating inputs
You could use session$sendInputMessage(inputId, message) to update inputs.
But again there are already more convenient wrapper functions for this, e.g. updateTextInput().
But it´s interesting to keep in mind for inputs that dont have a helper function.
General overview:
https://shiny.rstudio.com/reference/shiny/latest/session.html


Q:

Singleton usage C++

Not quite sure whether this has been asked before.
Language is c++. I am writing a class with a number of data items that should have a static behavior, say a buffer of 1 KB that holds some data and should be shared for all objects. My boss ask me, why don't you write a singleton class and put all the data items inside it?
I have some bitter experiences with singleton and also recently I have googled "singleton is evil" and read a couple of articles. In SO also I read the same. So I was a little hesitant to use singleton in the above case, because I believe it is not really required there. So I asked my boss, will it be OK to have static data members for the required data items, instead of making the class singleton? But he is not giving me any clear answer and tells me, design patterns are there to make life easier, so what is the problem in using it. I don't want to argue with him. :)
I am not an OOP expert. So it will be helpful if somebody can comment on whose point make more sense [also whether both are wrong :)].
Thanks...

A:

A singleton is essentially nothing but some OO encapsulation around a global variable.
If you encapsulate your state in some class and just add that as a static member to the class that needs the info, you're not really doing much different from a singleton, just with at least two drawbacks:

You preclude sharing that state with other classes.
In the simple implementation, there's nothing to stop anyone from creating another instance of your new class. If that is semantically an invalid thing, you should not allow it in the code, and that means you have to write all that singleton functionality anyway.

Sure, Just slapping a bit of Singleton Magic on top of globals doesn't make the problems with global state go away, and in that sense, singletons are evil™. But there are cases where your model needs to have global state. Encapsulation is a good thing in those instances, since it allows you to control who modifies what, when, and how. You can make the singleton factory method only accessible to certain classes, for example.


Q:

Google Maps V3: Pass drag event on marker to map

I'm drawing multiple radius circles on my map with the following code:
function drawRadius(size){
  var circle = new google.maps.Marker({
    position: map.getCenter(),
    zIndex: 1,
    icon: {
        path: google.maps.SymbolPath.CIRCLE,
        scale: size,
        strokeOpacity: 0.65,
        strokeWeight: 4,
        fillColor: '#FEFCF3',
        fillOpacity: 0.08,
        strokeColor: '#efe8b2'
    },
    map: map
  });
}

This method is called multiple times with different size parameters, it results in the the following image:

Unfortunately, I can't move the map anymore, because - as far as I can tell - the events are now fired on the circles and not on the map.
How can I fix this? I just want to be able to normally drag/move the map.
Thank you!

A:

If you don't need to click on the circles (markers), set clickable: false on them, that prevents the markers from receiving mouse events.
From the documentation:

clickable boolean If true, the marker receives mouse and touch events. Default value is true.

function drawRadius(size){
  var circle = new google.maps.Marker({
    position: map.getCenter(),
    zIndex: 1,
    clickable: false,
    icon: {
        path: google.maps.SymbolPath.CIRCLE,
        scale: size,
        strokeOpacity: 0.65,
        strokeWeight: 4,
        fillColor: '#FEFCF3',
        fillOpacity: 0.08,
        strokeColor: '#efe8b2'
    },
    map: map
  });
}

proof of concept fiddle
code snippet:

var geocoder;
var map;

function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  for (var size = 100; size < 600; size += 100) {
    drawRadius(size);
  }
}
google.maps.event.addDomListener(window, "load", initialize);

function drawRadius(size) {
  var circle = new google.maps.Marker({
    position: map.getCenter(),
    zIndex: 1,
    clickable: false,
    icon: {
      path: google.maps.SymbolPath.CIRCLE,
      scale: size,
      strokeOpacity: 0.65,
      strokeWeight: 4,
      fillColor: '#FEFCF3',
      fillOpacity: 0.08,
      strokeColor: '#000000'
    },
    map: map
  });
}
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}


Q:

Should I implement user data sanitization/validation as middleware?

I'm reimplementing my user management system with Slim, and I'm trying to figure out where I should do user data sanitization/validation.  I've been reading about middleware, and I'm wondering if this is an appropriate way to implement data validation.
My plan for validation is to use a validation schema (a simple JSON file) for each request that contains some user data (i.e., forms).  However, different forms will obviously use different schema, and there may be some types of validation that cannot be handled by the schema alone.
Thus, any middleware I implement will have to decide which schema to use based on the route.  Plus, some routes will require additional validation logic beyond that represented in the schema.  This to me sounds like the wrong approach though - isn't middleware supposed to be fairly "generic", performing the same logic on every request/response?
Another approach would be to have some sort of validation object that I initialize in each route with the appropriate schema, and then into which I inject my Slim app.
Which would be the more sensible approach?

A:

Using global middleware doesn't make sense as you end up coupling every endpoint's parameter list together.
The two options I would consider are:

Implement as route middleware so that you can have different filtering/validation for each endpoint.
e.g.
function fooFilter() {
    // filter/validate GET variables here and set back into request.
}

$app->get('/foo', 'fooFilter', function () {
    // "controller" logic
});

The advantage of doing it this way is that your controller logic doesn't need to be cluttered up with validation stuff as that's already been done.
Filter/validate within the controller logic. The main advantage here is that you can more easily audit if a GET variable is being used without being filtered/validated first.


Q:

The background for the div does not fit from the left side and make an unwanted scroll

Hi guys I explain my problem in this image.

I use this code to make a background to the div
.intro .bg-img{
     position: absolute;
     background: green url('https://static.pexels.com/photos/7350/startup-photos.jpg');
     background-size: cover;
     background-position: center;
     background-repeat: no-repeat;
     width:100%;
     height:350px;
     z-index: -1;
     opacity: 0.5;
}

here is the all code
https://codepen.io/haithamsha/pen/LeVZVr

A:

Looking at your code you have CSS that applies a 1em padding to every div within the wrapper class.
To fix this you can apply padding: 0 !important; to your intro class.
.intro {
    grid-column: span 1;
    text-align: center;
    min-height: 350px;
    background-color: #fff;
    z-index: 1;
    position: relative;
    padding: 0 !important; /* Apply important here */
    margin: 0;
}

Or you need to remove the 1em padding from every div and be more granular with your padding.
.wrapper > div {
   /* background: #ddd; */
   padding: 1em; /*<-- Remove this*/
}

Hope that helps


Q:

Can the disks need to be formatted before cStor pool creation?

I have few SSD disks attached to my nodes.Shall I wipe disks used before for OpenEBS when I reuse them ? So should I do a format of this disk is needed?

A:

There is no need to format the disks before providing the cStor pool. As part of the creation, it clears the disks and use the entire disk part of zfs pool.


Q:

How to write a vulnerable moment without it seeming cliche or mushy?

So, I have a kinda loudmouthed character who's always the first to fight and first to go on the offensive (This is a fantasy, so she fights a lot.) But, later in the story, she comes across someone she truly fears, and finds that she must fight that person in order to free the townspeople of an oppressive ruler.
Thing is, I want her to have a moment when she's weeping on her bed, and the MC/her love interest comes to comfort her. Then again, I don't want (insert group here) screaming in criticism and tearing that scene apart.
My question is: How do I show her vulnerability, and have a comforting moment, and tease the romance, without being overly cliche or overboard?

A:

There is a trick for this in The Emotional Craft of Fiction.
It's called 'me centered narration.'
Essentially, you have the character express at length in narrative (protest too much) what she wants everyone to think about her, in this case the opposite attribute of what she is actually feeling.

He came into my room and I quickly wiped my eyes, before he could see my tears.
  I refused to show any vulnerability, I was nothing like the girls in town, who constantly needed help for the least little thing. That wasn't me.
"What's wrong" he asked gently.
"Nothing." I busied myself about the room, not looking at him, afraid
  that doing so would lead me to another melt down. Where had that come
  from? I wasn't a frail little girl who needed saving. I'd saved myself
  long ago--knew plenty well how to stay ahead of trouble.
...etc...
"All right," he said at last, "I'm glad you're okay."
He made to leave, and I said, "No, wait."

Of course if you did something like this it'd be in your style, which this isn't. I think what it might do for your case is to keep the screaming hordes from saying your girl character is acting out of character. Instead, the scene serves to deepen her character and show that she has inner conflict.

A:

Switch the bravery. For this scene, her love interest is the brave one. As always, create a conflict between them. First draft of a long example:

Marcie heard something, a gasp, and moved to the back of the house. She heard it again, from Lexi's room, and moved to the door. Crying. Muffled crying. It sounded like Lexi. Was she crying? She thought she should walk away, respect her privacy, but the thought of Lexi actually crying was too much. She opened the door and walked in.
Lexi jumped, wiping her eyes. "Get out. Get out of here!"
"You're crying. What happened?"
Lexi wouldn't meet her eyes, she turned her head to the side. "Nothing."
"No, something." Marcie took a slow step toward her.
Lexi stood and faced her, eyes red, then strode to meet her. She raised her voice. "I said, get out!"
Her fists were clenched. She was angry. Marcie felt herself flush, she almost turned and ran, but stood her ground. Her knees felt weak. Her voice trembled. "I won't. You don't cry. So something's really wrong, Lexi. Tell me what's wrong."
Lexi's expression changed, from anger to ... is it sorrow?
"I'm sorry," Lexi said. "I shouldn't scare you." She turned back and sat on the bed, then fell face first into the pillow. She didn't say anything else.
Marcie hesitated, then moved to sit on the bed beside her, and put her hand on Lexi's shoulder, which made Lexi twitch. "Tell me."
Lexi's voice was muffled through the pillow. "I'm afraid. I have to fight Petrovski, and I think he might kill me."
Petrovski. Holy shit. "Wow. That's a really good reason."
Marcie was silent, thinking. Lexi sat up, and looked at her, half amused. "You think so?"
Marcie's hand had fallen to her lap. "Well. I would cry."
Lexi sniffed. "You cry if you spill coffee on yourself."
"Coffee stains, and that was my favorite dress!"
Lexi nodded, and leaned left to gently bump into Marcie, then looked away toward the window. "I know. What do you do when you're afraid?"

Then, however her love interest comforts her, proceed.


Q:

CRUD in SalesForce1

Anyone have any examples of how to create a CRUD page in Visualforce salesforce1?
I have doubts on how to create an optimized page for mobile devices using Visualforce.
I utilize Rest Api?
RemoteAction?
Thank you

A:

CRUD/FLS is always enforced server side.

Within Apex Code (custom controller or controller extension) you can explicitly call the isAccessible(), isDeletable(), methods. If you are only using standard controllers then this check is performed for you by the standard controller and you don't need to do anything.
You can (in some cases) automatically force isAccessible/isUpdateable checks to occur by using outputField, inputField apex components within visualforce, or by using the visualforce renderif tag. e.g. renderif="{!ObjectType.Account.Accessible}".  For more complex operations (e.g. knowing whether you can perform a SOQL query against certain fields in the WHERE clause), you need to do the check in the Apex class.

Therefore in a Salesforce1 app, you would still do the check in your apex class that handles your remoting call. The same principle applies for Lightning apps.
In other words, the only difference between using visualforce components and using a client side library to render your data is that in the former case you can make simple CRUD checks in the visualforce components (option 2) but in the latter case you cannot. You must use option 1 only. This is because CRUD is enforced server-side.


Q:

Open csv to export resultset

I want to export the result set of the sql query to a csv file. I am using opencsv to export to csv file. I am using below code to achieve it.
ResultSet rs = statement.executeQuery(queryString);
CSVWriter writer = new CSVWriter(new fileWriter "testFile.csv"), '|',CSVWriter.NO_QUOTE_CHARACTER);
writer.writeAll(rs, true);

But the problem I face is, it automatically exports to the datatype of the Databse Column which is from resultset.
Example if I a column with datatype as float in datatype in csv file i see as 100.00 and for another column I see value as 2.041928E+8 for 204192800.
But I want to csv file to export to string type. The value as it as in DB.
Can someone has any idea how to export the resulttype to csv file with string datatype using opencsv? Any help will be really appreciated.

A:

And Another solution is,
create your custom ResultSet Wrapper with your real resultset (source) and call
Also, you can create your custom ResultSetMetaData Wrapper to response ColumnType has String.
    writer.writeAll(new MyResultSet(rs), true);

//Wrapper class

public class MyResultSet implements Resultset{

 public MyResultSet(Resultset source, Map<String, NumberFormat > formatters){
//setting constructor properties and you can read here SQL resultset Metadata to complete    formatters
}

 //.... you will implement all sql.Resultset methods

  //example to implements

 public String getString(String columnName){
    return formatters.get(columnName).format(source.getInt(columnName));
  }

 public ResultSetMetaData getMetaData(){
   return new MyResultSetMetaData(source);
 }

}

}
//
   public MyResultSetMetaData implements ResultSetMetaData{
 //will implement all ResultSetMetaData methods,

   //replace Numeric to String the column Type, then the value has retrieved by getString(column)
       public int getColumnType(int columnIndex){
  return Types.VARCHAR;

}
}


Q:

Cakephp value from array

I've read many similar topics here but not one helps me with problem.
i'm trying to get sections_id value from query in controller.
$query_id = "SELECT sections_id FROM sections WHERE name='".$table_name."'";
        debug($id = $this->Info->query($query_id)); die();

there is debug result
array(
(int) 0 => array(
    'sections' => array(
        'sections_id' => '14'
    )
)

)
and i tried in controller get value of id typing $id['sections']['sections_id'], or
$id['sections_id'] and many other types, nothing works. Do you have any idea ?

A:

use $id[0]['sections']['sections_id'] to access it


Q:

how to calculate the number of a rating in a data frame

suppose I have a data frame consist of 60 columns and 170 observations. The rating for each of the 60 variables is from 1-7. Now I want to calculate how many "5" are there in the data frame, how should I do that using R?

A:

> df <- sample(1:7, 10200, replace=TRUE) %>%
+     matrix(nc = 60, nr = 170)
>
> df %>% .[df == 5] %>% plyr::count()
  x freq
1 5 137


Q:

Collapsed mesh when rendering animated model loaded with Assimp in OpenGL

So I'm working on loading and rendering an animated model, I can render the mesh in its static position no problem as well as draw the animated bones with a debug lines.
Here is a short video illustrating the issue.
As you can see in the video, I've got the animated "stick-figure" displaying properly. The mesh over-top however appears to only be partially properly displaying.
As mentioned in the title, I'm using Assimp, and OpenGL.
On the model loading side of things I load in the Scene, traverse the nodes keeping there parent child rotation, identify the nodes which are bones and add the bone information to the nodes.
└───Scene
     ├───Camera
     ├───Armature
     │    └───Torso : [ ROOT_BONE ]
     │        ├───Chest : [ BONE ]
     │        │    ├───Neck : [ BONE ]
     │        │    │    └───Head : [ BONE ]
     │        │    ├───Upper_Arm_L : [ BONE ]
     │        │    │    └───Lower_Arm_L : [ BONE ]
     │        │    │        └───Hand_L : [ BONE ]
     │        │    └───Upper_Arm_R : [ BONE ]
     │        │        └───Lower_Arm_R : [ BONE ]
     │        │            └───Hand_R : [ BONE ]
     │        ├───Upper_Leg_L : [ BONE ]
     │        │    └───Lower_Leg_L : [ BONE ]
     │        │        └───Foot_L : [ BONE ]
     │        └───Upper_Leg_R : [ BONE ]
     │            └───Lower_Leg_R : [ BONE ]
     │                └───Foot_R : [ BONE ]
     └───Character: [ 1 MESH(ES) ]

Here's a diargem of my current models node structure.
Each of the nodes has a transform matrix, the ones with [ROOT_BONE]/[BONE] next to them also include an offset matrix.
To render the animated bones, I read in the animation key frames, construct the matrix for each "channel"(bone) based on the interpolated position rotation and scale values. When I multiply the animated matrices together (based on there parent hierarchy) I get the bone/join position in world space.(I don't appear to need to know any of the nodes transform matrices or the bones offset matrices to get this to render properly. (just multiply the animation matrix with its parent animation matrix)
To render the mesh, I've tried a few things, using just the matrices from the animation gives results similar to the video shown above however the torso is laying on the ground in-front of the debug skeleton, the arms/legs however are still displayed the same as the video. The results as seen in the video were achieved by multiplying the animation matrices by there respective bones, the result was then passed to the vertex shader.
uniform mat4 uModelViewProjection;
uniform mat4 uBones[100];

in vec4 aPosition;

in  vec4 aWeights;
in ivec4 aBoneIds;

void main(void) {
    mat4 skinMat =
    uBones[aBoneIds[0]] * aWeights[0] +
    uBones[aBoneIds[1]] * aWeights[1] +
    uBones[aBoneIds[2]] * aWeights[2] +
    uBones[aBoneIds[3]] * aWeights[3];

    gl_Position = uModelViewProjection * skinMat * aPosition;
}

Here is the relevant code for the vertex shader. I've tried a few different approaches here as well with the same results (or worse in some cases).
A few of the things I thought immediately upon seeing the strange "collapsed" vertices was perhaps the bone matrices were not being passed properly, I did log them to verify they are indeed being sent, and I also checked the shader uniform location handles to make sure they were found properly.
I'm assuming I'm missing a step somewhere or prehapse just going about something in the wrong order. I've been working on a hand full of different "tutorials" for this topic but they are all quite difficult to follow. (code is all over the place with not the greatest documentation and I'm unable to run any of it as all of the examples require different languages/pre existing frameworks, or its just plain broken.)
Additional Info:

The model I'm currently trying to load is a Collada (.dae) file.
I'm using the LWJGL bindings for Assimp and OpenGL.

A:

I've finally figured out the issue. When using ivec4 (or any other i prefixed datatypes) as attributes in OpenGL Shaders, you must use glVertexAttribIPointer rather than glVertexAttribPointer (note the I). If you do not specify this, the buffer data will be sent to the GPU as floats.


Q:

The equation $a^2 - 4b = 3$ has no integer solution

Prove that: $$a^2 - 4b \neq 3$$ for all integers $a$ and $b$.

I'm not sure how to find a way to prove this statement. Some help would be appreciated.

A:

Assume that it is true. So $a^2-4b=3$.
Case I :When $a$ is even. Then $a=2k$ where $k$ is an integer. Thus we have, $4(k^2-b)=3$. LHS is even and RHS is odd. Contradiction.
CaseII: When $a$ is odd. Then $a=2k+1$ where $k$ is an integer. Then, $(2k+1)^2-4b=3$, hence we have $2(k^2+k-b)=1$. Again LHS even, RHS odd. Contradiction.


Q:

Why shouldn't I destroy http session on user logout?

Is there any good reason not to simply destroy the HTTP session like:
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
session.invalidate();

instead of just deauthenticating the user and make sure to clean user data from the session scoped beans?

A:

You have to do both. Deauthenticating the user can depend on your implementation. If you call out to a third party system to obtain a security token for a user, chances are you have to call back again to invalidate the token.
You also have to invalidate the HttpSession. Invalidating the session will release all session scoped beans. It also releases JSF view states and component trees for pages visited during the user's session. These can make the session sizeable and not invalidating will leave the heap full of sessions waiting to timeout and that have a negative impact on the server's capacity.
BTW, you can invalidate the session without the need to obtain the HttpSession, like so:
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();


Q:

portlet jsp auto submit form without refresh page

In a jsp page I have this form:
<form name ="form1" id="form1" method="post" action=portlet:actionURL name=acao
input type="text" name="data" id="2">

and I use this to fil the form with data:
document.getElementById("2").value= lonlat;

I'm using document.getElementById("1").submit(); to auto submit the form but it auto refresh all the page but my intent is to auto submit without refreshing all the page.

A:

on submit you need to make Ajax call and in portlet class override the serveResource
In jsp or java script you can get resource url as
<portlet:resourceURL var="resourceURL">
 </portlet:resourceURL>

serveResource() method
@Override
          public void serveResource(ResourceRequest resourceRequest,
                    ResourceResponse resourceResponse) throws IOException,
                    PortletException {

     // do your stuff here

     }


Q:

C++ Sentiment Analysis Library

I'm looking for a C++ sentiment analysis library that I could use in my own application. Something that would take a text written by a human as an argument and return information on its mood (positive, negative, neutral, angry, happy, ...). Any ideas?
A few remarks:

I'm not looking for a library with "just" NLP tools (as text tokenization, PoS tagging etc.), but really something that does sentiment analysis / opinion mining / mood analysis. Of course an NLP library with sentiment analysis tool is great.
Something very simple would be ok (e.g. just returning +1/-1/0)
I don't care which underlying technique it may use (dictionaries, bayesian stuffs, SVMs, rule-based...)
C++ only!

I know it probably does not exist just like that, but hey.

A:

I'd suggest writing your own. You can capture 80% of mood correctly with a simple filter for positive and negative sentiment words, and you can scale your sign based on some common modal words and punctuation. If you want to squeeze juice out of that remaining 20% of ambiguity and you don't want to train your own SVM or whatever, I'd suggest finding papers at op.to/goog/scholar+ some of those papers will have authors who have written C++ libs and talking about where you can find / download them.
Also see this SO post among many others for more ideas.


Q:

Calling numeric JSON field-names

I'm using a simple REST API for a project and some of the data I need uses a numeric string as the top-level parent node. When attempting to call it in my javascript, it throws syntax errors.
here's the JSON object:

{"23497400":{"id":23497400,"name":foobar,"profileIconId":627,"revisionDate":1431385425000}}

and here's where I'm throwing the error:
var myArr = JSON.parse(xmlhttp.responseText);
var name1 = myArr.23497400.name;

There's definitely something terribly simple that I'm missing, right?

A:

You need to use bracket notation if the key is not a valid identifier name.
var name1 = myArr['23497400'].name;

When you use the dot notation,

property must be a valid JavaScript identifier, i.e. a sequence of
  alphanumerical characters, also including the underscore ("_") and
  dollar sign ("$"), that cannot start with a number. For example,
  object.$1 is valid, while object.1 is not.


Q:

Can I wire my under cabinet lighting in parallel?

Not sure if this is the appropriate place, or something like DIY. I have purchased 6 of these light bars from Amazon https://www.amazon.com/gp/product/B074NX7H1K/
The power supply is 6A and each bar takes .3A (4W / 12V). So the power supply should be sufficient.
I know that wiring in parallel each light will get 12V and reduce the current.
The light bar itself seems to be a set of 24 LED diodes with a resistor (hard to read the ohms through the frosted plastic) every 2-3 lights.
My plan is to wire nut them all together directly to the spliced end of the powered source, with a separate run for each light. Alternatively, I might create 3 'feeds' and then wire them in parallel in a set of 2. As far as I understand that is the same thing.
Are there any problems going this route? Will this suffer from thermal runaway or anything? If it does, how can I calculate what size resistor I would need before each light bar? If I don't put in a resistor, realistically how much would this reduce the life of the lights?
Please note that I am a layman and can't really understand electrical diagrams, but I will try my best.

A:

Three LEDs per resistor is a common arrangement for fixtures designed to be connected directly to 12V.
No external resistor is required.
Your plan to connect them all in parallel is correct. Just make sure that the total current (0.3A per fixture × 6 fixtures = 1.8A) doesn't exceed the capacity of the power supply.
The lamps can be "daisy chained" with one cable running from the power supply to the first lamp, then a cable from there to the next lamp, and so on. However, electrically, this is still a parallel connection across the power supply, not a series connection. Each lamp is still getting the full 12V.


Q:

Make 20 REST API calls in parallel and combined the data after all request is completed and display on screen using angularjs

I am working to develop a page which display the list of 20 product details using Angularjs & nodejs. I have REST API to get the data for each product separately. This is same service I use when I launch other page where I display the details of this product.
I am looking for solution so that in the angularjs client side code, I can make 20 hits to REST API and combine the data and then use the angularjs directive to display the list of 20 products in my page.
How can i make 20 REST API call in parallel to get the data, once client gets all the data back then combine it and then display in UI.
Currently I am making call one by one and combining the data. Following is code snippet that I am using. I don't like this approach as it seems not optimal at all.
ApplicationLoaderService.initializePageCache($scope, 'product_1', 'myPage', function (response) {
    updateCache('product_1', 'myPage', response);
    ApplicationLoaderService.initializePageCache($scope, 'product_2', 'myPage', function (response) {
        updateCache('product_2', 'myPage', response);
        ApplicationLoaderService.initializePageCache($scope, 'product_3', 'myPage', function (response) {
            updateCache('product_3', 'myPage', response);
            ApplicationLoaderService.initializePageCache($scope, 'product_4', 'myPage', function (response) {
                updateCache('product_4', 'myPage', response);
                ApplicationLoaderService.initializePageCache($scope, 'product_5', 'myPage', function (response) {
                    updateCache('product_5', 'myPage', response);
                    ApplicationLoaderService.initializePageCache($scope, 'product_6', 'myPage', function (response) {
                        updateCache('product_6', 'myPage', response);
                        ApplicationLoaderService.initializePageCache($scope, 'product_7', 'myPage', function (response) {
                            updateCache('product_7', 'myPage', response);
                            ApplicationLoaderService.initializePageCache($scope, 'product_8', 'myPage', function (response) {
                                updateCache('product_8', 'myPage', response);
                                ApplicationLoaderService.initializePageCache($scope, 'product_9', 'myPage', function (response) {
                                    updateCache('product_9', 'myPage', response);
                                    ApplicationLoaderService.initializePageCache($scope, 'product_10', 'myPage', function (response) {
                                        updateCache('product_10', 'myPage', response);
                                        //invoke callback
                                        if (initilizeApplicationCacheCallback) {
                                            initilizeApplicationCacheCallback();
                                        }

                                    });

                                });

                            });

                        });

                    });

                });

            });

        });

    });
});

//initialize product page cache
initializePageCache: function ($scope, code, pageName, callback) {
    //make server call
    Product.get(function (response) {
        //invoke callback
        if (callback) {
            callback(response);
        }
    });
}

//Following is code as angular resource
app.factory('Product', ['$resource', function($resource) {
        return $resource('/products/:id', {id: '@id'}, {update: {method: 'PUT', isArray: false}}
        );
    }]);

A:

What you need is $q.all
It works by stacking promises and succeeding when they're all ready. It takes an array of promises as it's parameter.
For example:
var promises  = [
  $http.get('/test'),
  $http.get('/test2')
]

$q.all(promises).then(results) {
    var testResult1 = results[1];
    var testResult2 = results[2];
});

A:

This is a cool trick I often use (with jQuery):
var requests = [], count = 20;

while (count--) {
    requests.push($.ajax(...));
}

$.when.apply($, requests).then(function () {
    // all requests are done, each response is passed as an argument
    var args = Array.prototype.slice.apply(arguments)
        response, i, len;
    for (i = 0, len = args.length; i < len; i++) {
        response = args[i];
        // do something with each response here
    }
});


Q:

How to write to Kafka from Python logging module?

I've got a large complex application that is heavily using the Python logging module.
I need to start getting these logs into a Kafka cluster, and need to ensure that I don't change the data along the way.
To me the ideal solution is to just create a new handler for Kafka - and allow the logs to go to both the old logging solution and kafka in parallel for a while.  Then eventually shut off the old logging handlers and just send to Kafka.
However, I don't see any kafka logging handlers - only kafka clients.  Adding a kafka client would mean tracking down every current logging call and adding a separate call to the new kafka client.  Getting identical results will be difficult.

A:

Handler implementation is really simple. Actually, setting up the environment took more time than implementing the handler.
The handler constructor accepts optional argument key. If it's provided, the messages written will be sent to a single partition specified by this key. If not provided, the messages will be distributed between servers on round robin basis.
I haven't tested it much, but it's so simple that I don't see what might go wrong here. Hope it will be useful.
from kafka.client import KafkaClient
from kafka.producer import SimpleProducer,KeyedProducer
import logging,sys

class KafkaLoggingHandler(logging.Handler):

    def __init__(self, host, port, topic, key=None):
        logging.Handler.__init__(self)
        self.kafka_client = KafkaClient(host, port)
        self.key = key
        if key is None:
            self.producer = SimpleProducer(self.kafka_client, topic)
        else:
            self.producer = KeyedProducer(self.kafka_client, topic)

    def emit(self, record):
        #drop kafka logging to avoid infinite recursion
        if record.name == 'kafka':
            return
        try:
            #use default formatting
            msg = self.format(record)
            #produce message
            if self.key is None:
                self.producer.send_messages(msg)
            else:
                self.producer.send(self.key, msg)
        except:
            import traceback
            ei = sys.exc_info()
            traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
            del ei

    def close(self):
        self.producer.stop()
        logging.Handler.close(self)

kh = KafkaLoggingHandler("localhost", 9092, "test_log")
#OR
#kh = KafkaLoggingHandler("localhost", 9092, "test_log", "key1")

logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
logger.addHandler(kh)
logger.info("The %s boxing wizards jump %s", 5, "quickly")
logger.debug("The quick brown %s jumps over the lazy %s", "fox",  "dog")
try:
    import math
    math.exp(1000)
except:
    logger.exception("Problem with %s", "math.exp")

P.S. The handler uses this Kafka client: https://github.com/mumrah/kafka-python

A:

This is an awesome fix, thank you! The code has been updated somewhat in the past few years and some functions are now deprecated. The overall design of this fix was very, very helpful though so thank you once again.
SimpleProducer (deprecated) --> KafkaProducer
SimpleConsumer (deprecated) --> KafkaConsumer

Here is my revised snippet using Kafka 1.0.0 and kafka-python 1.4.2 and just the producer because I'm consuming via logstash on the other end.
Hope this works for you!
tester.py (main routine)
# -*- coding: utf-8 -*-
"""Module to test out logging to kafka."""

import json
import logging

from utils.kafka_handler import KafkaHandler
from kafka import KafkaProducer

def run_it(logger=None):
    """Run the actual connections."""

    logger = logging.getLogger(__name__)
    # enable the debug logger if you want to see ALL of the lines
    #logging.basicConfig(level=logging.DEBUG)
    logger.setLevel(logging.DEBUG)

    kh = KafkaHandler(['localhost:9092'], 'sebtest')
    logger.addHandler(kh)

    logger.info("I'm a little logger, short and stout")
    logger.debug("Don't tase me bro!")

if __name__ == "__main__":
    run_it()

utils/kafka_handler.py (utility for logging)
# -*- coding: utf-8 -*-
"""Module to provide kafka handlers for internal logging facility."""

import json
import logging
import sys

from kafka import KafkaProducer

class KafkaHandler(logging.Handler):
    """Class to instantiate the kafka logging facility."""

    def __init__(self, hostlist, topic='corp_it_testing', tls=None):
        """Initialize an instance of the kafka handler."""
        logging.Handler.__init__(self)
        self.producer = KafkaProducer(bootstrap_servers=hostlist,
                                      value_serializer=lambda v: json.dumps(v).encode('utf-8'),
                                      linger_ms=10)
        self.topic = topic

    def emit(self, record):
        """Emit the provided record to the kafka_client producer."""
        # drop kafka logging to avoid infinite recursion
        if 'kafka.' in record.name:
            return

        try:
            # apply the logger formatter
            msg = self.format(record)
            self.producer.send(self.topic, {'message': msg})
            self.flush(timeout=1.0)
        except Exception:
            logging.Handler.handleError(self, record)

    def flush(self, timeout=None):
        """Flush the objects."""
        self.producer.flush(timeout=timeout)

    def close(self):
        """Close the producer and clean up."""
        self.acquire()
        try:
            if self.producer:
                self.producer.close()

            logging.Handler.close(self)
        finally:
            self.release()


Q:

Are the drum patterns in songs comprised of rudiments?

I've been trying to get some basic understanding of drumming. The first thing I came across is rudiments. Some have likened it to practicing scales for melodic instruments.
But I was wondering if like scales, do rudiments serve as a basis for the songs we hear everyday? Are songs comprised of combinations of drum rudiments? (and if not, then maybe they are not as important as scales?)

A:

Rudiments are compared to scales in the way that scales are an exercise for warming up your fingers, working on speed or getting certain motions in to your hands/fingers.
They can be used in the same way, as warmups, as speed exercises and to get certain aspects of technique down. Just like you might hear a scale run in a song or a partial scale run in a song you may very well hear parts or all of a rudiments in a song but that doesn’t mean a drummer will use strictly rudiments to make up all of his playing the same way you wouldn’t go to classical concert and have the pianist playing only scales.
Typical drum set rhythms are not derived from rudiments but certain fills can contain rudiments and there are certain simple rudiments such as a flam that are used extensively.
Drum Corp or marching band drummers will use rudiments a ton, especially the snare drum player. If you want to hear rudiments played at their finest check out some marching snare playing.

A:

Drum rudiments are really more about the technique of playing. How to stick. Scales can't really be seen in the same way. Rudiments came about as the building blocks of play - mainly if not exclusively on snare. Since drum playing is simpler than piano, for instance, given that with piano it's not only the duration (rhythm) but specific notes at the same time, it's important to be conversant with how each rudiment gets played, stick-wise. (If you dv me for that, please mention it in a comment - it's not meant in a derogatory way).
Scales could be seen as building blocks for melody instruments, but I feel they don't compare too well to drum rudiments.
So, in answer - not per se. The elements contained in them get used all the time - especially when playing drum breaks at the end of a line/verse/chorus. The rudiments themselves are small pieces of the jigsaw that drummers use when putting together a roll, etc. A drum pattern played while the singer is singing may contain a drag in each bar, or an occasional diddle, and often, several will be strung together, but scales; they're usually played bottom>top>bottom. So not comparable.


Q:

Trying to add an arraylist

Im adding all the numbers between 0 and 1000 which are multiples or 3 and 5. Im just having trouble adding them up. I keep on getting the error message: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 468, Size: 468
My Code
    //Multiple of 3 and 5 up to 1000
    int total = 0;
    int answer = 0;
    ArrayList<Integer> multof3 = new ArrayList<Integer>();
    for(int i =0; i <=1000; i++){

        if(i % 3 == 0 || i % 5==0){
            multof3.add(i);
            total++;

        }else{
            continue;
        }

    }

    System.out.println(multof3);
    System.out.println(total);

    //looping through array to get sum of elements
    for(int x =0; x <= multof3.size(); x++){
        answer= answer + multof3.get(x);
    }
    System.out.println(answer);

Anyone know the reason why? I cant understand why its not working. It prints out the arraylist so surely I should add the elements together...

A:

When looping through an array you have to keep in mind that it is indexed from 0.
  for(int x =0; x < multof3.size(); x++){
    answer= answer + multof3.get(x);
  }

If there are 468 items in the list then size() will return 468 but the last item is at index 467. Using the enhanced for loop can help avoid this type of problem:
  for(Integer i: multof3){
       answer += i;
  }


Q:

Change the color of moreNavigationController's icons

I've managed to change the navBar tint, the background color and labels' color using this.
But is it possible to change the icons' color?
(those left to tableview's labels)
Thanks!

A:

I don't know of a way to change the icon colors, but I don't really think all this hacking is necessary anyway - Apple certainly doesn't recommend it.
As far as I can tell, there is nothing special about the moreViewController, apart from being hard to customize. If it were me, I'd simply create my own custom viewcontroller, say MoreViewController, as a subclass of UITableViewController, add it to a NavigationController and then add that as the fifth and last item in the TabBarController. This table would then have a cell for each additional viewcontroller that I'd like to show. Then I'd be free to customize these cells to my heart's content.

A:

This is an old question, nevertheless I'll post a fairly reasonable solution I found.
I first tried setting the global tint color to what I wanted, but that didn't work. Luckily, simply changing the tint color of the table view did work. Adapting code from here:
let color: UIColor
// ...
if let moreTableView = moreNavigationController.topViewController?.view as? UITableView {
    moreTableView.tintColor = color
}

This still doesn't seem to affect the edit view controller, however.
EDIT:
There is actually a simpler way to do both, see this answer.


Q:

Dynamic Compiling of XAML - Linq Error

I have an XAML as String which i compile and then execute.
DynamicActivity workflowActivity = (DynamicActivity)ActivityXamlServices.Load(new StringReader(xaml));

This workflow has a Person object (Type: Namespace Workflow.Model.Person) as an input, so i pass the parameters and execute it.
Dictionary<String,Object> parameters = new Dictionary<String,Object>();

Workflow.Model.Person person = new Workflow.Model.Person();
person.FirstName = "John";

parameters["Person"] = person;

WorkflowInvoker.Invoke(workflowActivity, parameters);

I get the following exception:
[System.ArgumentException] = {"Property 'System.String FirstName' is not defined for type Workflow.Model.Person'"}
The error is thrown by System.Linq.Expressions.Expression.Property(Expression expression, PropertyInfo property).
I have tried many things without success. If i remove the access of property FirstName inside the workflow, it executes properly. Following advice i added the import of the references but it didn't work:
VisualBasicSettings.Default.ImportReferences.Add(new VisualBasicImportReference()
{
    Assembly = typeof(Person).Assembly.FullName,
    Import = typeof(Person).Namespace
});

Any input is appreciated.
Thanks.

A:

I found out the problem. The DLL containing the class Person was loaded two times into the AppDomain. So the compiled XAML was referencing a diferent instance of the same type and as such throwing this error.


Q:

Git commit hook for when editor closed

I have implemented a commit hook to check the commit message and abort the commit if the message isn't formatted correctly. I've done this with the commit-msg hook.
However, this will only work if you commit with the -m flag. If you omit that flag (because you want to use your editor to add the message), then the commit hook will fail (no message).
From what I have read, both the pre-commit and commit-msg hook are fired before the editor is opened. Is there a way to do something similar that waits for the editor to be closed?

A:

Actually, the commit-msg hook is fired once the message is ready (so, after the user closes the editor), this hook is getting a path to a file with the message value.
From the docs:

The commit-msg hook takes one parameter, which again is the path to a temporary file that contains the commit message written by the developer.


Q:

Android App Detect Other Activity

I've been trying to look up solution but I just can't seem to find one that suits my need. It could be that I'm not using the correct keyword, so I'm gonna try to explain it the best I can.
Simply saying, I'm building an Android application. The application need to detect some other activities on the phone and show some message.
For example:

User launch MyApplication.
User received some notification from another app. (a phone call, text message, email, whatever)
MyApplication shows a message via toast or dialog, saying that "you just received an notification from another app"

I'm not entirely sure what function I should be looking for here, any help is appreciated.
Thanks!

A:

You will want to look at NotificationListenerService, this will let you receive calls from the system when new notifications are posted or removed, or their ranking changed.
Once you receive a callback from the NotificationListenerService, you will want to create a Toast.
Take a look at this tutorial should help you get started.


Q:

set something on GUI form and thread sleep

I have a GUI window form. I want to set image to pictureBox and next sleep 3 seconds.
   pictureBox.Image = image;
   Thread.Sleep( 3000 );

But if I do it like my code above, my form try to set image, next go to sleep for 3 seconds, and just after that my form draws itself. So my picture show after this 3 seconds. How can I set image, show it and just after that "go to sleep" ?
edit 1
exactly I want to do something like that:
I have two thread, UI and GUI. UI reads from net socket and call right method from GUI. And can be script like that:

UI call on GUI: set image
UI call on GUI: do something (then GUI must clear image)

But I want to have sure, that I will be able to see this image. So after GUI set image, I call this thread for 3 seconds. So, how can I do it?
Example:
(function from GUI)
public void f1() {
     MethodInvoker method = () => {
            pictureBox.Image = image;
            pictureBox.Update();
           // do something more
     };

     if ( InvokeRequired ) {
           Invoke( method );
     } else {
           method();
     }

 }

public void f2() {
     MethodInvoker method = () => {
            pictureBox.Image = null;
            pictureBox.Update();
           // do something more
     };

     if ( InvokeRequired ) {
           Invoke( method );
     } else {
           method();
     }

 }

And other function f3...fn
 public void f3() {
     MethodInvoker method = () => {
           // do something
     };

     if ( InvokeRequired ) {
           Invoke( method );
     } else {
           method();
     }

 }

And, I my UI thread call function f1 and after it f2, I want to be sure that my user will be able to see this picture. But if my UI thread call function f1 and some between f3..fn call it normally.
edit 2
No I make it that:
I define function in GUI form (which is called by UI ):
  public void f1() {
         MethodInvoker method = () => {
                pictureBox.Image = image;
                pictureBox.Update();
         };

         MethodInvoker method2 = () => {
                // something
         }

        if ( InvokeRequired ) {
                Invoke( method );
                Thread.Sleep( 3000 );  // sleep UI thread
                Invoke( method2 );
        } else {
                method();
                method2();
        }
  }

It works, but it isn't the best solution. If will be script like this:
- UI call f1
- UI call f3

UI will be sleep for 3 seconds and I don't expect it.
What is the best solution for my problem?

A:

You should never let your GUI sleep. At least not the way you are doing. If you use Thread.Sleep or other blocking mechanisms you will prevent the UI from doing what it is suppose to be doing; dispatching and processing messages.
If you really want to cause a delayed action then you would be better off using a System.Windows.Forms.Timer. Here is what I think you need to do. This of course is based on my vague understanding of what you mean by "go to sleep".

Set your image.
Then immediately disable all of the controls necessary that simulates whatever "go to sleep" means for you.
Then start the timer.
Finally in the Tick event add code that reverses whatever "go to sleep" means for you.

A:

Try one of these:
Form.Refresh ();
Application.DoEvents;

Application.DoEvents
I'm assuming WindowsForms.


Q:

Updating the ListBox Items

I have a TreeView with nodes, so when I click on one of the nodes I will be updating the ListBox with items bounded to an Observable Collection, which works fine. Next when I click another node in my tree view I will have to update the ListBox with different data(which is also an Obsv.Collection). Any Ideas on how to proceed with this?
<Resources>
    <DataTemplate x:Key="clipsource">
        <StackPanel>
            <Image Name="img" Width="125" Height="70" Margin="1,0" Source="{Binding Path=Path, Converter= {x:Static l:UriToThumbnailConverter.Instance}}"/>
            <TextBlock FlowDirection="LeftToRight" FontFamily="Arial" FontSize="12" Text="{Binding Path = DisplayClipName}"/>
        </StackPanel>
    </DataTemplate>
</Resources>
<Grid  Height="Auto" Grid.Column="2" VerticalAlignment="Stretch"  x:Name="RightPane_grid" Margin="2,0,0,0" KeyboardNavigation.DirectionalNavigation="None">
    <Grid.RowDefinitions>
        <RowDefinition Height="21.205"/>
        <RowDefinition  Height="*"/>
    </Grid.RowDefinitions>
    <Rectangle  Fill="#FF232323" Stroke="#FF000000" RadiusX="3" RadiusY="3" Margin="0,0,0,0" x:Name="Right_Pane_bkg" Grid.ColumnSpan="1" Grid.RowSpan="2" KeyboardNavigation.DirectionalNavigation="None"/>
    <ListBox Name="ListBox1" SelectionMode="Extended" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" Grid.Row="0" Background="#FF3B3B3B"  Margin="2,25,2,2" ItemsSource="{Binding}" ItemTemplate="{StaticResource clipsource}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
</Grid>

Code Behind:
private void Handle_Click1(object sender, MouseButtonEventArgs e) // tree view Item
{
    ListBox1.DataContext = Clips Items;
    // Clips Items is an Obs v. Collection
}

I have a another Obs v Collection Still Items which I have to bound it to the List box to show another view

A:

You can try the following:
    <TreeView Name="MyTreeView">
        <TreeView.ItemContainerStyle>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="Header" Value="{Binding Path=Name}"/>
                <Setter Property="ItemsSource" Value="{Binding Path=SomeItems}"/>
            </Style>
        </TreeView.ItemContainerStyle>
    </TreeView>

    <ListBox ItemsSource="{Binding ElementName=MyTreeView, Path=SelectedItem.SomeItems}">
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Content" Value="{Binding Path=Name}"/>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

The Binding will retrieve the items displayed in the ListBox from the SelectedItem in the TreeView using the Path SomeItems. This assumes the SelectedItem is something like this:
public class MyTreeViewItem
{

    public string Name { get; private set; }
    public ObservableCollection<MyTreeViewItem> SomeItems { get; private set; }

    public MyTreeViewItem(string name)
    {
        if (name == null)
            throw new ArgumentNullException("name");

        this.SomeItems = new ObservableCollection<MyTreeViewItem>();
        this.Name = name;
    }

}

When you select an item in the TreeView the children are displayed in the ListBox.
Edit:
To populate the TreeView use the following code:
        MyTreeViewItem a = new MyTreeViewItem("A");
        a.SomeItems.Add(new MyTreeViewItem("A1"));
        a.SomeItems.Add(new MyTreeViewItem("A2"));
        a.SomeItems.Add(new MyTreeViewItem("A3"));

        MyTreeViewItem b = new MyTreeViewItem("B");
        b.SomeItems.Add(new MyTreeViewItem("B1"));
        b.SomeItems.Add(new MyTreeViewItem("B2"));
        b.SomeItems.Add(new MyTreeViewItem("B3"));

        this.MyTreeView.ItemsSource = new MyTreeViewItem[] { a, b };


Q:

How to access source code in bitbucket using REST API?

How to access a java file which is sitting in repo in a specific package.
Bit bucket has meta data info like pullrequest api,last commit REST APIs.
can you suggest/help me with sample rest call and also how to pass username and password? given that I know fully qualified class name including project.
note: we are using bitbucket which hosted with our organization.
Ex: https://bitbucket.org/repo/my-project
branch: tempBranch
file:src/main/java/temp/Main.java
I would like to access/view full content on Main.java with in the Rest call.
is there  any REST api exist for this ?

A:

Strangely there is no way to do this using the latest version (2.0) of the bitbucket.org (cloud) API.
The available data from the /repositories/{username}/{repo} endpoint may lead you to somewhere.
You can access files in the 'downloads' of your repo using the /repositories/{username}/{repo}/downloads/{filename} endpoint.

However There is an endpoint for what you need in version 1.0 of the API. Based on testing this still works.


Q:

asp.net mvc jquery clientside validation for dynamic forms

ok i have a complete form in my database  as row for example name of the field ,is mandatory, sortid, regularexpression, datatype, maxlength , default value etc. So the form is completely dynamic.
now i want to perform the client side validation on the form . What will be the best practice for doing that? like i have to see that if the field is mandatory check it for null and if not then leave it on the client side . i am thinking about setting hidden field for it .
can u guys guide me better in this scenario.

A:

You could dynamically construct javascript to test this form on client. Or you could use jquery.validate plugin and do right mark-up of your html.


Q:

How to get multidimensional length - of one axis

I have an array such as
 string[,] SSISVariableNameValue = new string[,]
            {
            {"DestinationConfigDB","dest db"},
            {"DestinationServer","dest server"},
            {"SourceConfigDB","source db"},
            {"SourceServer","source server"},
            {"SSISConfigFilter","filter"}
            };

The .length property is listed as 10.  How can i get the 'x' axis of this array..aside from dividing by 2?

A:

An array has a Rank property to tell you the number of dimensions and a GetLength(int d) function to give you the size in a specific dimension. d = 0 .. Rank-1
So you want SSISVariableNameValue.GetLength(0);


Q:

StructureMap DI on Model Assembly

I’m new to Dependency Injection and had a question/need guidance.
I had an application that used the repository pattern for data access. I used StructureMap to get the correct repository and all worked well.
I have since broken out my model (including the repository logic) into its own assembly and added a service layer. In the interest of DI the service layer class takes an IRepository in its constructor. This seems wrong to me as now all consumers of my model need to know about the repository (at least configure their DI to know which one to use). I feel like that is getting into the guts of the model.
What sounds wrong with this?

A:

An application written to use dependency injection typically configures a single container instance where all the interface/implementation type mappings have been registered at an initialization stage of the application.  This would include the registration of the repositories, services, and any consumers of the service within the application.
By resolving the consumers of the service through the container, consumers need only indicate their dependency upon the service, not any dependencies the service might need.  Therefore, the consumers of the service will not be coupled to its dependencies (e.g. your repository).  This is the benefit of doing dependency injection through a container as opposed to doing manual dependency injection.
If you are designing services to be consumed by other applications in the form of a reusable library then your options will vary depending on the level of flexibility you wish to offer.
If you presume all clients of your library will be using dependency injection, then you will need to provide an appropriate amount of documentation about what types need to be registered within their container.
If you presume all clients will be using a specific container (e.g. StructureMap), then you can ease the registration requirements by providing registries which encapsulate all the specific registration needs for the client.
If you wish to allow your library to be used by clients not using their own dependency injection container then you can provide a static factory which returns the service.  Depending on the level of complexity, such a scenario may not require use of a container (for example, if your service is comprised by just a few objects in all).  If your library is comprised of a substantial amount of components which need to be composed then you might have factories which resolve the services through their own shared internal infrastructure initialization needs.


Q:

Sleep specific Ticks

I need a function that waits for a specified number of DateTime.Ticks (about 155 000). Unfortunately, it works with the following function not really (waited about 300 000 ticks):
private void sleep_ticks(long t)
{
    long _start = DateTime.Now.Ticks + t;
    int i = 0;

    do
    {
        i++;
        Console.WriteLine((DateTime.Now.Ticks - _start) + " => " + i);
        if (DateTime.Now.Ticks >= _start)
            break;
    } while (true);

    Console.WriteLine((DateTime.Now.Ticks - _start) + " < " + t + " -- " + i);
    Console.ReadLine();
}

I added some debug output :-)
The last value would have to be close to 0.
Here is the output for sleep_ticks (1):
-1 => 1; -1 => 2; -1 => 3; -1 => 4; -1 => 5; -1 => 6; -1 => 7; -1 => 8; -1 => 9; -1 => 10;
-1 => 11; -1 => 12; -1 => 13; -1 => 14; -1 => 15; -1 => 16; -1 => 17; -1 => 18; -1 => 19;
-1 => 20; -1 => 21; -1 => 22; -1 => 23; -1 => 24; -1 => 25; -1 => 26; -1 => 27; -1 => 28;
-1 => 29; 156262 < 1 -- 29;

Does anyone have any idea why this might be, or how to fix it?
Thanks and regards
Robert

A:

Use Thread.Sleep
System.Threading.Thread.Sleep(new TimeSpan(155000));

A:

"I need a function that waits for a specified number of DateTime.Ticks." This is not possible.
Use System.Threading.Thread.Sleep(int millisecondsTimeout) for waiting accuracy gauged in milliseconds.
// Puts the current thread to sleep for 15 milliseconds.
System.Threading.Thread.Sleep(15);

It should be noted regarding the accepted answer (https://stackoverflow.com/a/23134395/3076020) that Thread.Sleep(TimeSpan) disregards fractional milliseconds.
"This overload of Sleep uses the total number of whole milliseconds in timeout. Fractional milliseconds are discarded." As documented here: https://msdn.microsoft.com/en-us/library/274eh01d(v=vs.110).aspx
This means that half a millisecond will be disregarded in the minimum time period to wait when providing Thread.Sleep 155000 ticks utilizing a TimeSpan. There are 10000 ticks in a single millisecond, therefore 155000 ticks = 15.5 milliseconds. While this may not have much impact in this scenario where 15 milliseconds is being waited. It may have an impact in a scenario where ticks or some measure more accurate than milliseconds is actually desired. This is why in this case I suggest for clarity using the integer (millisecond) overload.
If using milliseconds is not applicable I suggest looking into spinning the thread. Meaning keeping it active/busy repeatedly checking a suitably high-resolution timer between calls. Even this is prone to giving inaccurate results as the operating system may schedule another thread of higher priority, thus skewing the timing.

Be aware Thread.Sleep is the minimum time to keep the thread off of the scheduler, kept from processing, sleeping. The thread may end up "waiting" to resume processing longer than specified. This answer provides a bit of clarity on why Thread.Sleep isn't always precisely the time specified. https://stackoverflow.com/a/6254753/3076020
Reference information regarding that a single millisecond is 10,000 ticks. I believe this is standard in .NET and cannot be changed.
https://msdn.microsoft.com/en-us/library/system.timespan.tickspermillisecond(v=vs.110).aspx


Q:

Building a string parser for user command and control?

My goal is to build a command parser that has basic syntax and multiple possible branches at each point. These commands come from users of the system and are text input (no GUI). The basic syntax is base_command [sub_command [optional_parameters]], where optional_parameters is a space seperated list of parameters.
Examples:
add event "Program-a-thon"
add notification program-a-thon meeting
add pattern "follow the white rabbit"
remove event "Program-a-thon"
remove notification meeting
remove pattern "follow the white rabbit"
edit pattern "follow the white rabbit" "follow the white tiger"
reload settings

As you can see, I have 4 base commands (add, remove, edit and reload). However, I anticipate adding more in the future. I also have 4 subcommands (event, notification, pattern and settings). However, edit only has 1 subcommand and settings only applies to the reload base command. Not all subcommands are associated with all base commands. Finally, I have parameters. For simplicity, I am planning on making these position based.
I am writing this application in Python (utilizing the 2.7 branch).
So far, I've come up with this:

Utilize the .split() command and take the first two results to get the command and base command. The third index (if it exists) will be the positional arguments.
OR
Utilize a regular expression to get the base command and sub-command. The third index will be positional arguments.

Then utilizing this information, look at a dictionary like this to see if the command/sub-command option is viable. If it is, call the method described in the commands[base_command][sub_command]['method'] key to perform my action.
The upside of this is that I can easily tell if the command/subcommand combination is valid. The downside is maintaining such a dictionary and possibly extending it if I wish to add more options or information. For just these few commands I already have a dictionary like this (with some supporting attributes)
commands =
{
    'add' :
    {
        'help_text' : "Add a `event`, `notification`, or `pattern`",
        'sub_commands': {
                'event' : {
                    'help_text' : "Add an event",
                    'method' : "add_event",
                    'permissions' : 'trusted',
                },
                'notification' : {
                    'help_text' : "Recieve a notification for events that are tagged with the values you wish (tag1 [,tag2[,tag3[,tag4]]])",
                    'method' : "add_notification",
                    'permissions' : 'all',
                },
                'pattern' : {
                    'help_text' : "Add a pattern you wish the system to watch for in new event descriptions",
                    'method' : "add_pattern",
                    'permissions' : 'all',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
    'remove':
    {
        'help_text': "Remove a `event`, `notification`, or `pattern`",
        'sub_commands': {
                'event' : {
                    'help_text' : "Remove an event",
                    'method' : "remove_event",
                    'permissions' : 'trusted',
                },
                'notification' : {
                    'help_text' : "Remove a notification for specific tags (tag1 [,tag2[,tag3[,tag4]]])",
                    'method' : "remove_notification",
                    'permissions' : 'all',
                },
                'pattern' : {
                    'help_text' : "Add a pattern you wish the system to watch for in new event descriptions",
                    'method' : "remove_pattern",
                    'permissions' : 'all',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
    'edit':
    {
        'help_text': "Edit an existing `pattern`",
        'sub_commands': {
                'pattern' : {
                    'help_text' : "Edit a pattern pattern to watch for in new event descriptions (old_pattern, new_pattern)",
                    'method' : "edit_pattern",
                    'permissions' : 'all',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
    'reload':
    {
        'help_text': "Reload application options",
        'sub_commands': {
                'settings' : {
                    'help_text' : "Reload the settings of the application",
                    'method' : "reload_settings",
                    'permissions' : 'owner',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
}

My questions are, how do I properly design the parser so that I can

Extend the command tree easily in the future?
Have a combination of sub-commands that may or may not apply to all base commands?

And

Is utilizing a dictionary, like above, worth the hassle of maintenance when adding commands? I realize that commands will be 'relatively' stable (once added, modifications will be rare to the dictionary itself). However, when I do add them, they will probably come in at least pairs (add and remove), meaning the potential for messing up the dictionary occurs in multiple places.

A:

Have a look at the Python argparse and cmd modules. If you'd like to make an interactive UI, subclass cmd.Cmd and for each of the commands, you can use argparse to parse the subcommand and options.
import readline # for history and autocomplete
import cmd

class MyShell(cmd.Cmd):
    def do_add(self, line):
        "adds various things"
        print "add called with arguments", line # here you can use argparse on line

>>> MyShell().cmdloop()
(Cmd) xyz
*** Unknown syntax: xyz
(Cmd) help

Documented commands (type help <topic>):
========================================
add  help

(Cmd) help add
adds various things
(Cmd) add
add called with arguments
(Cmd) add 1 2 3 4
add called with arguments 1 2 3 4
(Cmd)


Q:

Chrome SameSite: Identity Server 4 (Code flow) + Web API Core 3.1 + Angular 8

Our application is the following:

Identity.Web (localhost:5555) - .Net Core 3.1: it has razor pages for login and password reset. We are using Identity Server 4 (Code flow - Oauth 2.0, OpenId).
Web.Api (localhost:4500)  .Net Core 3.1: basically has the resource APIs
Angular 8 (localhost:4200): using open-id client to authenticate and access the resource APIs.

Our application used to work perfectly prior to the Chrome SameSite Updates. Now, whenever we input the username password and login (Identity.Web - localhost:5555), the browser redirects to (Angular 8 - localhost:4200), then back directly to login page.
Before, there used to be an auth-callback, then login to dashboard.
You can find below our configuration:
Identity.Web (config.cs)
        var redirectUris = new List<string> { frontendUrl + "/auth-callback", frontendUrl + "/silent-refresh.html" };

        var allowedCorsOrigins = new List<string> { frontendUrl };

        var postLogoutRedirectUris = new List<string> { frontendUrl + "/signout-callback-oidc" };

        return new List<Client>
        {
           new Client
           {
                RequireConsent = false,
                ClientId = "angular_spa",
                ClientName = "Angular 4 Client",
                AllowedGrantTypes = GrantTypes.Code,
                RequirePkce = true,
                RequireClientSecret = false,
                AllowedScopes = new List<string> {"openid", "profile", "api1"},
                RedirectUris = redirectUris,
                PostLogoutRedirectUris = postLogoutRedirectUris,
                AllowedCorsOrigins = allowedCorsOrigins,
                AllowAccessTokensViaBrowser = true,

           }
        };

Identity.Web (Startup.cs)
 var settings = Configuration.GetSection(nameof(MongoDbSettings)).Get<MongoDbSettings>();

        var mongoDbContext = new MongoDbContext(settings.ConnectionString, settings.DatabaseName);

        services.AddIdentity<ApplicationUser, MongoIdentityRole>()
                .AddMongoDbStores<ApplicationUser, MongoIdentityRole, Guid>(mongoDbContext)
                .AddDefaultTokenProviders();

        services.Configure<MongoSettings>(options =>
        {
            options.ConnectionString = Configuration.GetSection("MongoDbSettings:ConnectionString").Value;
            options.DatabaseName = Configuration.GetSection("MongoDbSettings:DatabaseName").Value;
        });

        services.AddIdentityServer(options => { options.Events.RaiseSuccessEvents = true; })
                .AddDeveloperSigningCredential()
                .AddAspNetIdentity<ApplicationUser>()
                .AddProfileService<ProfileService>()
                .AddMongoRepository()
                .AddClients()
                .AddIdentityApiResources();

Web.Api (Startup.cs)
services.AddAuthentication()
                  .AddIdentityServerAuthentication("api1", options =>
                  {
                      options.Authority = Configuration.GetSection("IdentityServer:BaseUrl").Value;
                      options.RequireHttpsMetadata = false;
                      options.ApiName = "api1";
                      options.TokenRetriever = (request) =>
                      {
                          string token = TokenRetrieval.FromAuthorizationHeader().Invoke(request);
                          if (string.IsNullOrEmpty(token))
                          {
                              token = TokenRetrieval.FromQueryString().Invoke(request);
                          }
                          return token;
                      };
                  });

Note: Everything works perfectly in Firefox. We read this article, and applied what's there, but it didn't work.

A:

You will get below console warring in Google Chrome and your Identity server failed to redirect to Client App for Chrome version 80.
A cookie associated with a resource at was set with SameSite=None but without Secure. It has been blocked, as Chrome now only delivers cookies marked SameSite=None if they are also marked Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5633521622188032.
To Fix this , you need to do changes mention in below link with additional changes mention below.
https://www.thinktecture.com/en/identity/samesite/prepare-your-identityserver/
NOTE : For .Net Core 2.2 , set SameSite = (SameSiteMode)(-1) , For .Net Core 3.0 or above , set SameSite = SameSiteMode.Unspecified
Also , for Chrome 80 version , add this extra condition -
 if ( userAgent.Contains("Chrome/8"))
            {
                return true;
            }

Please accept this answer if it is fixed issue for Chrome.


Q:

UTF16 stored string doesn't match once retrieved back from CoreData

So I am using CoreStore to save a string identifier in CoreData.
The string may have some Swedish UTF16 characters. Inspecting from the debugger console:
> po identifier
"/EXTERNAL/Gemensam RUN/FileCloud Test/Test folder åäö/Test with Swedish characters - åäö.xlsx"

Immediately after being saved back to CoreData:
>po record
<File: 0x281e140a0> (entity: File; id: 0xdcac6620f1e9eb63 <x-coredata://BA0168AF-92CE-4AC2-A934-1020E41C5C20/File/p615>; data: {
    // ...
    identifier = "filecloud.test@run.se@files.runcloud.se/EXTERNAL/Gemensam RUN/FileCloud Test/Test folder \U00e5\U00e4\U00f6/Test with Swedish characters - \U00e5\U00e4\U00f6.xlsx";
    // ...
})

Which looks like the UTF16 string has been stored as an UTF8 one. But still a valid one as:
> po record.identifier == identifier
true

The problem comes later when trying to retrieve the record with again a UTF16 Swedish identifier string as the original above as it doesn't match anymore.
CoreStore.fetchOne(From<Record>().where(\.identifier == identifier)) // Fails

How could I convert identifier to a representation that would match the stored CoreData value?
Update
Even more strange, a hardcoded identifier does succeed:
CoreStore.fetchOne(From<Record>().where(\.identifier == "filecloud.test@run.se@files.runcloud.se/EXTERNAL/Gemensam RUN/FileCloud Test/Test folder åäö/Test with Swedish characters - åäö.xlsx")) // Works

And identifer and this hardcoded string do match:
po identifier == "filecloud.test@run.se@files.runcloud.se/EXTERNAL/Gemensam RUN/FileCloud Test/Test folder åäö/Test with Swedish characters - åäö.xlsx"
true

But using identifier instead of the hardcoded one doesn't.
Update 2
Comparing .unicodeScalars of identifier and the hardcoded string does show that they are indeed different:

A:

CoreData does save and return strings exactly the same.
The issue at trying to retrieve values using complex characters is that CoreData (and most probably SQLite behind it) do not consider my sentences equal as they have different grapheme clusters. Both sentences are valid and compare equal in Swift but not in CoreData as values to retrieve objects.
There doesn't seem to be a proper way to convert grapheme clusters in Swift, so my workaround was to recreate the process that lead to have the original grapheme clusters in the first place. This involved first creating a URL out of the string and then letting the FileProvider framework create the same grapheme clusters by calling persistentIdentifierForItem(at: url)!.rawValue. Then use this value to retrieve my saved object.


Q:

Edit view of checkbox list in Symfony form

I have a form with an entity field where you can select multiple provinces. I want to show it like a list, one under another, but this is how it looks now:

And I want that it looks like this:

There is a way I can edit it?
The formType code:
$builder->add('provinces', EntityType::class, array(
    'label' => 'Provincias donde actuo',
    'required' => true,
    'class' => 'CASEventBundle:Province',
    'choice_label' => 'name',
    'required' => false,
    'multiple' => true,
    'expanded' => true
));

The twig template:
{{ form_label(form.provinces) }}

    <input type="checkbox" class="selectAllCheckboxes">Seleccionar todos

    {{ form_errors(form.provinces) }}
    {{ form_widget(form.provinces) }}

Edit: Here is the HTML code that is generated:

            <input type="checkbox" id="cas_group_profile_provinces_1" name="cas_group_profile[provinces][]" value="1">
            Álava
            <input type="checkbox" id="cas_group_profile_provinces_2" name="cas_group_profile[provinces][]" value="2">
            Albacete
            <input type="checkbox" id="cas_group_profile_provinces_3" name="cas_group_profile[provinces][]" value="3">
            Alicante
            <input type="checkbox" id="cas_group_profile_provinces_4" name="cas_group_profile[provinces][]" value="4">
            Almería
        ...

A:

I have found a solution by myself
{{ form_label(form.provinces) }}

    <input type="checkbox" class="selectAllCheckboxes">Seleccionar todos

    {% for field in form.provinces %}

         {{ form_widget(field) }}
         {{ form_label(field) }}

    {% endfor %}

Even so thanks to all the answers :)


Q:

java Constructor of class Printwriter

In one of the sample code I saw, there is such a line:
PrintWriter pw = new PrintWriter("$$$temp$$$.$$$");

What is the "$" sign mean in this context? Is it something like a wildcard?

A:

$ means nothing in particular which is why its appears to being used here to specify a temporary file name. Chances are a file with this name will not already exist on the filesystem. If you're trying to create a temporary file check out createTempFile


Q:

Is there a way to make css letter-spacing: 0.5 px?

I ran across the problem, I need to make it easy for users to read the text, so I used letter-spacing of 1 px, but it looks ugly, so I thought I'll use half a pixel so 0.5px, but it doesn't work, I tried using em attributes, but didn't achieve the task.
So is there a way to make letter spacing half pixel (cross browser solution if possible)

A:

This bug has been reported back in 2008 and is confirmed. So if someone feels like hacking into webkit that would make a lot of designers happy.
https://bugs.webkit.org/show_bug.cgi?id=20606

A:

Sub-pixel letter spacing works fine on FF, but not on WebKit (at least on Windows). See this test case:
http://jsfiddle.net/fZYqL/2/
This test also shows that it is not the sub-pixel literal value that is a problem. Using fractional em values that result in less than 1px of letter-spacing are also not honored on Webkit, but work just as well on Firefox.

A:

This bug has been fixed in Chromium and landed in Chrome 30. So fractional values are now supported by Firefox, Chrome and Opera.


Q:

Run batch file code from java code

I want to execute a batch file code from java button click. Also I don't want any command prompt window to be shown all from java code.
I have a code :-
C:\xyz-3.1.1\bin>dita --input=C:/Users/india/Desktop/mobile-phone/m
obilePhone.xyz --format=pdf --output=C:/Users/india/Desktop --logfile=C:/Use
rs/india/Desktop/dofhdif.txt

So I want above code to be run from batch command with  C:\xyz-3.1.1\bin> as the parent directory.
Also I want to update --input file path whenever I will choose new file from JFileChooser.
I did this from the java code on button click transform:-
ProcessBuilder pb=new ProcessBuilder("dita --input=C:/Users/india/Desktop/mobile-phone/mobilePhone.xyz --format=pdf --output=C:/Users/india/Desktop --logfile=C:/Users/india/Desktop/dofhdif.txt");
pb.redirectErrorStream(true);
Process process=pb.start();

and getting IOException error.
I get stuck over here for long time , where am I going wrong.
EDIT :- error
java.io.IOException: Cannot run program "dita --input=C:/Users/india/Desktop/mobile-phone/m
obilePhone.xyz --format=pdf --output=C:/Users/india/Desktop --logfile=C:/Use
rs/india/Desktop/dofhdif.txt": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)

A:

Try this:
String inputFile = ...;
String outputFile = ...;
String logFile = ...;

ProcessBuilder pb = new ProcessBuilder(
        "dita",
        "--input=" + inputFile,
        "--format=pdf",
        "--output=" + outputFile,
        "--logfile=" + logFile)
    .directory(new File("C:\\xyz-3.1.1\\bin"))
    //.inheritIO();
    .redirectErrorStream(true);

Process process = pb.start();

This shows the following points:

The command is separated from the arguments
The argument values can be determined at runtime
The command's default directory (C:\xyz-3.1.1\bin) is set before starting the process
Consider using inheritIO() instead of redirectErrorStream() if you want the process's output to appear as part of your Java application's output.


Q:

Htaccess Rewrite Rule But Not When File Extension Present

I am trying to create a RewriteRule for paths but not for files. This code works for paths but if a file is requested such as an image or CSS file this is also pointed to the index.php file which is incorrect behavior!
RewriteRule (.*)/(.*) index.php?$1/$2

Any ideas how to fix this!? Thanks Matt!

A:

Put this on the line before the rule:
RewriteCond %{REQUEST_FILENAME} !-f


Q:

Passing Multiple value in Bundle, value assigned in last String is getting passed to all string

I'm trying to pass 9 string from one java class to another class via Bundle. But in the another screen, value assigned to last extra is overwritten to all other string.
Class1
public class HomeScreen extends AppCompatActivity {

public  static String  Buy_Price;
public  static String  Sell_Price;
public  static String  QUANTITY;
public  static String  BROKERAGE;
public  static String  ActualProfitLoss_String;
public  static String  TurnOver_String;
public  static String  STT_String;
public  static String  ServiceTax_String;
public  static String  TotalCharge_String;
public  static String  x;
private static  String Strin ;

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

public void calculateProfit(View view) {
    Intent intent = new Intent(this, displayProfit.class);
    Bundle extras =new Bundle();
    EditText editText=(EditText) findViewById(R.id.editText);
    EditText editText4=(EditText) findViewById(R.id.editText4);
    EditText editText2=(EditText) findViewById(R.id.editText2);
    EditText editText3=(EditText) findViewById(R.id.editText3);

    String buyPriceString = editText3.getText().toString();
    Float BuyPrice =  Float.parseFloat(buyPriceString);
    String quantityString = editText2.getText().toString();
    Float Quantity =  Float.parseFloat(quantityString);
    String sellPriceString = editText4.getText().toString();
    Float SellPrice =  Float.parseFloat(sellPriceString);
    String brokerageString = editText.getText().toString();
    Float Brokerage =  Float.parseFloat(brokerageString);

    double TurnOver=(BuyPrice*Quantity)+(SellPrice*Quantity);
    double Sell1 =SellPrice-(SellPrice*(Brokerage/100));
    double Buy1 = BuyPrice+(BuyPrice*(Brokerage/100));
    double TotalBrokerage = ((Sell1*.03)+(Buy1*0.3));
    double STT = (Quantity*(SellPrice-(SellPrice*(Brokerage/100))))*(.025/100);
    double TrnxChrge = TurnOver*(0.00275/100);
    double ServiceTax = (TotalBrokerage+STT)*(15/100);
    double SEBICharge = (TurnOver*(.0002/100));
    double TotalCharge = ServiceTax+TrnxChrge+SEBICharge+STT;
    double NetProfit = (Sell1-Buy1)*Quantity;
    double ActualProfitLoss = (NetProfit -TotalCharge);

    String ActualProfitLossString=Double.toString(ActualProfitLoss);
    String TurnOverString=Double.toString(TurnOver);
    String STTString=Double.toString(STT);
    String ServiceTaxString=Double.toString(ServiceTax);
    String TotalChargeString=Double.toString(TotalCharge);

    extras.putString(ActualProfitLoss_String,ActualProfitLossString);
    extras.putString(TurnOver_String,TurnOverString);
    extras.putString(STT_String,STTString);
    extras.putString(ServiceTax_String,ServiceTaxString);
    extras.putString(TotalCharge_String,TotalChargeString);
    extras.putString(Buy_Price,buyPriceString);
    extras.putString(Sell_Price,sellPriceString);
    extras.putString(BROKERAGE,brokerageString);
    extras.putString(QUANTITY,quantityString);
    intent.putExtras(extras);

    startActivity(intent);

}

Class 2:
public class displayProfit extends AppCompatActivity {

private static  String Strin ;

protected void onCreate(Bundle savedInstanceState) {
    Log.d(Strin, "buyPrice :::");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_profit);

    Intent intent =getIntent();
    Bundle extras = intent.getBundleExtra(HomeScreen.x);
    String Buy_Price = extras.getString(HomeScreen.Buy_Price);
    String Sell_Price = extras.getString(HomeScreen.Sell_Price);
    String QUANTITY = extras.getString(HomeScreen.QUANTITY);
    String BROKERAGE = extras.getString(HomeScreen.BROKERAGE);
    String ActualProfitLoss_String = extras.getString(HomeScreen.ActualProfitLoss_String);
    String TurnOver_String = extras.getString(HomeScreen.TurnOver_String);
    String STT_String = extras.getString(HomeScreen.STT_String);
    String ServiceTax_String = extras.getString(HomeScreen.ServiceTax_String);
    String TotalCharge_String = extras.getString(HomeScreen.TotalCharge_String);

    TextView Buy_Price1= (TextView) findViewById(R.id.Buy_Price1);
    TextView Sell_Price1= (TextView) findViewById(R.id.Sell_Price1);
    TextView QUANTITY1= (TextView) findViewById(R.id.QUANTITY1);
    TextView BROKERAGE1= (TextView) findViewById(R.id.BROKERAGE1);
    TextView ActualProfitLoss_String1= (TextView) findViewById(R.id.ActualProfitLoss_String1);
    TextView TurnOver_String1= (TextView) findViewById(R.id.TurnOver_String1);
    TextView STT_String1= (TextView) findViewById(R.id.STT_String1);
    TextView ServiceTax_String1= (TextView) findViewById(R.id.ServiceTax_String1);
    TextView TotalCharge_String1= (TextView) findViewById(R.id.TotalCharge_String1);

    Buy_Price1.setText(Buy_Price);
    Sell_Price1.setText(Sell_Price);
    QUANTITY1.setText(QUANTITY);
    BROKERAGE1.setText(BROKERAGE);
    ActualProfitLoss_String1.setText(ActualProfitLoss_String);
    TurnOver_String1.setText(TurnOver_String);
    STT_String1.setText(STT_String);
    ServiceTax_String1.setText(ServiceTax_String);
    TotalCharge_String1.setText(TotalCharge_String);

}

}

In the end of class2 I placed log and found that Value assigned to QUANTITY is getting populated for all the string.
Please clarify the above. If you more code needed will share the same.

Logs for the same after changing the Class1 as suggested in answer
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
     W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
     W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
     I/art: Background sticky concurrent mark sweep GC freed 25273(2MB) AllocSpace objects, 15(264KB) LOS objects, 44% free, 4MB/8MB, paused 14.345ms total 168.562ms
       [ 02-20 23:21:14.614  3314: 3314 D/         ]

buyPrice :::
[ 02-20 23:21:14.861  3314: 3314 D/         ]
     NotNull::::::
     D/AndroidRuntime: Shutting down VM
       --------- beginning of crash

E/AndroidRuntime: FATAL EXCEPTION: main
     Process: com.test.tax, PID: 3314
     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.tax/com.test.tax.displayProfit}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
     at android.app.ActivityThread.-wrap12(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6077)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
     at com.test.tax.displayProfit.onCreate(displayProfit.java:29)
     at android.app.Activity.performCreate(Activity.java:6662)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
     at android.app.ActivityThread.-wrap12(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6077)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
     Disconnected from the target VM, address: 'localhost:8625', transport: 'socket'

A:

Just initialize all the above public static Strings which you are using to add items into the Bundle with unique values else they will override each other. eg.
public  static String  Buy_Price = "a";
public  static String  Sell_Price = "b";
public  static String  QUANTITY = "c";
public  static String  BROKERAGE = "d";
public  static String  ActualProfitLoss_String = "e";
public  static String  TurnOver_String = "f";
public  static String  STT_String = "g";
public  static String  ServiceTax_String = "h";
public  static String  TotalCharge_String = "i";
public  static String  x =  = "j";

Also, they should ideally be public static final String. Please consider using a consistent naming convention too (TOTAL_CHARGE, TURN_OVER).
You can imagine the Bundle as a Map, if you put values with the same key, the values will be overridden. That is why you got the value of QUANTITY in for all the keys because all the keys were null (equal) and QUANTITY was the last key you put in the Bundle.
EDIT:
For the NullPointerException.
In Class 1 (HomeScreen) inside calculateProfit(View view) method you put the Bundle in the Intent without a key.
intent.putExtras(extras);

Then in Class 2 (displayProfit) inside onCreate(Bundle savedInstanceState) you get the Bundle from the Intent with a key.
intent.getBundleExtra(HomeScreen.x);

So put the extras using the same key in HomeScreen like so
intent.putExtra(HomeScreen.x, extras);