Stack Overflow

Subscribe to Stack Overflow feed
most recent 30 from 2018-02-21T10:21:19Z
Updated: 4 hours 28 min ago

Correct way to using namespace in nested namespace scope

Mon, 02/19/2018 - 09:59

We have in code one common namespace MainNamespace and a lot of namespace per module eg. ModuleNamespace, DifferentModuleNamespace. Module namespaces are inside the main namespace.

When we create a new class and need another class from different module we have to declare some using to avoid writing full namespace path.

What is consider as a good practice in such situation:

Using namespace with full path:

namespace MainNamespace { namespace ModuleNamespace { using MainNamespace::DifferentModuleNamespace::Foo; class MyClass { void method(Foo); }; } }

or remove MainNamespace namespace from path:

namespace MainNamespace { namespace ModuleNamespace { using DifferentModuleNamespace::Foo; class MyClass { void method(Foo); }; } }

or maybe different approach is better?

how to use bootstrap alert message inside a javascript function?

Mon, 02/19/2018 - 09:57

I would like to add Bootstrap alert messages inside the javascript function.


<div class="alert alert-success fade in"> <a href="#" class="close" data-dismiss="alert">&times;</a> <strong>Success!</strong> Your message has been sent successfully. </div>

The above div content displays a success message.. i want to call this inside my javascript code, if my web service returns a success message.

Kindly respond with a solution.

Thanks, Janani

adding border to CircleMarkers with leaflet and R

Mon, 02/19/2018 - 09:51

i would like to add border to the CircleMarkers, i use this code:

pal <- colorNumeric( palette = 'RdYlBu', domain = city_results$ratio ) m <- leaflet() %>% addTiles() %>% setView(lng = median(city_results$long), lat = median(mean(city_results$lat)) , zoom = 8) %>% addProviderTiles(providers$CartoDB) %>% addCircleMarkers(data=city_results,lng=~long, lat=~lat, radius = ~(Socioeconomic_status_group), color = ~pal(ratio), stroke = TRUE, fillOpacity = 0, popup = ~as.character(nameH), label = ~as.character(round(corr_value,2)), labelOptions = labelOptions(noHide = T, textOnly = TRUE) )

but can't find any function to add black border to the stroke.

I wanted to connect my application to active directory.There I wanted to use all AD services like grouping ,administration etc.Is that possible?

Mon, 02/19/2018 - 09:49

I am creating an application.Can I connect that with active directory? There I wanted to use all AD services like grouping ,administration etc.Is that possible?

In the java application I need to write code for connecting to active directory.I am trying to create a spring boot application.

What type does `n` in `const n = 1u;` have?

Mon, 02/19/2018 - 09:14

I am wondering about the inference of const variable types in C++.

Our old compiler compiles the declaration const n = 1;. n will have the type const int, I assume. I would think that the int is not inferred from the type of the initializing expression (1) but is a simple grammar rule.

What then is the type of n in const n = 1u;? I would assume it is also int, but cannot find the rule in the C++17 standard draft (which makes me wonder whether it is in fact illegal but tolerated by a lenient compiler). Also of interest is whether there would be a difference to C, hence both tags.

Null value is also decoding in HIVE

Mon, 02/19/2018 - 07:52

I am working on Hive. I need decode some of the fields in table so i am using Translate() method but problem is like in some of the places i have null this character also decoding. How do you solve this one?

here is my code

TRANSLATE (Address2, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 'DEFGHIJKLMNOPQRSTUVWXYZABCdefghijklmnopqrstuvwxyzabc') as Address2,

What case is unsafe of ByteIterable#getBytesUnsafe() of Xodus?

Sun, 02/18/2018 - 22:10

what case is unsafe? I'm using getBytesUnsafe() like this. is this safe?

@Test public void unsafe() { Environment env = Environments.newInstance("db/xodusTest"); Transaction txn = env.beginTransaction(); Store s = env.openStore("unsafe", StoreConfig.WITHOUT_DUPLICATES_WITH_PREFIXING, txn); Random rnd = new Random(); Long id = rnd.nextLong(); byte[] appData = new byte[32]; rnd.nextBytes(appData); s.put(txn, LongBinding.longToEntry(id), new ArrayByteIterable(appData)); ByteIterable data = s.get(txn, LongBinding.longToEntry(id)); byte[] loadedAppData = data.getBytesUnsafe(); txn.commit(); env.close(); }

How clean data-set for missing values using MapReduce

Sun, 02/18/2018 - 22:09

How can I write a MapReduce program to achieve this?

  • You are given a file with keys and values.
  • The keys are in increasing order from 1 to 1,000,000, but some keys in this file may be missing.
  • Key "1" will always exist.

The goal is to reconstruct missing keys with the value from the previous key.

For example, if the file contains: (1, A), (2, B), (4, C), … The cleaned output would be: (1, A), (2, B), (3, B), (4, C), …

Keep getting infinity as result??

Sun, 02/18/2018 - 22:09

So I am working on an expression evaluation project. I am using stacks. I have written a method to evaluate stacks, yet I am having some trouble.

public static float evaluate(String expr, ArrayList<Variable> vars, ArrayList<Array> arrays) { String exp = expr.replaceAll(" ", ""); Stack<String> ops = new Stack<String>(); Stack<String> numsAndVars = new Stack<String>(); //expression is a number if(isNumeric(exp)) { return Float.parseFloat(exp); } //expression is a basic Variable else if(isBasicVar(exp)) { int index = 0; for(int i = 0; i < vars.size(); i++) { if(vars.get(i).name.equals(exp)) { index = i; } } return (float) (vars.get(index).value); } //expression has two terms and an operator else if(numOps(exp) == 1) { int indexOp = 0; for(int i = 0; i < exp.length(); i++) { if(Pattern.matches("[+-/*]", exp.substring(i, i+1))) { indexOp = i; } } if(exp.charAt(indexOp) == '+') { return (float) evaluate(exp.substring(0, indexOp), vars, arrays) + evaluate(exp.substring(indexOp + 1), vars, arrays); } else if(exp.charAt(indexOp) == '-') { return (float) evaluate(exp.substring(0, indexOp), vars, arrays) - evaluate(exp.substring(indexOp + 1), vars, arrays); } else if(exp.charAt(indexOp) == '*') { return (float) evaluate(exp.substring(0, indexOp), vars, arrays) * evaluate(exp.substring(indexOp + 1), vars, arrays); } else { return (float) evaluate(exp.substring(0, indexOp), vars, arrays) / evaluate(exp.substring(indexOp + 1), vars, arrays); } } else if(numOps(exp) > 1) { String readyToTok = prepString(exp); StringTokenizer st = new StringTokenizer(readyToTok, "$"); String[] tokens = new String[st.countTokens()]; for(int i = 0; i < tokens.length; i++) { tokens[i] = st.nextToken(); } int j = 0; while(j < tokens.length) { if(isNumeric(tokens[j]) || isBasicVar(tokens[j])){ numsAndVars.push(tokens[j]); j++; } else if(isOperator(tokens[j])) { ops.push(tokens[j]); j++; } //else if(isOperator(tokens[j]) && ops.isEmpty() == false) { //if(hasHigherPrec(tokens[j], ops.pop())) { //ops.push(tokens[j]); //j++; //} //else { // processStacks(numsAndVars, ops, vars, arrays); //} //} else { j++; } } processStacks(numsAndVars, ops, vars, arrays); processStacks(numsAndVars, ops, vars, arrays); System.out.println(numsAndVars.pop()); } return 0f; } private static boolean isNumeric(String s) { if(Pattern.matches("[0-9]+", s) && Pattern.matches("[a-zA-Z]", s) == false && Pattern.matches("\\[|\\]", s) == false ) { return true; }return false; } private static boolean isBasicVar(String s) { if(Pattern.matches("[a-zA-Z]+", s) && Pattern.matches("[0-9]+", s) == false && Pattern.matches("\\[|\\]", s) == false ) { return true; }return false; } private static void processStacks(Stack<String> n, Stack<String> o, ArrayList<Variable> v, ArrayList<Array> a) { if(n.isEmpty() == false && o.isEmpty() == false) { String v2 = n.pop(); String op = o.pop(); String v1 = n.pop(); String express = v1 + op + v2; float result = evaluate(express, v, a); n.push(Float.toString(result)); } }

"2 * 3 + 4" --> BASIS FOR THIS POST Essentially, I am adding tokens from a string, which I have tokenized in a certain way to the stacks based on if the are an operand or an operator. I am having some issues so I am using S.O.P to see whats happening. When I call processStacks the first time, it gives me the correct answer of 7 which would be 3 + 4, and then the 7 would be pushed onto the operands stack. However, when I call it a second time, it should yield 14 since it is 14 and 2 in the operand stack and * in the operator stack. However, when I run it, it gives me infinity. I cant figure out why this keeps happening?

R: How can I apply column name changes to many data frames at once?

Sun, 02/18/2018 - 22:09

I am trying to replace certain words in the column headers of over 100 data frames.I have a string that works perfectly:

names(singledataframe) <- gsub(x = names(singledataframe), pattern = "Int'l",

replacement = "International")

I am trying to apply this to all the frames I've made. I used c()to refer to them under AllFrames. I was trying to make a function of the string that works on one frame and apply it to AllFrames, with a for loop.

ChangeName1 <- function(singledataframe) { gsub(x = names(singledataframe), pattern = "Int'l", replacement = "International") }

then something like:

for (i in 1:length(names(AllFrames))) {lapply(i, ChangeName1) }

I get no errors, but randomly checking individual frames shows the intended effect did not take.I've tried so many variations, but I'm stuck! I'm thinking maybe I need to edit the c() that refers to AllFrames in a better way.

  • I apologize if any of this is unclear or I generally posted incorrectly. It's my first time and all this is new two me. Thanks in advance for any direction or help you can give.

How to improve the training of the neural network to annotate images?

Sun, 02/18/2018 - 22:08

I have to modify making a landscape classification project more efficient, written in python, the software allows you to annotate images classifying them with:

  • grass

  • sea

  • sky

using features extracted only by color (because easier to do).

That said, I'll explain briefly what the software does, there are two main phases:

  • The first phase is the quantization of the color where the images of the dataset are reconstructed with only 10 colors (I use the kmeans) to understand which centroid to replace the pixel of the image: to do this we calculate the Euclidean distance between the image pixels and centroids (representative for the 10 clusters) considered one at a time, the centroid with minimum distance will take the place of the pixel in this way all the images will be reconstructed, the histogram of the color of each image will also be calculated.

    height, width, r=image.shape print image.shape new_image=np.zeros((height,width,r),np.uint8) print new_image.shape for i in range(0, height): for j in range(0, width): pixel=image[i, j] #extract the first pixel of the image r = pixel[0] g = pixel[1] b = pixel[2] min = 500 #minimum fictitious distance pos = 0 #color position for k in range(len(db_palette)): #dbpalette = palette with 10 centroid calcolated by kmeans colore=db_palette[k].tolist() #extract the first centroid r1= colore[0] g1 = colore[1] b1 = colore[2] d=sqrt(((r-r1)**2)+((g-g1)**2)+((b-b1)**2)) #eucliean distance if d<min: min=d pos=k colore_scelto=db_palette[pos].tolist() nuovo_colore=(colore_scelto[0],colore_scelto[1],colore_scelto[2]) pixel=nuovo_colore new_image[i,j]=pixel
  • The second phase consists of training the network (a network of feed-forward type of the neurolab library is used), the network is created giving input:

  • the histogram of the color of the images

  • the categories of membership (considering that it is supervised learning)
  • network is set with 50 hidden nodes

    network =[[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]],[50, 3])

The network is trained with a dataset of 200 total images (for the categories grass, sea, sky, grass+sea, grass+sky, grass+sea+sky, sea+sky), in output has 3 numerical values ​​between 0 and 1 which represent the percentage of belonging to one of the categories (grass, sea and sky), after which it is tested on other images to check the efficiency of the network.

The problem is that it often happens that the network does not correctly annotate the images. Now I wanted to ask if there are alternative methods to train the network:

  • Is there a way to replace network training with another simple way to avoid using the color histogram?

  • How can I evaluate the image quantization process if it is correct?

  • With the goal of improving network efficiency in the image annotation process, what should I do?

  • Can I modify the program without upsetting the logic by improving the efficiency to annotate the images?

Sorry for the questions but I have very little experience and I would like to be able to modify the software as simply as possible without upsetting it.

EF Core Many-To-Many Relationship Sets Both Keys to Parent

Sun, 02/18/2018 - 22:08

I working on building out a model that would represent a typical product that could be created in an e-commerce platform written using EF Core 2.0. See the model structure below

public class GSProduct : BaseEntity { [Required] public string Name { get; set; } public ICollection<GSProduct> BaseProducts { get; set; } public ICollection<GSRelatedProduct> ParentProducts { get; set; } public ICollection<GSRelatedProduct> ChildProducts { get; set; } public ICollection<GSVendorProductInfo> VendorProductInfo { get; } = new List<GSVendorProductInfo>(); } public class GSRelatedProduct { public virtual GSProduct ParentProduct { get; set; } public Guid ParentProductId { get; set; } public virtual GSProduct ChildProduct { get; set; } public Guid ChildProductId { get; set; } } public class GSVendorProductInfo : BaseEntity { public GSContact Vendor { get; set; } public Guid VendorId { get; set; } public GSProduct Product { get; set; } public Guid ProductId { get; set; } public string VendorPartNumber { get; set; } public int BaseUnits { get; set; } public double Cost { get; set; } public int MinOrderQty { get; set; } public int OrderedInMultiples { get; set; } }

This is what I have set up for the Fluent API.

modelBuilder.Entity<GSVendorProductInfo>() .HasOne(pt => pt.Product) .WithMany(p => p.VendorProductInfo) .HasForeignKey(pt => pt.ProductId); modelBuilder.Entity<GSVendorProductInfo>() .HasOne(pt => pt.Vendor) .WithMany(t => t.VendorProductInfo) .HasForeignKey(pt => pt.VendorId); modelBuilder.Entity<GSRelatedProduct>().HasKey(x => new { x.ParentProductId, x.ChildProductId }); modelBuilder.Entity<GSRelatedProduct>() .HasOne(pt => pt.ParentProduct) .WithMany(t => t.ParentProducts) .HasForeignKey(pt => pt.ParentProductId); modelBuilder.Entity<GSRelatedProduct>() .HasOne(pt => pt.ChildProduct) .WithMany(t => t.ChildProducts) .HasForeignKey(pt => pt.ChildProductId);

The scaffolding / migration is working fine and I can actually create products without a problem that include all of the relationships. The issue arises when I try to add a 'RelatedProduct' to the Product model.

I set the ParentProductId and the ChildProductId accordingly and when I create or update the entity it sets both the ParentProductId and the ChildProductId value to the ParentProductId.

I've followed the code through my debugger and it is correct up until the point where I call _context.Update(entity). After that both of the Ids in the RelatedProduct model are set to the same value.

I've got no idea why this is happening any suggestions would be very helpful.

How to create a Vec<u8> that covers 0 to 255, inclusive?

Sun, 02/18/2018 - 22:08

I wanted a vector of u8 that covered 0 through 255 inclusive:

let v: Vec<u8> = (0..256).collect();

This does not work as might be expected because apparently it is not possible in Rust to define a Range that spans the entire set of possible values of integers.

I guess I can do something like this instead:

let v: Vec<u8> = (0..256u16).map(|x| x as u8).collect();

But this seems roundabout. Am I doing this wrong? Is there a better way to do what I'm looking for?

execute(); in PHP PDO not working

Sun, 02/18/2018 - 22:07

I write code in PDO OOP but SQL query is working to var_dump($sql) and to SQL PHPMyAdmin but not working execute!

public function insertData($filds, $data) { if (is_array($data)) { $names = "'" . implode("','", $data) . "'"; $filds = implode(",", $filds); $sql = $this->pdo->prepare("INSERT INTO {$this->tbl}($filds) VALUES ($names)"); var_dump($sql); $sql->execute(); } }

Localized input gesture text in WPF

Sun, 02/18/2018 - 22:04

I have a custom RoutedCommand with an input key gesture that is called in a menu item in a localized app. I discovered that the text displayed as keyboard shortcut for my own command is not localized to German (displayed as "Ctrl+..."), while the built in ApplicationCommands' key modifiers are translated to German (displayed as "Strg+...").

The result looks like this:

This the xaml code:

<ContextMenu> <MenuItem Header="Edit" Command="local:MyWindow.MyCommand"/> <MenuItem Header="Save" Command="Save"/> </ContextMenu>

Why is this? How can I localize own commands (preferebly without hardcoding the translated modifiers)?

SQL Server: Updating a table row with first instance of multiple records from another table

Sun, 02/18/2018 - 22:00

I have two tables. TableA & TableB. TableB already has rows of data but needs to be updated with information from TableA but the only matching information in each table does not identify a specific row, only a group of rows. They look something like this:

TableA StartTime InstanceID WorkCode JobNumber WorkCenter ======================= ========== ======== ========= ========== 2018-02-16 18:37:13.000 728282 103 725863 155 2018-02-17 00:54:12.000 728265 106 725863 155 2018-02-16 22:12:03.000 728110 103 725863 155 TableB StartTime InstanceID WorkCode JobNumber WorkCenter ======================= ========== ======== ========= ========== 2018-02-16 18:39:53.000 NULL NULL 725863 155 2018-02-17 00:52:18.000 NULL NULL 725863 155 2018-02-16 22:08:26.000 NULL NULL 725863 155

In the above example, these two tables were inserted approximately at the same time but not exact as you can see by their timestamps. The only truly matching information is JobNumber and WorkCenter. I need a way to match them up so I can do an UPDATE on TableB with the missing information from TableA.

The only way I think this can be done is to sort TableB by StartTime and do some sort of UPDATE via a loop where TableA will also have to be sorted by StartTime. Then, the first instance in TableA will match to the first instance in TableB and will be updated, then the second record/instance, the third, fourth, etc.

Any pros ever had to deal with this before where the only way to link them up is by their order? Would creating temp tables help by creating a numbered column and linking that way?

Keep in mind, these tables have multitudes of different values in JobNumber and WorkCenter columns so I'll need to use WHERE clause filtering as well.

javascript - global variable being persisted in forEach loop. scope issue?

Sun, 02/18/2018 - 21:59

I'm having an issue looping through an array of objects (twice) and modifying a nested object.

I have an array of roles that contain permissions assigned to that role. I also have an array of all possible permissions that can be assigned to a role.

On my html page, I need to list each role... and within each role I need to list all the permissions as checkboxes. The permission checkbox needs to be checked if the permission has already been assigned to that role. To do that, I need to:

  1. Loop through all roles
  2. For each role, copy the ID's of all the attached permissions to an array.
  3. Replace the role's permissions with the list of all permissions.
  4. Loop through the role's new permissions array.
  5. For each permission, add a new "selected" property, whos value is true or false depending on if the permission's ID is in the array of ID's set in #2

Here is a jsFiddle. Here is the operation:

roles.forEach(function(role){ // Get list of all the permission ids before the permissions are replaced with the list of all permissions var permission_ids = => { return }); // Replace the roles permissions with the global list of permissions role.permissions = permissions; role.permissions.forEach(function(permission){ permission.selected = permission_ids.indexOf( > -1; }); });

The problem is, the permissions variable is binding to the local role.permissions array and is being persisted across every iteration of role.

The result of the operation should be a list of roles containing a list of all permissions, and in each permission there is a "selected" property based on if the permission is attached to the role.

Rather, in the end... the permissions of each role is the result of the operation of the last iteration of the role loop.

I can accept an alternative solution, but I would also like an explanation of why this is happening?

C programming : padding in structure

Sun, 02/18/2018 - 21:58

I am using processor architecture: x86_64 OS : Debian GNU/Linux 9 (stretch) 64-bit GCC compiler ver. : 6.3.0 if i compile this code - struct test{chara;intb;}test; printf("%ld",sizeof(test); then the output is - 8 i assumed it because of 4 bytes padding , i mean 1+3+4 now i tried this code- struct test{char a;double b;}test; and this gave me 16 bytes, then i thought, may be it is because of 8 bytes padding, i.e.- 1+7+8 now when i tried this code - struct test{char a;long double b;char c;}test; this gave me 48 bytes

in my system using gcc , int = 4 byte, double = 8 byte, char = 1 byte ,long double = 16 byte. my question is how this works? why not a uniform padding?

Switch case jumps to wrong case in javascript

Sun, 02/18/2018 - 21:58

My code is not so long so I am pasting all of it here.

The code is not complete but when I run it it first jumps to case "start" which it is supposed to, and then jumps to case "end". I can see it because it prints both blocks' console log texts. Why is it jumping to the "end" case?

<html> <body> <script> function stepStream(stream,step){ switch (stream[step]){ case "start": console.log("Started reading stream..."); case "end": var success = "Finished reading dataStream."; console.log(success); return success; default: throw "Data stream format is bad"; case "gesture": //commUGesture(stream[i+1]); //createLogLine("robot:CommU","event:gesture:"+stream[i+1]); console.log("Running case gesture! But why?"); step+=1; stepStream(stream,step); case "say": step+=1; stepStream(stream,step); case "sleep": step+=1; stepStream(stream,step); } } var sentence1 = "Where are my bananas? I thought you put them in my bag?"; var sentence2 = "This is a rather irritating situattion."; var dataStream = ["start","gesture","banzai","sleep",1.0,"say",sentence1, "say",sentence2,"gesture","kubikasige","end"]; stepStream(dataStream,0);//Second parameter sets where to start reading the dataStream. </script> </body> </html>

How to rise known event using TestStack.White or CodedUI?

Sun, 02/18/2018 - 21:48

I have custom control with event RightButtonClick, but this control cannot be cast to exist types such as Pane, Custom or another.

How can I rise such event?