text:
Q: How do I close pyplot windows and display new ones when a widget button is pressed? I have some code that generates an interactive display.  One plot is seen in a "magnified display," and several other plots are seen below:
https://i.stack.imgur.com/eydU7.png
When I press the "apply to all" button, I want to update the graphs in the lower row to reflect the parameters selected by the widgets.  My function for this works, but the original graphs aren't cleared and the new ones are displayed under them.  No amount of using plt.close(), plt.clf(), or any related functions has been able to solve this issue.
The graphs are generated using the interactive_output feature of the ipywidgets package, so a function runs every time one of the widgets is updated.  This function includes a plt.close() call to remove the current figure and subsequently defines a new one.  However, this doesn't happen and the new one is just plotted on top of the old one.
How do I remove the old graphs from the display when the new ones are generated?


text:
Q: Bot Framework Emulator failed to run on Windows Downloaded BotFramework-Emulator-4.11.0-windows-setup.exe from the release page 'https://github.com/Microsoft/BotFramework-Emulator/releases'. After installation, the emulator cannot start on Windows 10 X64.
I tried it on my desktop, laptop and a VM in Azure. What could be wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding link to CollectionView cell based on image name I have a CollectionView with UIImageView's in them and the images are defined in listImages array.
I am trying to get it so that when you click on a specified image, you will get redirected to a website with more information about that.
However, I don't know how to use the if clause to get the name of the image and by that give it a link.
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    listImages = [NSArray arrayWithObjects:@"7513-kirjatkuivumassa.jpg", @"kuppi.jpg", @"kuva1.jpg", @"juna-042.jpg", @"rautio-valamonruusut-helleaamuna-maalaus.jpg", @"pysähtynyt1.jpg", @"Screen-Shot-2013-02-20-at-21.07.38.jpg", @"sateenkaari.jpg", @"Screen-Shot-2013-02-21-at-17.04.22.jpg", @"moninaiset-e1391026376696.jpg", @"Tomperi+Metsä20111.jpg", @"3-shinot.jpg", @"Ulpukat.jpg", @"janne-e1391025808211.jpg", @"martikainen-240x240.jpg", @"takala-240x240.jpg", @"paanukallokaarme1.jpg", @"käsityök-240x240.jpg", @"kuvis-004.jpg", @"Se-on-hieno-2012-tammi-105x28x223.jpg", nil];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    if ([[cell.listImageView text] isEqualToString:@"7513-kirjatkuivumassa.jpg"]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://website.com"]];
    }
}

A: please try this.
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *image_name= [listImages objectAtIndex:indexPath.row];
    if ([image_name isEqualToString:@"7513-kirjatkuivumassa.jpg"]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://website.com"]];
    }
}

A: I think your structure here is not very good. You should leverage the power of objective-C instead of trying to do things yourself. I would follow the following steps:

*

*Create an object with the following properties: (1) UIImage, (2) NSString with the text, (3) NSUrl with the URL.

*listImages should contain your objects

*Now it's very easy to do what you are trying to do
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
         yourObject *yourObject = [listImages objectAtIndex:indexPath.row];
        [[UIApplication sharedApplication] openURL:yourObject.url]];
 }


text:
Q: Guice Bind Generic Types is there a way to bind generic types of the next sort:
public interface A<T extends Number> {
  void print(T t);
}

public class B implements A<Integer> {
  @Override
  public void print(Integer i) {
    System.out.println(i);
  }
}

public class C implements A<Double> {
  @Override
  public void print(Double d) {
    System.out.println(d);
  }
}

how can I exactly bind the above interface and its implementations (using TypeLiteral?) so that I could create a typed instance by some condition?
class Main {
  public static void main(String[] args) {
    A a1 = Guice.createInjector(new MyModule()).getInstance( ??? );
    a1.print(1); //will print 1

    A a2 = Guice.createInjector(new MyModule()).getInstance( ??? );
    a2.print(1.0); //will print 1.0
  }

}

how does MyModule suppose to look like?

A: What you are missing is,
Injector  injector = Guice.createInjector(new MyModule());
A a1 = injector.getInstance(Key.get(new TypeLiteral<A<Integer>>() {}));

And your MyModule
public static class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(new TypeLiteral<A<Integer>>() {}).toInstance(new B());
    }
}

A: You can create provider methods, without having to use TypeLiteral<A<Integer>> in the definition.
class MyModule extends AbstractModule {
  @Provides
  @Singleton
  A<Integer> provideAOfInteger() {
    return new B();
  }
}

And you can also use an implicit binding to access your A<Integer>:
class AOfIntegerHolder {
  @Inject A<Integer> aOfInteger;
}

Injector injector = Guice.createInjector(new MyModule());
A<Integer> a1 = injector.getInstance(AOfIntegerHolder.class).aOfInteger;

The beauty of Guice is that there are more than often several ways to do what you want, and none is better than the other: they're just different ;)


text:
Q: Python pandas printing correct dataframe I am reading from a csv-file, and have the current values in my dataframe, where width and height is min and max value.
name     width       heigth
apple    [10, 20]    [15, 18]

And now i want to split and format the columns and print them:
pd.DataFrame(df['width'].str.split(',').tolist(), columns=['width-min', 'width-max'])
pd.DataFrame(df['height'].str.split(',').tolist(), columns=['height-min', 'height-max'])

print(tabulate(df, headers='keys', tablefmt='psql'))

My problem is that it stills print:
name     width       heigth
apple    [10, 20]    [15, 18]

Whereas I want it to print:
name     min-width   max-width   min-height   max-height
apple    10          20          15           18

What am I doing wrong?

A: You do not save the resulting df.
You need to assign the modified df to a new variable or overwrite the original.
EDIT:
#create a separate df for each split operation (height and width separately)

df_1 = pd.DataFrame(df['width'].str.split(',').tolist(), columns=['width-min', 'width-max'])
df_2 = pd.DataFrame(df['height'].str.split(',').tolist(), columns=['height-min', 'height-max'])

# join the two dataframes on a common index or column
pd.merge(df_1, df_2, on=["enter common column here"])

A: This code can help you ,
a = {"name":['apple'],
     'width': ['[10, 20]'],
     'heigth': ['[15, 18]']}

import pandas as pd
df = pd.DataFrame(a)

df['min-width'], df['max-width'] = df['width'].apply(lambda x: x.strip('][').split(', ')[0]), \
                                   df['width'].apply(lambda x: x.strip('][').split(', ')[1])

df['min-height'], df['max-height'] = df['heigth'].apply(lambda x: x.strip('][').split(', ')[0]), \
                                   df['heigth'].apply(lambda x: x.strip('][').split(', ')[1])

df = df.drop(['width','heigth'],axis=1)

The df will be,
    name min-width max-width min-height max-height
0  apple        10        20         15         18

please let me know if that helps you !! Also, I am open to optimized suggestions!!


text:
Q: How do i program a Double hash implementation meant for strings? Hello everyone first time here but i'd like to start by first asking if my understanding of double hashing is correct.
Double hashing works by first implementing a hash function then checking to see if that spot is open. if the current spot is not open then using a second hash function determine another spot and then multiply it by the current attempt and then add it to the index spot that was determined by the first hashing algorithm.
the current code i'd have is:
unsigned int findPos(hashedObj& x)
{
    int offset = 1;
    int iteration = 0;
    unsigned int originalPos = myhash1( x );
    unsigned int index = originalPos;
    unsigned int secondPos = myhash2( x );
    while( array[ index ].info != EMPTY && array[ index ].element != x )
    {
        iteration = offset++ * secondPos;
        if ( ( originalPos + iteration ) > array.size( ) )
            index = ( originalPos + iteration ) % array.size( );
        else
            index = originalPos + iteration;
    }
    return ( index );
}

unsigned int hash1( const string& key, const int Tsize )
{
    //start the hashvalue at 0
    unsigned int hashVal = 0;

    //cout<<" the size of the table is: "<< Tsize <<endl;

    //add the ascii value for every word to hashval, multiply by 37 each time
    for ( int i = 0; i < key.length(); i++ )
        hashVal = 37 * hashVal + key[ i ];
    //mod hashval so it remains smaller than the table size
    hashVal %= Tsize;

    //return the itemes index value
    return hashVal;
}

i just realized i didnt include my second hash function
unsigned int hash2( const string& key, const int Tsize )
{
//store the sum of ascii numerical values
int hashVal = 0;

//add the values of all chars while multiplying each one with a prime number
for ( int i = 0; i < key.length(); i++ )
    hashVal = 29 * hashVal + key[ i ];

//mod the hashed value with a prime smaller than the table size, subtract that number
//with the prime just used and return that value
unsigned int index = 44497 - ( hashVal % 44497 );

return index;
}

it may not look like it but in the real deal tsize is being called correctly.

A: Your if statement is incorrect:
if ( ( originalPos + iteration ) > array.size( ) )
    index = ( originalPos + iteration ) % array.size( );
else
    index = originalPos + iteration;
}

Should be:
if ( ( originalPos + iteration ) >= array.size( ) )
    index = ( originalPos + iteration ) % array.size( );
else
    index = originalPos + iteration;
}

or better yet, since you're wasting more than the % op by doing the if, and the answer is the same regardless, you can just get rid of the if altogether:
index = ( originalPos + iteration ) % array.size( );

A: Or you could completely simplify it by saying
unsigned int hashkey = myhash1( x );
unsigned int stepSz = myhash2( x );
while( array[ index ].info != EMPTY && array[ index ].element != x )
        hashKey = (hashKey + stepSz) % capacity;
return hashkey;

Which accomplishes the same thing while making the while loop a lot smaller (and getting rid of the extra variable). I'm assuming you don't want to allow duplicates (hence the second condition in the while loop?).


text:
Q: circular/ring/360 laser Some time in the 1980s I was flipping through an Omni magazine and in one of their "new in science" sections they had a short blurb on a new type of laser that generated a "beam" that was a complete 360 degree disk. This was not scanned, the laser cavity itself purportedly did this directly. The article was quoting one of the Soviet journals, and the accompanying photo showed something that looked like it was built out of natural gas piping.
I can think of a couple of ways this might have been accomplished using conventional tech, even the mundane solution of shining through appropriate optics, but the right-up made it clear this is not what was going on.
I've looked for this device on a couple of occasions since, but google simply turns up circular saws. Anyone know anything about this?


text:
Q: Deserialize appsettings.json with json array into C# List I have a C# .Net Core Console Application thats supposed to check different Logfiles if these contain Errors and notifies the right person via Email. The Application has an appsetting.json that looks like this:
{
  "Programs": [
    {
      "name": "program 1",
      "LoggingPath": "C:\...",
      "Emails": [
        "person1@company.com",
        "person2@company.com",
        "person3@company.com"
      ]
    },
    {
      "name": "program 2",
      "LoggingPath": "C:\...",
      "Emails": [
        "person1@company.com",
        "person2@company.com",
        "person3@company.com"
      ]
    }
  ]
}

Now i want to convert this Json into a C# Object List to iterate through the different Programs and do my Log analyzing etc.
I used https://json2csharp.com to convert the Json into this C# Code:
public class Program
{
    public string name { get; set; }
    public string LoggingPath { get; set; }
    public List<string> Emails { get; set; }
}

public class Root
{
    public List<Program> Programs { get; set; }
}

My code to initialize the appsettings.json and deserialization looks like this:
public static void Main(string[] args)
{
    IConfiguration configuration;
    configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    JToken JtokenConfig = Serialize(configuration);

    Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(JtokenConfig.ToString());
}

But when I try this I get the following Error:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[LogAnalyzer.Model+Program]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

I can't change the Json to an array (Without the "Programs":) cause the appsettings.json builder requires an object and not an array.
I have also tried to use this Json to get rid of the array and use a dynamic C# property to deserialize the different object names but the deserialization also failed.
{
    "Programs": {
        "program 1": {
            "LoggingPath": "test",
            "Emails": [
                "person1@company.com",
                "person2@company.com",
                "person3@company.com"
            ]
        },
        "program 2": {
            "LoggingPath": "test",
            "Emails": [
                "person1@company.com",
                "person2@company.com",
                "person3@company.com"
            ]
        }
    }
}

I read countless stackoverflow threads and other websites but wasnt able to convert the Json into a C# List.
I hope someone here can help me or give me a hint.

A: you can install Microsoft.Extensions.Configuration.Binder Nuget package and try this code
using Microsoft.Extensions.Configuration;

List<Program> programs = configuration.GetSection("Programs").Get<List<Program>>();

Update
the second json you can deserialize to a dictionary
Dictionary<string,Program> programsDict = configuration.GetSection("Programs")
                                     .Get<Dictionary<string,Program>>();


text:
Q: SSH jump host solution I am researching the idea of implementing (using existing?) solutions of SSH jump hosts. There are two main use cases:
Organization wants to manage/limit/control the access to remote servers (certain people are allowed to login to certain servers). Organization wants to log commands issued by the user. As seamless as possible integration with organization infrastructure. One of the ideas was to use DNS to record designated remote, provide jump host's IP and capture connection.
The jump host based on LDAP will check if user is allowed to reach certain server and if so, will establish connection to remote and act like a proxy
Here are my questions:

*

*Does the similar solution already exist ? (I couldn't find any)

*What approach would you undertake to accomplish such use case(s) ? What do you think about utilizing DNS ?

*How to ensure that user will not be aware of any jumps hosts on the way ? e.g. He would still be able to use X forwarding (ssh someremote.host -X --other_option_that_should_work).


text:
Q: Circle Graphing Program Null Value Errors (Python 3.4) This is my program for graphing circles according to the radius and center coords that the user inputs.
import numpy as np
import matplotlib.pyplot as plt
def circle(r,h,k,domain):
    x = np.array(domain)
    y = eval(np.sqrt(r**2 - (x-h)**2) + k)
    plt.plot(x,y)
    plt.show
rad = float(input("Radius: "))
xcen = float(input("Center X Coordinate: "))
ycen = float(input("Center Y Coordinate: "))

circle(rad,xcen,ycen,np.linspace(-10,10,500))
print("Done")

When it is run I get these errors.
Warning (from warnings module):
  File "/Users/William/Documents/Science/PYTHON3/Circle.py", line 5
    y = eval(np.sqrt(r**2 - (x-h)**2) + k)
RuntimeWarning: invalid value encountered in sqrt
Traceback (most recent call last):
  File "/Users/William/Documents/Science/PYTHON3/Circle.py", line 13, in <module>
    circle(rad,xcen,ycen,np.linspace(-10,10,500))
  File "/Users/William/Documents/Science/PYTHON3/Circle.py", line 5, in circle
    y = eval(np.sqrt(r**2 - (x-h)**2) + k)
TypeError: source code string cannot contain null bytes

A: eval is not used for arithmetic evaluation in python, simply remove it from
y = eval(np.sqrt(r**2 - (x-h)**2) + k)

to obtain a valid
y = np.sqrt(r**2 - (x-h)**2) + k

also plotting each point as a separate data serie is rather a bad idea, you should create lists of x's and y's and then run.
plt.scatter(X,Y) # plt.plot() is used for line plots, not point plots
plt.show() # plt.show is the reference to the function, you need () to call it


text:
Q: Jquery multiple divs countup timer. One ends and next one starts and so on In Jquery I want to create multilevel level wise COUNT-UP Timer
For example timer for 1st div ends and timer for next div starts and so on till last div...
Main requirements.

*

*All div will have seconds and minuets count-up counter

*Only one div counter will work at a time. One ends and next div will start counter.

*Different timer counts are there for different DIVs

Following sample code demo works fine for 1st DIV but not working next all DIVs
Following is my HTMLCODE for multiple DIVs. Where I want to show time up counter for example  00:01 => 00:02 => .. => 00:60 =

    00:00

    00:00

    00:00

01:01

        00:00

    00:00

    00:00

Jquery/JavaScript Code
var totalSeconds = 0;

var div_1 = "div_1";
var timer_1_start = 0;
var timer_1_limit = 05;

var div_2 = "div_2";
var timer_2_start = 05;
var timer_2_limit = 10;

var div_3 = "div_3";
var timer_3_start = 10;
var timer_3_limit = 20;

var div_1_pointer =
    setInterval(
        function(){
            console.log(' ------> Inner function to setInterval for '+div_1);
            w3n_setTime(div_1,div_1_pointer,timer_1_start,timer_1_limit);
        },
    1000 );

/*
var div_2_pointer =
    setInterval(
        function(){
            console.log(' ------> Inner function to setInterval for '+div_1);
            w3n_setTime(div_2,div_2_pointer,timer_2_start,timer_2_limit);
        },
    1000 );
*/

function w3n_setTime(div_id,div_pointer,timer_start,timer_limit){

    // console.log(" total mins ==> "+pad(parseInt(totalSeconds / 60)) );
    // console.log(" total seconds  ==============> "+pad(totalSeconds % 60));

    if(parseInt(pad(totalSeconds % 60)) === parseInt(timer_limit)){

        console.log(" Timer complete for "+div_id);
        clearInterval(div_pointer);
        $('#'+div_id+' div#done').html("Done");

    }

    ++totalSeconds;

    //secondsLabel.innerHTML = pad(totalSeconds % 60);
    //minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));

    $('#'+div_id+' span#seconds').text(pad(totalSeconds % 60));
    $('#'+div_id+' span#minutes').text(pad(parseInt(totalSeconds / 60)));

}

function pad(val) {
    var valString = val + "";
    if (valString.length < 2) {
        return "0" + valString;
    } else {
        return valString;
    }
}

Issue : I am able to make code work for one DIV only and not for all.

A: Try following code.
I have modified code to match your requirements. It has only 1 function which will work for all your main DIV.
You have to count and mention length of your DIVs in starting.
Let me know if this works for you.

var totalSeconds = 0;
var game_timer = Array(1,1,1); // time in mins
var game_level = 1; // for start level

var div_pointer =
    setInterval(
        function(){

            var c = game_timer.length; // total game level

            if(parseInt(pad(totalSeconds / 60)) == game_timer[game_level-1]) {

                $('#div_'+game_level+' div#done').html("Done");

                game_level ++;
                totalSeconds=0;
            }

            if(game_level==c && parseInt(pad(totalSeconds / 60)) === parseInt(game_timer[c-1])){
                clearInterval(div_pointer);
            }

            ++totalSeconds;
            $('#div_'+game_level+' span#seconds').text(pad(totalSeconds % 60));
            $('#div_'+game_level+' span#minutes').text(pad(parseInt(totalSeconds / 60)));
        },
    1000 );

function pad(val) {
    var valString = val + "";
    if (valString.length < 2) {
        return "0" + valString;
    } else {
        return valString;
    }
}

    00:00

    00:00

    00:00


text:
Q: Specifying the same gem twice for development/test and production but different paths Sometimes you make a gem that is specific to a project. This helps abstract and pull some of the "responsibility" out of the main Rails app and into a more modular place.
The gem would be located here on you application:
gem 'example_gem', path: './example_gem'

You bundle and everything is OK. Now, you git init the gem and store it in its own repo on github. You try doing this to keep it developer friendly:
group :development, :test do
  gem 'example_gem', path: './example_gem'
end

group :production do
  gem 'example_gem', github: 'company/example_gem'
end

You pat yourself on the back for increasing your workflow, but after running bundle you get:
Your Gemfile lists the gem example_gem (>= 0) more than once.
You should probably keep only one of them.
While it's not a problem now, it could cause errors if you change the version of just one of them later.
You cannot specify the same gem twice coming from different sources.
You specified that example_gem (>= 0) should come from source at ./example_gem and git://github.com/company/example_gem.git

The workflow here is to be able to edit the gem in development and when you're done, commit those changes and push them to Github. BUT, when on development, you don't want to have to do a git commit, git push, and a bundle update on your main app just to see a small change.
Does anyone know of a better way to solve this issue?

A: Yes, there is a better way: First, have the gem as a git gem in all environments
gem :example_gem, :git => 'git@github.com:foo/example_gem', :branch => :master #you need to set a branch

Then in your app's folder run
bundle config --local local.example_gem /path/to/gem

This will edit .bundle/config to set this option (make sure this file isn't checked into source control!) and tells bundler to get the gem from that path.
At the point when you are going to push your commits you have to be a little bit careful: if your app depends on not yet committed changes to the gem then clearly things will break. In addition as you commit to the repository for the example gem the rails app's Gemfile.lock will get updated. If you push a Gemfile.lock that references a commit that only exists in your copy of the example_gem repo then other users will be stuck.

A: this works for me.
foo = "https://github.com/me/my-development-version-gem.git"
group :production do
    foo = "https://github.com/me/my-production-version-gem.git"
end
gem "foo", :git => foo

in my case i need different branchs for envs to engine


text:
Q: Insert scopedSlot into d3 svg using foreignObject I'm creating a chart component using d3js and Vue (v2). In some parts, I want to support custom user content using scoped slots (in this case, custom tooltips)
<my-chart>
  <template slot="tooltip" slot-scope="{ data }">
    <span>{{ data }}</span>
  </template>
</my-chart>

But I'm struggling to render this using d3js on a vuejs component render function. I'm trying to do something like:
g?.append("foreignObject").html(
  this.$scopedSlots["tooltip"]({
    event,
  }),
);

Obviously, the html method isn't appropriated. I can't find anything like this online. All other examples use the component template to insert the foreignObject and Vue component on the SVG. Nothing using d3js
EDIT
As user I refer to developers. This code is for a lib.

A: Just in case anyone wants to implement something like this, I manage to resolve my issue.
Background
SVG has a concept of foreignObject which allows me to inject HTML inside an SVG. The next step is, somehow, to render the Vue component to HTML.
I'm using vue2, Vuetify, and d3js v6
Rendering the component
this.$scopedSlots["tooltip"]({
    event,
  }),

returns a VNode[], so using Vue.extend I create a new component, instantiate it and mount it to a div inside the foreignObject like this:
// Call the scoped slot, which returns a vnode[]
const vnodes = this.$scopedSlots["tooltip"]({
    event,
  });
const id = "RANDOM_GENERATED_ID";
// Append a foreignObject to an g
const fo = g?.append("foreignObject");
// Append a div to the foreignObject, which will be the vue component mount point
fo?.append("xhtml:div").attr("id", id);
// Create a new component which only render our vnodes inside a div
const component = Vue.extend({
    render: (h) => {
      return h(
        "div",
        {staticClass: "foreign-object-container"}
        vnodes,
      );
    },
  });
// Create a instance of this new component
const c = new component();
// I'm using vuetify, so I inject it here
c.$vuetify = this.$vuetify;
// Mount the component. This call will render the HTML
c.$mount("#" + id);
// Get the component rect
const bbox = c?.$el.getBoundingClientRect();

// Resize the ForeignObject to match our injected component size
return fo
    ?.attr("width", bbox?.width ?? 0)
    .attr("height", bbox?.height ?? 0);

This successfully renders our component inside an SVG using d3js. At least it appears inside the DOM.
Problems
At this point, I faced 2 new problems.
Invalid component size
After rendering the Vue component inside the foreignObject it reported width equals 0. So, based on this I used the next styles:
.foreign-object-container {
  display: inline-flex;
  overflow: hidden;
}

And voilá, habemus a visible Vue component.
Scroll, ForeignObject, and the old Webkit Bug
My use case is this: The chart is responsive, so it re-renders after every container resizes (with some debounce), but to prevent deformations I set a minimum width to every element. With some screen sizes, this provokes some overflow, which inserts a scrollbar (browser behavior).
This is exactly what I want. But I'm using some Vuetify components on my scopedSlot which have a position: relative style.
Enters, an old bug on WebKit (Google Chrome, Safari, and Edge Chromium). This is better explained here and here
The solution in my case is simple. As I stated before, my foreignObject was resized to match the rendered component. So, to prevent my components to be wrongly drawn, I change my styles a little bit.
.foreign-object-container {
  display: inline-flex;
  overflow: hidden;
  position: sticky;
  position: -webkit-sticky;
}

Now, my teammates can use a generic chart with scroll support and customize some pieces of it using any Vue component (at least for now )


text:
Q: Object not found! after redirect route in Fuel php Below is the directory structure of my fuelphp project

*

*fuel

*logs

*public

*tmp

In public folder i have

*

*assets

*index.php

When I hit any URL other than base URL it throws following error
Object not found error
here is my login code
public function action_index(){

    $html = new Template();

    if(Session::get("logged_in")){

      Response::redirect('/test-newsletter');

      exit(0);
    }
     // die("in ifss");
    if(Input::post()){

      $username = Input::post('username','');
      $password = Input::post('password','');

      if($username === "username" && $password === "password") {

        Session::set('logged_in', true);

        Response::redirect('/test-newsletter');

      }else{
        $html->assign('message','Wrong username or password');
      }

    }

    return $html->fetch('login.tpl');

  }

here is my routes.php
<?php

return array(

  "_root_"  => "default/index",
  "logout" => "default/logout",
    "_404_"   => "default/404",
  "time" => "default/time",
  "test"  => "default/test",

  "birthdays" => "backstage/birthdays",
  "earned-status" => "backstage/earned_status",
  "nearly-new-status" => "backstage/nearly_new_status",
  "placed-order" => "backstage/placed_order",
  "user-history" => "backstage/user_history",
  "test-newsletter" => "backstage/test_newsletter",
  "preview-email" => "backstage/preview_email",

  "view-email/:id" => "backstage/view_email",

  "api/set-date" => "backstage/api_set_date"
);

this is the Backstage controller test_newsletter function
public function action_test_newsletter(){
    die("here");
    $submitted = Input::post("submit", false);
    $points = Input::post("points", "");
    $email = Input::post("email", "");
    $type = Input::post("type", "");

    $html = new Template();
    $html->assign("points", $points);
    $html->assign("email", $email);
    $html->assign("type", $type);
    $html->assign("message", "");

    if($submitted){
      $testService = new TestService(trim($type), trim($email), trim($points));

      if($testService->isValid()){
        $testService->processEmail();
        $html->assign("message", "Email Sent!");

      }else{
        $html->assign("message", $testService->getErrorMesssage());
      }
    }

    return $html->fetch("test_newsletter.tpl");
  }

But after login its not going to test_newsletter instead its showing me Object not found error.
** I have read that wee need to put .htaccess somewhere in our project but I am not clear about that. Can any guide me **

A: Try this .htaccess in your web root folder (usually public/ ?):
RewriteEngine On

# The following rule tells Apache that if the requested filename
# exists, simply serve it.

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

# The following rewrites all other queries to index.php. The
# condition ensures that if you are using Apache aliases to do
# mass virtual hosting, the base path will be prepended to
# allow proper resolution of the index.php file; it will work
# in non-aliased environments as well, providing a safe, one-size
# fits all solution.

RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]


text:
Q: invalid: EXPKEYSIG C8CAB6595FDFF62 I am getting the following message when I type 'sudo apt update' in the terminal:
W: GPG error: http://ddebs.ubuntu.com focal Release: The following signatures were invalid: EXPKEYSIG C8CAB6595FDFF622 Ubuntu Debug Symbol Archive Automatic Signing Key (2016) <ubuntu-archive@lists.ubuntu.com>
E: The repository 'http://ddebs.ubuntu.com focal Release' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: GPG error: http://ddebs.ubuntu.com focal-updates Release: The following signatures were invalid: EXPKEYSIG C8CAB6595FDFF622 Ubuntu Debug Symbol Archive Automatic Signing Key (2016) <ubuntu-archive@lists.ubuntu.com>
E: The repository 'http://ddebs.ubuntu.com focal-updates Release' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

A: It seems that you forget to add GPG key for the ddeb repository.
Open terminal and type:
sudo apt install --reinstall ubuntu-dbgsym-keyring

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys F2EDC64DC5AEE1F6B9C621F0C8CAB6595FDFF622

sudo apt-get update


text:
Q: JavaFX webpage doesn't show in mobile browsers I have made some JavaFX based webpage but it doesn't show in mobile web browsers but works fine in desktop browsers. I wonder there is some way to port/convert this to a mobile version.
Thanks,

A: OK, I found the current version JavaFX doesn't support mobile web browsers...-_-


text:
Q: Firemonkey dragging image not showing on screen The following first image is taken from a Virtual Machine and second is taken from a real pc. Why don't I see the dragging image on the real PC?
Virtual Machine

Real PC


text:
Q: Falha em resposta de aplicação swing Tenho uma aplicação swing no qual verífico se a palvra digitada está correta ou errada.
String palavra[] = new String[3];
palavra[0] = "bar";
palavra[1] = "ola";
palavra[2] = "alo";
String p = jTextField1.getText();
int cont = 0;
while (cont < 3) {
    if (palavra[cont].equals(p)) {
        JOptionPane.showMessageDialog(this, "EXISTE");
        jTextField1.setText("");
        break;
    } else {
        JOptionPane.showMessageDialog(this, "NAO EXISTE");
        jTextField1.setText("");
        break;
    }
    cont++;
    // TENTATIVA DELE RETOMAR O LOOP DEPOIS DO BREAK
}

Além da primeira palavra "bar", não estou conseguindo validar as seguintes. E por muitas vezes na tentativa de mudar o código, acabo entrando em um looping que fica retornando Não Existe diversas vezes.

A: Pela sua descrição não condiz com o que realmente está acontecendo.
    String palavra[] = new String[3];
    palavra[0] = "bar";
    palavra[1] = "ola";
    palavra[2] = "alo";
    String p = jTextField1.getText();
    int cont = 0;
    while (cont < 3) {
        if (palavra[cont].equals(p)) { // Só verifica aqui uma vez. Porque? Repare o seu else.
           JOptionPane.showMessageDialog(this, "EXISTE");
           jTextField1.setText("");
           break;

        // Se a condição de cima é falsa então você diz aqui para sair do laço,
        // o laço nunca vai dar dois loops, ou seja só vai dar a resposta certa quando
        // o textfield tiver o valor "bar".
        } else {
            JOptionPane.showMessageDialog(this, "NAO EXISTE");
            jTextField1.setText("");
            break; // Manda sair do laço while, sem ao menos ter dado todos os loops.
        }
        cont++;
        // TENTATIVA DELE RETOMAR O LOOP DEPOIS DO BREAK.
    }

O código não apresenta nenhuma falha, a falha está na lógica do que você quer fazer.
SOLUÇÃO
Vou deixar bem comentado o código para um melhor entendimento. Essa é uma das maneiras para resolver esse problema.
String palavra[] = {"bar", "ola", "alo"}; // Maneira mais elegante de inicializar um vetor
String p = jTextField1.getText(); // Recupera String do componente textfield.
boolean existe = false; // Declaro uma flag que indica se encontrou ou não uma palavra igual.

// Quando você sabe o tamanho máximo que vai percorrer o laço, utilize o for.
for (int i = 0 ; i < 3; i++) {
    if (palavra[i].equals(p)) { // Percorre vetor de acordo com i.
        existe = true; // Altera valor da flag.
        break; // Sai do laço se encontrou palavra igual.
    }
}
if (existe) {//verifica flag
    JOptionPane.showMessageDialog(this, "EXISTE");
} else {
    JOptionPane.showMessageDialog(this, "NAO EXISTE");
}
jTextField1.setText("");


text:
Q: "some" vs "about" All examples are mine.
Could you help me to deal with them?
(1a) There are some thousand people. - as far as I know, it's correct
(1b) There are some a thousand people. - ??? (I don't know if it's correct)
(1c) There are some one thousand people. - as far as I know, it's correct
(2a) There are about thousand people. - ??? (I don't know if it's correct)
(2b) There are about a thousand people. - I'm sure it's correct
(2c) There are about one thousand people. - I'm sure it's correct

A: "about" is the normal way to express approximate values.  Use this, but you do need "a" or "one", so 2a is not correct.
Using some as an adverb like this is rather rare and informal, 1a and 1c  are rare, but correct.


text:
Q: I am unable to get splatting to work with New-ADUser using given and created attributes I am processing an array of AD User data pulled from one domain to recreate in another. I have created a hash table linking the New-ADUser parameters with the user data imported from a CSV (populated from the domain I intend to recreate). When I call New-ADUser with the hash table, the user is not created and there are no error.
Here is the hash table:
$NewUserAttr = @{
    'Name'              = $ADUser.UsersName
    'SamAccountName'    = $ADUser.UsersSamAccountName
    'Company'           = $ADUser.UsersCompany
    'Department'        = $ADUser.UsersDepartment
    'DisplayName'       = $ADUser.UsersDisplayName
    'EmailAddress'      = $ADUser.UsersMail
    'EmployeeID'        = $ADUser.UsersEmployeeID
    'Enabled'           = $UsersEnabled
    'GivenName'         = $ADUser.UsersGivenName
    'Initials'          = $ADUser.UsersInitials
    'Manager'           = $ADUser.Manager
    'MobilePhone'       = $ADUser.UsersMobileNum
    'OfficePhone'       = $ADUser.UsersTelephoneNumber
    'PostalCode'        = $ADUser.UsersPostalCode
    'State'             = $ADUser.UsersST
    'StreetAddress'     = $ADUser.UsersStreetAddress
    'Surname'           = $ADUser.UsersSN
    'Title'             = $ADUser.UsersTitle
    'userPrincipalname' = $ADUser.UsersUPN
    'Path'              = $ParentOU
    'Server'            = $TargetDomain

    'OtherAttr' = @{
        'c'                  = $ADUser.Usersc
        'GIDNumber'          = $ADUser.UsersGIDNumber
        'l'                  = $ADUser.UsersL
        'LoginShell'         = $ADUser.UsersLoginShell
        'msSFU30Name'        = $ADUser.UsersMsSFU30Name
        'msSFU30NisDomain'   = $ADUser.UsersMsSFU30NisDomain
        'PhysicalDeliveryOfficeName' = $ADUser.UsersPhysicalDeliveryOfficeName
        'SSN'                = $ADUser.UsersSSN
        'Uid'                = $ADUser.UsersUid
        'uidNumber'          = $ADUser.UsersUidNum
        'unixHomeDirectory'  = $ADUser.UsersUHD
    }
}

PS > New-ADUser @NewUserAttr

I have reduced the NewUserAttr to Name, SamAccountName, Path, and Server and that did create the user, but that is far less parameters than what I need.

A: Continuing from my comments:
To avoid empty fields from being assembled in the attributes Hashtable to use for splatting, you could create two lookup tables in which you  map the CSV header names with the actual AD user attribute names.
Something like this:

    # create two mapping lookup Hashtables for 'normal' attributes and one for the OtherAttributes
    # format is: PropertyNameFromCsv = PropertyNameForActiveDirectory
    $attribMap = @{
        UsersName           = 'Name'
        UsersSamAccountName = 'SamAccountName'
        UsersCompany        = 'Company'
        Usersc              = 'Country'
        Manager             = 'Manager'
        # etc.
    }

    $otherMap = @{
        UsersGIDNumber        = 'GIDNumber'
        UsersLoginShell       = 'LoginShell'
        UsersmsSFU30Name      = 'MsSFU30Name'
        UsersmsSFU30NisDomain = 'MsSFU30NisDomain'
        # etc.
    }

Next, import the CSV and loop over each entry:
$csv = Import-Csv -Path 'X:\your_importFile.csv'

foreach ($item in $csv) {
    # two empty Hashtables for splatting
    $NewUserAttr = @{}
    $OtherAttr   = @{}
    # pre fill the default attributes you need for all users
    $NewUserAttr['Enabled'] = $UsersEnabled
    $NewUserAttr['Server']  = $TargetDomain
    $NewUserAttr['Path']    = $ParentOU

    # loop over the properties for each item in the CSV and only store
    # the ones that are not empty and for which you can find a mapping
    $item.PsObject.Properties | ForEach-Object {
        if (![string]::IsNullOrWhiteSpace($_.Value)) {
            if ($attribMap.Contains($_.Name))    { $NewUserAttr[$attribMap[$_.Name]] = $_.Value }
            elseif ($otherMap.Contains($_.Name)) { $OtherAttr[$otherMap[$_.Name]] = $_.Value }
        }
    }
    # join the hashtables together if we have OtherAttributes
    if ($OtherAttr.Count) { $NewUserAttr['OtherAttributes'] = $OtherAttr }

    # now try and create the new user
    try {
        New-ADUser @NewUserAttr -ErrorAction Stop
    }
    catch {
        Write-Warning "Error creating user $($NewUserAttr.Name): $($_.Exception.Message)"
    }
}

A: I run into this often with named parameters and null values. To avoid null values for your named parameters which $null indicates the parameter should be omitted rather than provided, follow these rules when creating the splat-hashtable:

*

*When defining the hashtable, define any properties that will not (or should not be) $null, like so:
$splatArgs = @{
  ParameterOne = 'Value'
  ParameterTwo = 'OtherValue'
}

*For parameters that may or may not need to be provided based on whether its value is $null (or evaluates falsey), conditionally add it to the hashtable:
if( $someVar ) {
  $splatArgs.ConditionalParameter = $someVar
}

Repeat 2. for each conditional argument you have. Alternatively, you could initialize the hashtable with all possible parameter names and values, then strip them out after after checking falsiness, comparing to $null, etc.
  # You could do any condition here but in this example,
  # We will do a simple falsiness test on each key's value
  $removeParameterNames = $splatArgs.Keys | Where-Object {
    !( $splatArgs.$_ )
  }

  # Use another loop here since we don't want to modify the hashtable
  # while iterating over its keys
  foreach( $key in $removeParameterNames ) {
    $splatArgs.Remove($key)
  }

A: Here is what I ended up getting to work, which is very similar to what Bender recommended and what Richard from the link in my above comments recommended.
$NewUserAttr = @{
    'Name'                  = $ADUser.UsersName
    'SamAccountName'        = $ADUser.UsersSamAccountName
    'AccountPassword'       = (ConvertTo-SecureString -AsPlainText "<Ab@1Cd!2>" -Force)
    'Company'               = $ADUser.UsersCompany
    'Department'            = $ADUser.UsersDepartment
    'DisplayName'           = $ADUser.UsersDisplayName
    'EmailAddress'          = $ADUser.UsersMail
    'EmployeeID'            = $ADUser.UsersEmployeeID
    'Enabled'               = $UsersEnabled
    'GivenName'             = $ADUser.UsersGivenName
    'MobilePhone'           = $ADUser.UsersMobileNum
    'OfficePhone'           = $ADUser.UsersTelephoneNumber
    'SurName'               = $ADUser.UsersSN
    'Title'                 = $ADUser.UsersTitle
    'userPrincipalname'     = $ADUser.UsersUPN
    'Path'                  = $ParentOU
    'Server'                = $TargetDomain

    'OtherAttr' = @{
        'GIDNumber'                     = $ADUser.UsersGIDNumber
        'LoginShell'                    = $ADUser.UsersLoginShell
        'msSFU30Name'                   = $ADUser.UsersMsSFU30Name
        'msSFU30NisDomain'              = $ADUser.UsersMsSFU30NisDomain
        'Uid'                           = $ADUser.UsersUid
        'uidNumber'                     = $ADUser.UsersUidNum
        'unixHomeDirectory'             = $ADUser.UsersUHD
    }
}

# Check the uncommon attributes and add them to the hash table if not null
if($ADUser.Usersl){$NewUserAttr.add('City',$ADUser.Usersl)}
if($ADUser.Usersc){$NewUserAttr.add('Country',$ADUser.Usersc)}
if($ADUser.UsersInitials){$NewUserAttr.add('Initials',$ADUser.UsersInitials)}
if($ADUser.Manager){$NewUserAttr.add('Manager',$ADUser.Manager)}
if($ADUser.UsersPostalCode){$NewUserAttr.add('PostalCode',$ADUser.UsersPostalCode)}
if($ADUser.UsersST){$NewUserAttr.add('State',$ADUser.UsersST)}
if($ADUser.UsersStreetAddress){$NewUserAttr.add('StreetAddress',$ADUser.UsersStreetAddress)}
if($ADUser.physicaldeliveryofficename){$NewUserAttr.OtherAttr.add('physicaldeliveryofficename',$ADUser.physicaldeliveryofficename)}
if($ADUser.UsersSSN){$NewUserAttr.OtherAttr.add('SSN',$ADUser.UsersSSN)}

#Add new user to destination domain
try {
    $UserExists = Get-ADUser -Identity $ADUser.UsersName -Server $TargetDomain
    if ($UserExists) {
        "Exists,$($ADUser.UsersName),$ParentOU`n" | Out-File $UserCreationLog -Append -Force
    } else {
        New-ADUser @NewUserAttr -ErrorAction Continue
        #Change password
        "Added,$($ADUser.UsersSamAccountName),$($ADUser.UsersName),$ParentOU`n" | Out-File $UserCreationLog -Append -Force
    }
} catch {
    $ErrorMsg = $_.Exception.Message
    Write-Log -Message "Unable to create user, $($ADUser.UsersName): $ErrorMsg." -Severity Error -LogPath $LogFile
    Write-Log -Message "Failed users attributes: $NewUserAttr $($NewUserAttr.OtherAttr)" -Severity Error -LogPath $LogPath
}

Now I just need to test each of these suggest answers to see which is the fastest! Thanks everyone!!


text:
Q: Query ColdFusion Externally Is it possible to submit a query to a form built with ColdFusion from a page built on another site. The form I have in mind is this one.. http://web.sba.gov/pro-net/search/dsp_dsbs.cfm
I'd like to build a page on my site with its own version of that form and when users click submit have it pass the information to the site above and load the search results based off of their selections. Essentially just creating a different set of controls for it. I just wasn't sure if this was even possible.

A: Yes, this is possible. Submitting a HTML form simply composes a GET/POST request (depending on the method attribute in your form) and sends it to the URL stated in the action attribute in your form. The URL can be any resource and is not restricted to the same origin.
Edit: If you simply want to host a form on your own site, just make sure to keep the field names, form action and form method.
You can handle the GET/POST request the same way you would do it on your own page. In ColdFusion the form fields would be available in the URL scope (when <form method="get">) or in the FORM scope (when <form method="post">).


text:
Q: Slanted slash, angle control How can I achieve this angled slash (/) using CSS? It should be responsive and should also have IE 8 support?

A: You can use an element and hide the unwanted parts with pseudo elements and borders (which are supported by IE8):

div{
    position:relative;
    width: 100px; height: 100px;
    background: #000;
}
div:before, div:after{
    content: '';
    position: absolute;
}
div:before{
    top: 0; left: 0;
    border-left: 99px solid #fff;
    border-bottom: 99px solid transparent;
}
div:after{
    bottom: 0; right: 0;
    border-right: 99px solid #fff;
    border-top: 99px solid transparent;
}

You can control the slant by changing the border widths on the pseudo elements. For an explanation of how this works, see here: How do CSS triangles work?
Although this can't be implemented over an image or gradient because of the plain color triangles, It can be responsive.

A: If you want to use CSS for creating a content,
You must use the CSS content property
and you must apply it to CSS property with ::before selector.
Here is the example

.number::before {content:"\2215"}
12

The only difference is,you must use ::before with one semicolon for IE8 :before
IE8 Supports both the CSS :before Pseudo selector,and CSS content property.
For the content property,you need to find the specific "slash" that you want,in the Unicode table


text:
Q: Allow quick categorization of downvotes / hint templates When a reviewer feels something is off about a question, he/she has two choices:

*

*Flagging the question with a category

*Downvote and optionally leave a comment

Leaving a comment is encouraged by a message saying something like: 'Please consider adding a comment ...'
However, writing a comment takes time (unless one has a user-script with templates), and I assume many downvotes have common causes, such as:

*

*Mostly off-topic (but not in the off-topic list of reasons in the flags)

*Badly formatted

*Badly phrased

*Answer easily found via search engine, did not read the manual

I think it would be helpful if there was a one-click way of justifying a downvote, possibly adding a auto-generated comment (or an upvote on the same comment category).
Alternatively providing comment templates in the UI, such as these already shared in questions like this (which indicates there is a whole cult about many new posts doing the same mistakes requiring same old comments):
Repository of useful pro-forma comments


text:
Q: How Get Other Value from select option ionic 3 I have something like this
.html
<ion-item>
    <ion-label>Choose Industry Type</ion-label>
    <ion-select (ionChange)="getOuterName()" [(ngModel)]="getSelectedValue">
        <ion-option *ngFor="let some of someItems" value="{{some.id}}">
            {{some.name}} </ion-option>
    </ion-select>
</ion-item>
<p>{{getSelectedValue}}</p>

.ts
someItems = [{'id': 1, 'name':'Agriculture','othervalue':'123'},
          {'id': 2, 'name':'Chemicals','othervalue':'1234'},
          {'id': 3, 'name':'Pesticides','othervalue':'12345'}];
getOuterName(){
 console.log(this.getSelectedValue);
 let term = this.someItems.filter(item => item.othervalue ===this.getSelectedValue );
}

can i get 'othervalue' to show in 'getSelectedValue' without changing value="{{some.id}}" in ion-option ?

A: What you can do is just bind the whole object into value
html:-
<ion-item>
        <ion-label>Choose Industry Type</ion-label>
        <ion-select (ionChange)="getOuterName()" [(ngModel)]="getSelectedValue"  >
            <ion-option *ngFor="let some of someItems" [value]="some" >
                {{some.name}} </ion-option>
        </ion-select>
    </ion-item>

in .ts:-
 someItems = [{'id': 1, 'name':'Agriculture','othervalue':'123'},
          {'id': 2, 'name':'Chemicals','othervalue':'1234'},
          {'id': 3, 'name':'Pesticides','othervalue':'12345'}];

getOuterName(){
// Your can call your **this.getSelectedValue** and its properties
 console.log( this.getSelectedValue.id + this.getSelectedValue.name);

 let term = this.someItems.filter(item => item.othervalue ===this.getSelectedValue.othervalue );
}

this way you can have both id and othervalue


text:
Q: If $f(f(x))=-f(x)$,does it necessarily follow that $f(x)=-x$? Is there any counterexample other than $f(x)=0$?
The actual problem states: Find a function $f: \mathbb{R} \to \mathbb{R}$, such that $f(f(x+y))=x-f(y)$.  By substituting $x=0$, we get $f(f(y))=-f(y)$. Is it safe to conclude that $f(y)= -y$ for all $y$?

A: If $f$ is surjective, absolutely. Then, for any $y \in \mathbb{R}$, we have $f(x) = y$ for some $x \in \mathbb{R}$, so
$$f(y) = f(f(x)) = -f(x) = -y.$$
If you look back at the original equation, $f(f(x + y)) = x - f(y)$, it's not difficult to show that this is surjective; fix $y$ and let $x$ vary. So, indeed, $f(x) = -x$ for all $x$.
Here's an example of a function satisfying $f(f(x)) = -f(x)$ that isn't surjective:
$$f(x) = \begin{cases}-x & \text{if $-1 \le x \le 1$} \\ -\frac{2x}{x^2+1} & \text{otherwise}\end{cases}.$$
The key is that such a function must be $-x$ on its range, but free to be anything else outside the range. I opted for a continuous odd function!


text: Q: Quick question regarding C*-algebras/W*-algebras I'm reading about C*-algebras and W*-algebras, and I want to know the differences between the two,in other words properties you can find in W*-algebras that aren't in C*-algebras and the other way around.


text:
Q: ChromeOS errors in GCP Logging I'm seeing errors in StackDriver logging for my Compute instance. The logs are showing repeated issues every hour, creating a lot of noise. I have a Spring Boot API deployed in a container to a VM in Compute Engine using latest stable version of Container OS.
I'm relatively new to GCP and don't understand what is causing this issue, searches have come up empty so far.
Failed to call method: org.chromium.SessionManagerInterface.RetrieveActiveSessions: object_path= /org/chromium/SessionManager: org.freedesktop.DBus.Error.ServiceUnknown: The name org.chromium.SessionManager was not provided by any .service files

CallMethodAndBlockWithTimeout(...): Domain=dbus, Code=org.freedesktop.DBus.Error.ServiceUnknown, Message=The name org.chromium.SessionManager was not provided by any .service file

Error calling D-Bus proxy call to interface '/org/chromium/SessionManager': The name org.chromium.SessionManager was not provided by any .service files

The same 3 lines are repeating every hour. Anyone aware of what might be causing this or how to fix/suppress these?

A: I looked into this error, and as per my findings:

*

*The error message that you have been receiving is a manifestation of Chrome to reliably exit shortly after starting up.

*The UI's job (which encompasses Chrome, the session_manager and the window manager) gets shut down by upstart because of it's thrashing, and when the test tries to restart the session_manager, the session_manager cannot communicate it over to the D-Bus.

The crash collection software in Container OS was originally for Chromebooks (The laptop using Chrome browser). So the code typically expects Chrome and some other related software on the system.
However, Container OS is a server OS, and does not have Chrome. So if Chrome is missing, the software will report some errors. They are actually not real failures, just some verbose error messages.
Overall, It is safe to ignore these logs and continue using your VM Instances.
Hope this helps.


text:
Q: Karma Chai How to access DOM element I am writing test cases using Karma Mocha.
Following is my function:
fun : function()
{

  if(a == 1)
  $("#test").hide();

}

We set the DOM element property based on some condition.
While writing its test:
   it('fun', function (){
     var a = 1;
   // how do I test the DOM element.
   // Is it possible to access the DOM element of the source file in the test file.

    })

I tried using chai-jquery but it accesses only body and not the other elements.I guess it works on DOM elements of test file.
Can anyone please help.?

A: I assume you have your jQuery loaded upon testing then you would select you element with $('#test') and then do you tests.
Like so:
describe('obj.fun', function (){
  before(function() {
    $('

').appendTo(document.body);
  });

  after(function() {
    $('#test').remove();
  });

  it('should hide the element when a is 1', function() {
    var $test = $('#test');
    expect( $test.is(':hidden') ).to.be.false;
    obj.a = 1;
    obj.fun();
    expect( $test.is(':hidden') ).to.be.true;
  });
});


text:
Q: React i18next-http-backend won't load translation json file from Public folder I have React app in which I am trying to get language options set up using i18next http backend. However it seems that when the call is made to get the json file it is not returned correctly.
My json files are stored in the Public folder in a subfolder locales and the call to fetch these is made:
backend: {
    loadPath: "/locales/{{lng}}/translation.json",
},

Looking at the network tab I am getting 200:

But if I put that URL directly into the browser I get the app navbar and an empty page as if it is loading an instance of the app, rather than grabbing the json file.
How do I get around this?

A: This was resolved by creating a .env file in the root of the project and adding the line PUBLIC_URL=sub_folder where subfolder was where my app was.


text:
Q: PHP SESSION data lost between page loads with WAMPserver 2.0 on localhost I have a PHP authentication system on my website using the $_SESSION variable.
A form submits a username and password to the file "login.php". It is handled like this:
<?php include '../includes/sessionstart.inc.php'; ?>
<?php ob_start(); ?>

if($_POST){
    $q = mysql_query("SELECT id, company FROM users WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".md5($_POST['password'])."'");
    if(mysql_num_rows($q) >= 1){
        $f = mysql_fetch_Array($q);
        $_SESSION['company'] = $f['company'];
        $_SESSION['id'] = $f['id'];
        $_SESSION['logedin'] = true;
        session_write_close();

        ob_clean();
        header("Location: index.php");

}

Afterwards, index.php is loaded and checks whether 'logedin' is true.
<?php include '../includes/sessionstart.inc.php'; ?>
<?php if(!isset($_SESSION['logedin'])) header('Location: login.php'); ?>

On my production server, it continues, but on my Wampserver, it reverts back to login.php. I notice that Wampserver is very slow in page loading, this might have to do something with it. That's why I included the session_write_close, to make sure session data is saved before the pages are switched, but it doesn't help.
The contents of session_start.inc.php are simply:
<?php
    session_start();
?>

I used to have more code in there, but at the moment it's just this. The problem also existed before I started using an include file.
Does anybody have an idea what I'm doing wrong? Why doesn't Wampserver transmit my SESSION data to the next PHP file?

A: WAMP server 2  - settings are not set by default for $_SESSION var.
PHP.ini
requires the following settings
C:\wamp\bin\apache\apache2.4.2\bin\php.ini
session.cookie_domain =
session.use_cookies = 1
session.save_path = "c:\wamp\tmp"   ;ensure the \ is used not /

Session testing -
load.php -- load $_SESSION var.
<?PHP
session_start();
$_SESSION['SESS_MEMBER_ID'] = 'stored variable';
session_write_close();
header("location:print.php");
?>

print.php -- print $_SESSION var.
<?PHP
session_start();
var_dump($_SESSION);
?>

run the script in your browser var_dump() should produce results
go to c:\wamp\tmp Files containing the session data will appear here.

A: First of all: the index logedin seems strange for keeping track of a user being logged in. Is this just a typo on SO, or really a code-typo?
Second (depending on the desired behavior), try another approach for making pages login-protected. Your page should look something like
<?php
  include 'login.inc.php';

  if(authorized()) {
    // put some more script here, if needed
    ?>
    // put some plain HTML here
    <?php
  }
?>

Where login.inc.php handles the session, cookies. In particular, the authorized function should return TRUE if a client is already logged in. If a client is not logged in, it should display a form with action $_SERVER['PHP_SELF'] and return FALSE. If you name the submit-input something like login_submit, you can let login.inc.php handle the verification.
This way, you don't need to refer users to a dedicated login page, and after logging in, user are directly shown the requested page. You can tweak this a bit to make query-strings persistent through login as well.

A: Try to replace
if($_POST){...}

with
if( isset($_POST['username']) && isset($_POST['password']) ){...}

... at least for debugging purposes. It's possible that some different settings are causing a non-empty $_POST array where it's not expected.
Also, your code seems to be missing exit() calls after header() redirections. Sending an HTTP Location header doesn't automatically stop your script.

A: I had this problem using WAMPSERVER for development on /localhost. I needed to change session.use_only_cookies either in-line or in the php.ini setting from
session.use_only_cookies = 1

to
session.use_only_cookies = 0

Explanation
Using default cookie-based sessions was working as expected but I needed a cookie-less solution. A test starting page:
<?php
// page1.php

ini_set('session.use_cookies', '0');
session_start();

$_SESSION['time'] = time();

echo '
page 2';
?>

The session data was created and stored successfully in the WAMPSERVER temp directory, e.g., C:\wamp\tmp\sess_0rkdlonl5uia717rf03d4svs16. The link generated by the above code looks similar to (note the UID matches the session data file name):
page2.php?PHPSESSID=0rkdlonl5uia717rf03d4svs16
But the destination page2.php was throwing undefined errors for the variable 'time' whilst attempting to retrieve the session data:
<?php
// page2.php

ini_set('session.use_cookies', '0');
session_start();

echo date('Y m d H:i:s', $_SESSION['time']);

echo '
page 1';
?>

By setting session.use_only_cookies FALSE in either the script before session_start();:
ini_set('session.use_only_cookies', '0');

or changing it globally in php.ini:
; This option forces PHP to fetch and use a cookie for storing and maintaining
; the session id. We encourage this operation as it's very helpful in combatting
; session hijacking when not specifying and managing your own session id. It is
; not the end all be all of session hijacking defense, but it's a good start.
; http://php.net/session.use-only-cookies
session.use_only_cookies = 0

solved the problem.

A: After a long time I have fixed this bug finally.
On my localhost WAMP, the session data is not saved between page loads, because the session data is stored in a cookie, and there is no cookie domain to be set for localhost.
The solution:

'session.cookie_domain' should be set to empty string for all local domain names, not only for 'localhost' (but should not be empty for local IP addresses):

<?php
ini_set('session.cookie_domain', (strpos($_SERVER['HTTP_HOST'],'.') !== false) ? $_SERVER['HTTP_HOST'] : '');
?>

Thanks to Marcin Wiazowski who posted it here.

A: Faced the same problem but it was being caused by
session_regenerate_id(true);

So I just deleted it from my code.

A: Update to WAMP 2.5 and now the problem is solved!


text:
Q: Discover DynamicResource bindings within DataTemplate Is it possible to discover all dynamic resources within a datatemplate - either within the datatemplate itself, or after it was applied to some ContentPresenter?
My idea was to make some sort of property editor to edit the appearance of wpf objects (maybe dynamically created using XamlReader) and show - for a certain object, only the resource entries used inside the corresponding DataTemplate.

A: Please look at Snoop utility. You can look at the source code and see how you can view the style/template of any object and change its appearance.

A: Up to now, I have not found a "clean" way to get the dynamic resource using framework methods.
However, one possibility is to search the DataTemplate using reflection. The dynamic resources are stored inside structs of type System.Windows.ChildValueLookup where the LookupType is "Resource". I have written a helper class to enumerate the resources:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Windows;

namespace DashboardTest
{
    public struct ResourceInfo
    {
        public ResourceInfo(string resourceKey, DependencyProperty property)
            : this()
        {
            ResourceKey = resourceKey;
            Property = property;
        }

        public string ResourceKey { get; private set; }
        public DependencyProperty Property { get; set; }
    }

    public static class DataTemplateHelper
    {
        private static readonly Type ChildValueLookupType = GetType("System.Windows.ChildValueLookup");
        private static readonly FieldInfo LookupTypeField = ChildValueLookupType.GetField("LookupType", BindingFlags.Instance | BindingFlags.NonPublic);
        private static readonly FieldInfo ValueField = ChildValueLookupType.GetField("Value", BindingFlags.Instance | BindingFlags.NonPublic);
        private static readonly FieldInfo PropertyField = ChildValueLookupType.GetField("Property", BindingFlags.Instance | BindingFlags.NonPublic);
        private static readonly object LookupTypeResource = Enum.Parse(LookupTypeField.FieldType, "Resource");

        public static List<ResourceInfo> FindDynamicResources(DataTemplate template)
        {
            var recordField = typeof(DataTemplate).GetField("ChildRecordFromChildIndex", BindingFlags.Instance | BindingFlags.NonPublic);
            Debug.Assert(recordField != null);

            var values = EnumerateObjects(recordField.GetValue(template)).Where(IsDynamicResource).Select(ToResourceInfo).ToList();
            return values;
        }

        private static ResourceInfo ToResourceInfo(object lookup)
        {
            return new ResourceInfo((string)ValueField.GetValue(lookup), (DependencyProperty)PropertyField.GetValue(lookup));
        }

        private static Type GetType(string typeName)
        {
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                Type type = assembly.GetType(typeName);
                if (type != null)
                    return type;
            }
            return null;
        }

        private static bool IsDynamicResource(object obj)
        {
            if (obj == null || obj.GetType() != ChildValueLookupType) return false;
            return LookupTypeResource.Equals(LookupTypeField.GetValue(obj));
        }

        private static IEnumerable<object> EnumerateObjects(object obj)
        {
            var visited = new HashSet<object>();
            EnumerateObjectsInternal(obj, visited, 20);
            return visited;
        }

        private static void EnumerateObjectsInternal(object obj, HashSet<object> visited, int maxDepth)
        {
            if (obj == null || maxDepth <= 0) return;
            var type = obj.GetType();

            if (obj is Type || obj is string || obj is DateTime || type.IsPrimitive
                || type.IsEnum || visited.Add(obj) == false) return;

            var array = obj as Array;
            if (array != null)
            {
                foreach (var item in array)
                {
                    EnumerateObjectsInternal(item, visited, maxDepth - 1);
                }
            }
            else
            {
                foreach (var field in GetAllFields(type))
                {
                    var fieldValue = field.GetValue(obj);
                    EnumerateObjectsInternal(fieldValue, visited, maxDepth - 1);
                }
            }
        }

        private static IEnumerable<FieldInfo> GetAllFields(Type type)
        {
            const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;

            if (type == typeof(object) || type.BaseType == typeof(object))
            {
                return type.GetFields(bindingFlags);
            }
            else
            {
                var fieldInfoList = new List<FieldInfo>();

                var currentType = type;
                while (currentType != typeof(object))
                {
                    fieldInfoList.AddRange(currentType.GetFields(bindingFlags));
                    currentType = currentType.BaseType;
                }
                return fieldInfoList;
            }
        }
    }
}


text:
Q: Why do complex function have derivatives? I'm sorry if I sound too ignorant, I don't have a high level of knowledge in math.
The function $f(z)=z^2$ (where $z$ is a complex number) has a derivative equal to $2z$.
I'm really confused about this. If we define the derivative of $f(z)$ as the limit as $h$ approaches $0$ (being $h$ a complex number) of $(f(z+h)-f(z))/h$, then clearly the derivative is $2z$, but what does this derivative represent??
Also, shouldn't we be able to represent a complex function in 4-dimensional space, since our input and output have 2 variables each ($z=x+iy$) and then we could take directional derivatives...right?
But if we define the derivative as above, it would be the same if we approach it from all directions. That's what's bothering me so much.
I would really appreciate any explanation. Thanks!

A: The complex derivative shouldn't be thought of as representing a "gradient" as such, but rather as a set of instructions for approximating a function near a point where it is differentiable.

Suppose $f\colon\mathbb{C}\to\mathbb{C}$ is complex differentiable at a point $z_{0}\in\mathbb{C}.$ This means that the limit
$$\lim_{h\to0}\frac{f(z_{0}+h)-f(z_{0})}{h}$$
exists and is finite. In turn, this means there must be some "error" function $\epsilon,$ with $\epsilon(h)\to0$ as $h\to0,$ such that
$$f(z_{0}+h)-f(z_{0}) = h[f^{\prime}(z_{0}) + \epsilon(h)].$$
Rearranging this, we find that, for small $\lvert h\rvert,$
$$f(z_{0}+h) = f(z_{0}) + hf^{\prime}(z_{0}) + h\epsilon(h).$$
Since $\epsilon\to0$ as $h\to0,$ we can make an approximation of sorts: when $\lvert h \rvert$ is small, so too is $\lvert \epsilon(h) \rvert.$ Then $\lvert h\epsilon(h) \rvert = \lvert h \rvert \lvert \epsilon(h) \rvert$ must be very small indeed. Thinking of complex numbers as vectors in the plane (as in this image), we have
\begin{equation}
f(z_{0}+h) \approx f(z_{0}) + hf^{\prime}(z_{0}),
\end{equation}
where by "$\approx$" I mean the pointy ends of the vectors are close together. So what does this all mean?
Recall that if you multiply a complex number $a$ by another complex number $b,$ the product $ab$ has magnitude $\lvert a \rvert \lvert b \rvert$ and has argument $\arg(a)+\arg(b).$ The approximation above tells us that if $z_{1}$ is close to $z_{0},$ so that $z_{1}=z_{0}+h$ for some "small" number $h,$ then
$$f(z_{1}) \approx f(z_{0}) + (z_{1}-z_{0})f^{\prime}(z_{0}).$$
That is, to compute $f(z_{1})$ as a vector, you take $f^{\prime}(z_{0})$ as a vector, stretch it (that is, multiply its magnitude by $\lvert z_{1}-z_{0}\rvert$), rotate it (that is, add the arguments), and finally you add on the vector $f(z_{0}).$
So, what is the complex derivative? It's a complex scaling factor, just like the real derivative is a real scaling factor. The only difference is that complex scaling factors introduce rotations. It shouldn't be thought of as representing a "gradient" as such, but rather as a set of instructions for approximating a function near a point where it is differentiable.

To take a specific example, the function $f\colon z\mapsto z^{2}$ is differentiable at the point $1+i$, and it's derivative there is $2(1+i)$ (it's also differentiable everywhere else, I just want a concrete example). By the above, this means that if I have a complex number $z_{1}$ which is close to $1+i,$ then $z_{1}^{2}\approx (1+i)^{2} + (z_{1}-1-i)(2(1+i)),$
i.e., $$z_{1}^{2} \approx -2i + 2(1+i)z_{1}.$$
We can check this numerically: let's agree that $1.1+i$ is close to $1+i.$ Then, setting $z_{1} = 1.1+ i$ gives
$$z_{1}^{2} = 0.21 + 2.2 i,$$
and meanwhile
$$-2i + 2(1+i)z_{1} = 0.2 + 2.2 i.$$
I think if we agree that $1.1+i$ is close to $1+i,$ then we should also agree that $0.2+2.2i$ is close to $0.21+2.2i.$

A: Treating the complexes as two real dimensions is an important idea. If we relate the standard coordinates as $z=x+\mathbf{i}y$, then you'd have $\mathrm{d}z = \mathrm{d}x + \mathbf{i} \mathrm{d}y$. It's convenient to also use $\mathrm{d}\bar{z} = \mathrm{d}x - \mathbf{i} \mathrm{d}y $.
Every differential is a linear combination of $\mathrm{d}z$ and $\mathrm{d}\bar{z}$. The complex differentiable functions are the ones for which the coefficient on $\mathrm{d}\bar{z}$ is zero, so that we have $\mathrm{d}f(z) = g(z) \mathrm{d} z $, and we'd call $g$ the complex derivative of $f$.
That is, the complex differentiable functions $f$ are for which the "rate of change" in $f(z)$ is proportional to the "rate of change" in $z$.

If you prefer partial derivatives to differentials, we define
$$\frac{\partial }{\partial z} = \frac{1}{2} \left( \frac{\partial}{\partial x} - \mathrm{i} \frac{\partial}{\partial y} \right) \qquad \qquad \frac{\partial }{\partial \bar{z}} = \frac{1}{2} \left( \frac{\partial}{\partial x} + \mathrm{i} \frac{\partial}{\partial y} \right)$$
As for why these particular formulas are the way they are, they are the ones that satisfy
$$ \frac{\partial z}{\partial z} = 1
\qquad \qquad \frac{\partial \bar{z}}{\partial z} = 0 $$
$$ \frac{\partial z}{\partial \bar{z}} = 0
\qquad \qquad \frac{\partial \bar{z}}{\partial \bar{z}} = 1 $$
The complex differentiable functions are the real differentiable functions for which
$$\frac{\partial f(z)}{\partial \bar{z}} = 0$$
so that the derivative is completely determined by the derivative in the "$z$ direction".

When working with more general functions, it is actually somewhat useful to treat $z$ and $\bar{z}$ as 'independent' variables, so that you can do calculus more conveniently. e.g. rather than working with $|z|^2$, you'd use $z \bar{z}$, whose differential $\mathrm{d}(|z|^2)$ is easy to compute as $z \mathrm{d}\bar{z} + \bar{z} \mathrm{d}z$. This can be more convenient to work with that $\mathrm{d}x$ and $\mathrm{d}y$, because you get to exploit complex derivatives and arithmetic.
In these terms, the complex differentiable functions are precisely those functions that 'depend' only on $z$ and not $\bar{z}$.

A: From the point of view of the Taylor's theorem (which, I think, is geometrically the "correct" one), the derivative of a complex function (along with its value) represents exactly the same thing as the derivative of a real function: a linear approximation of the function at the point. If $f$ is differentiable at $x_0$, then
$$
f(x_0+\Delta x)=f(x_0)+f'(x_0)\cdot \Delta x+o(\lvert \Delta x\rvert).
$$
The theorem holds over reals and over the complex numbers, along with its generalizations, to higher dimensions and higher derivatives, which motivates the respective definitions.

A:
If we define the derivative of $f(z)$ as the limit as $h$ approaches $0$ (being $h$ a complex number) of $(f(z+h)−f(z))/h$...

That's precisely what we do.

then clearly the derivative is $2z$, but what does this derivative represent??

Well, it represents what we have defined: the limit of the incremental ratio, same as in the real case. Probably you're wondering if we can interpret this complex derivative geometrically or visually, as we  interpret the (real) derivative as the slope of the tangent line... There is no such a simple pictorial interpretation.

Also, shouldn't we be able to represent a complex function in 4-dimensional space, since our input and output have 2 variables each ... and then we could take directional derivatives...right?

Indeed, you could consider each of the two components (real and imaginary) separatedly, both for the variable and for the function, and then you'd get four (real) derivatives. And, yes, it's natural to ask how these four derivatives are related to the complex  derivative, and if there are some (necessary and/or sufficient) restrictions on them so that the complex derivative gives the same value no matter the "direction" (as one would want)... Behold the Cauchy–Riemann equations and holomorphic functions.

A: A complex-valued function $f$ is differentiable if near an arbitrary point $z_{0}$, the function $f$ acts like multiplication by a complex number $f'(z_{0})$ in the sense that
$$
f(z_{0} + h) = f(z_{0}) + h\, f'(z_{0}) + o(|h|).
$$
Since multiplication by a non-zero complex number
$$
\alpha = |\alpha| \exp(i\theta)
$$
rotates the plane (about the origin) through an angle $\theta$ and scales the plane (about the origin) by a factor $|\alpha|$, a complex-differentiable function is properly conformal (preserves both orientation and angle) at each point where the derivative is non-zero.
You're correct that drawing the graph of a complex-valued function of one complex variable entails four-dimensional plotting. Drawing the image of a Cartesian grid, however, is perfectly feasible in the plane:

Each map above is defined by a pair of real cubic polynomials; the red curves are the images of vertical lines; the blue curves are images of horizontal lines. The maps differ in the sign of one component of the cubic term. One map is complex differentiable (or holomorphic), one is not.
The holomorphic map sends a square grid to an "infinitesimally square grid". (There is one critical point, whose image is visually apparent.) The derivative $f'(z_{0})$ at a point determines the size of the image (quasi-)square and the angle of rotation compared to the original Cartesian square.
The non-holomorphic map sends a square grid to a grid of curvilinear parallelograms that are not generally squares. This is the geometric manifestation of the directional derivatives at $z_{0}$ depending on the direction of approach to $z_{0}$: The Cartesian grid in the domain "gets stretched and rotated by differing amounts in different directions at a single point."

A: Let $w=f(z) = z^2$.  Then $f(2+i)= 3+4i$ and $\dfrac{dw}{dz} = f'(z) = 2z$ and $f'(2+i) = 4+2i$.
The means an infinitely small change in $z$, from $2+i$ to $2+i+dz$, has a corresponding infinitely small change in $w$, from $3+4i$ to $3+4i + dw = 3+4i + (4+2i)\,dz$.
The change $dz$ gets multiplied by $4+2i$.  Geometrically, what is a multiplication by $4+2i$?  We have $$ 4+ 2i = \sqrt{4^2 + 2^2}\  \left( \cos\theta+i\sin\theta \right) \text{ where } \theta = \arctan\frac 2 4. $$
Thus, multiplying $dz$ by $4+2i$ amounts to rotating $dz$ through that angle $\theta$ and multiplying its absolute value by $\sqrt{4^2+2^2} = 2\sqrt{5} \approx 4.472.$

A: Perhaps I'm repeating some things already said, but here's my two cents.
In a sense, your question of "why shouldn't the derivative change when you approach from different directions" in the reason why complex analysis works the way it does. In the real case, $f'(x) =a$ means that for small changes $\Delta x$ of $x$, we get small changes $a\Delta x$ of $y$. It's the same in the complex case, but now $a$ is a complex number, so $\Delta x \mapsto a\Delta x$ behaves, as a map $R^2 \to R^2$, as a rotation and scaling of the complex number $\Delta x$, which you can think of as a vector in $R^2$. Thus multiplication by $a$ can be thought of a linear transformation transformation $R^2\to R^2$, just as the usual derivative of a function $R^2 \to R^2$.
This ultimately means that complex differentiable functions send little circles to little circles (a rotation and scaling surely does just this), which for one thing explains why complex differentiable functions are conformal, which in turn helps explain why they are in a sense "so rigid".


text:
Q: Only show column with X's I have a massive Excel sheet with currently 100+ columns and 84 rows. I am looking to be able to toggle a specific row and have only the columns with text show, all others hidden. For example:
TITLE |COLUMN 1|COLUMN 2|COLUMN 3|COLUMN 4|COLUMN 5|
 ROW 1 |   X    |        |   X    |        |   X    |
 ROW 2 |        |   X    |   X    |   X    |        |
When I "toggle" ROW 1 only columns 1,3,5 will show and columns 2,4 will hide, all other rows will also hide.
When I "toggle" ROW 2 only columns 2,3,4 will show and columns 1,5 will hide, all other rows will also hide.
EDIT: Rows 1,2,3 and Columns A,B must always be visible.
Can this be done and what method do you suggest? ie: radio button, checkbox, etc...?

A: I agree with @Wolfie - if you transpose the data, it'll make it much simpler to do.  However, this was a little fun to work on, so I have the below macro:
Sub toggleRows()
Dim mark As String
Dim rng As Range, cel As Range, totalRng As Range
Dim rowNum As String
mark = "x"

rowNum = InputBox("What ROW (#) do you want to filter?")
rowNum = Trim(rowNum)
If rowNum = "" Then Exit Sub

unhideAllColumns
Set totalRng = Range(Cells(4, 3), Cells(ActiveSheet.UsedRange.Rows.Count, Cells(Columns.Count).End(xlToLeft).Column))
totalRng.Select

For Each cel In totalRng
    If cel.Row <> rowNum Then
        cel.EntireRow.Hidden = True
    Else
        cel.EntireRow.Hidden = False
        If cel.Value = "" Then ' changed from cel.Value <> mark
            cel.EntireColumn.Hidden = True
        Else
            cel.EntireColumn.Hidden = False
        End If
    End If
Next cel

End Sub

and to show all columns:
Sub unhideAllColumns()
Cells.EntireColumn.Hidden = False
Cells.EntireRow.Hidden = False
End Sub

A: For the transpose solution, here are the steps:

*

*Select your data

*Copy (Ctrl+C). Select a cell in column A below the original data. Paste Special Transpose

*Delete the original data

*Add filters from the Data Ribbon (Alt+D+F+F)

*Pull down the ROW 1 dropdown and filter on X


text:
Q: Can SpEL be passed an enviroment variable directly or is a properties file in some form always required? We build micro services and I am working on a generic way of generating documentation for them. This has created a situation where I need to set a variable which is static across all our services yet has two possible values depending on the environment the service is deployed in. Hence I would like to inject a value based directly on an environment variable rather than through my Application.yml file, and it's various profiles, as I would usually do. Is there any way to do this?
Here is an example of what I imagine this would look like (with a syntax similar to what it would have looked like if it was a regular property in Application.yml):
@Value("#{enviromentProperties['environment'].equals['production'] ? jupiter : mars}")
private String APIGatewayHostname;

Just to be clear we have situations where we deploy several profiles behind the same proxy. Hence we want the hostname reference to be the proxy host so people don't attempt to call the service directly as this is not possible. We only have one proxy per environment regardless which profiles we are running at any given time hence my desire to use an environment variable rather than a property. Also this proxy is not really a part of the design of the services themselves so it seems counter intuitive to store it in multiple profiles in the Application.yml file.
NB: If there are other better ways to accomplish this feel free to let me know :)


text:
Q: Argument passing using Cucumber between two methods in Java I am a newcomer to Cucumber and I am having a hard time trying to understand how to pass data between two methods. I keep reading about data tables but I only see examples on how to use data that is already listed in the table in feature. When I run my code I get the error:
Step [^Send Results$] is defined with 3 parameters at 'cucumebr.test.addResult(int,int,String,Integer>>) in file:/Users/lcren1026/eclipse-workspace/cucumebr/target/classes/'.However, the gherkin step has 0 arguments.

What am I trying to do is pass a Map in an Arraylist between two methods using the data gathered in Selenium. Below is my code:
package cucumebr;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import testrail.APIException;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;

public class test
{
    public static WebDriver driver;
    String FFDriverDirectory = "directory";
    String FFDriverEXE = "webdriver.gecko.driver";
    ArrayList Results = new ArrayList<>();
    @Given("^Open the browser$")

public void openBrowser() throws IOException, APIException, InterruptedException
    {
        System.setProperty(FFDriverEXE, FFDriverDirectory);
        driver = new FirefoxDriver();

        driver.navigate().to("https://www.google.com/");
        Thread.sleep(5000);
    }

    @When("^verify logo$")
    public void verifyLogo() throws IOException, APIException, ParseException
    {
        if(driver.findElement(By.xpath("//*[@id=\"hplogo\"]")).isDisplayed()) {
            addResult(120254, 1, Results);

        } else
        {
            addResult(120254, 5, Results);
        }
    }

    @Then("^verify btn$")
        public void verifyBtn() throws IOException, APIException, ParseException
        {
            if(driver.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div/div[3]/center/input[1]")).isDisplayed()) {
                addResult(120255, 1, Results);

            } else
            {
                addResult(120255, 5, Results);
            }
    }

        @Then("^Send Results$")
        public  void addResult(int testCaseId, int status, ArrayList<Map<String, Integer>> newResults
                ) throws IOException,  ParseException {

                int count = testCaseId;
                if(testCaseId == count) {
                    Map myTestResults= new HashMap<String, Integer>(){{put("suite", testCaseId); put("milestone", 179);  put("status", status);}};
                    System.out.println(myTestResults);
                    newResults.add(myTestResults);
                    count++ ;
                }
                System.out.println( newResults);
        }

    @Then("^Print Results$")
      public static void PrintResultForTestCase( ArrayList<Map<String, Integer>> newResults ) throws IOException, APIException {

        System.out.println("This is the final result " + newResults);
        }}

Here is the feature:
Feature: google
Scenario: Driver works
Given Open the browser
When verify logo
Then verify btn
Then Send Results
Then Print Results

The data is ArrayList> newResults and the methods are  "addResult" and "PrintResultForTestCase".
Thanks in advance!

A: Your code:
public  void addResult(int testCaseId, int status, ArrayList<Map<String, Integer>> newResults))

requires three parameters, however your feature file does not have any.
Here is an example how to use parameters (number, text or table)
Sample scenario:
  Scenario: Test Scenario
    Given Number parameter $1
    And Text parameter "text"
    And Table example
      | Team name | Number of members |
      | team1     | 2                 |
      | team2     | 5                 |

Steps:
@Given("^Number parameter \\$(\\d+)$")
public void numberParameter(int number)
{
    System.out.println("Number from step is: " + number);
}

@And("^Text parameter \"([^\"]*)\"$")
public void textParameter(String text)
{
    System.out.println("Text from step is: " + text);
}

@And("^Table example$")
public void tableExample(DataTable table)
{
    List<List<String>> data = table.raw();
    // iterate through 'data' here to access rows in table
}

Read more about DataTable here.


text:
Q: kotlin: spring and kapt not working together I created a kotlin/gradle project using spring initializr.
As stated here, if I try to add kapt like:
plugins {
    kotlin("plugin.jpa") version "1.2.71"
    id("org.springframework.boot") version "2.1.6.RELEASE"
    id("io.spring.dependency-management") version "1.0.7.RELEASE"
    kotlin("jvm") version "1.2.71"
    kotlin("plugin.spring") version "1.2.71"
--> kotlin("kapt") version "1.3.41"
}

I get the following error as soon as I try to compile the code:
Caused by: org.gradle.internal.event.ListenerNotificationException: Failed to notify project evaluation listener.
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:86)
    at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
    at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
    at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
    at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy37.afterEvaluate(Unknown Source)
    at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate$1.execute(LifecycleProjectEvaluator.java:190)
    at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate$1.execute(LifecycleProjectEvaluator.java:187)
    at org.gradle.api.internal.project.DefaultProject.stepEvaluationListener(DefaultProject.java:1424)
    at org.gradle.configuration.project.LifecycleProjectEvaluator$NotifyAfterEvaluate.run(LifecycleProjectEvaluator.java:196)
[...]
Caused by: java.lang.AbstractMethodError: org.jetbrains.kotlin.noarg.gradle.NoArgKotlinGradleSubplugin.getNativeCompilerPluginArtifact()Lorg/jetbrains/kotlin/gradle/plugin/SubpluginArtifact;
    at org.jetbrains.kotlin.gradle.plugin.SubpluginEnvironment.addSubpluginOptions(SubpluginEnvironment.kt:81)
    at org.jetbrains.kotlin.gradle.plugin.SubpluginEnvironment.addSubpluginOptions(SubpluginEnvironment.kt:51)
    at org.jetbrains.kotlin.gradle.plugin.Kotlin2JvmSourceSetProcessor$doTargetSpecificProcessing$2.invoke(KotlinPlugin.kt:184)
    at org.jetbrains.kotlin.gradle.plugin.Kotlin2JvmSourceSetProcessor$doTargetSpecificProcessing$2.invoke(KotlinPlugin.kt:161)
    at org.jetbrains.kotlin.gradle.plugin.RunOnceAfterEvaluated.execute(RunOnceAfterEvaluated.kt:25)
    at org.jetbrains.kotlin.gradle.plugin.RunOnceAfterEvaluated.onEvaluated(RunOnceAfterEvaluated.kt:34)
    at org.jetbrains.kotlin.gradle.plugin.RunOnceAfterEvaluatedKt$runOnceAfterEvaluated$1.execute(RunOnceAfterEvaluated.kt:56)
    at org.jetbrains.kotlin.gradle.plugin.RunOnceAfterEvaluatedKt$runOnceAfterEvaluated$1.execute(RunOnceAfterEvaluated.kt)

A: I resolved it by ugrading jvm plugin to the same version as kapt.
In the end I updated all the plugins to the latest version.


text:
Q: Express.js / Node 0.12 res.setHeader undefined I've an express application running on node.js 0.12 which is clustered
When I try to run inside a middleware a res.setHeader i get the following error:
TypeError: Cannot set property 'server' of undefined

_stream_readable.js:505
  dest.end();
     ^
TypeError: undefined is not a function
  at Stream.onend (_stream_readable.js:505:10)
  at Stream.g (events.js:199:16)
  at Stream.emit (events.js:129:20)
  at _stream_readable.js:908:16
  at process._tickCallback (node.js:355:11)

I've spent the last days trying to figure out what's happening, but the application is properly initialized. It's running inside a function because the application is clustered.
Of course I'm unable to use any function which tries to set an header inside my application because of this error, this is just a test I've made to figure out what's the problem.
Any idea?
For completeness here's the code of the application file, called by cluster (only by workers).


text:
Q: Geodan's DualListbox : how to populate selected box with data from ArrayList I am writing an MVC applicaiton with a dual list box, with one side as Unselected Testers. On selection of testers, I am saving the data into a table. The problem is how to bind the saved data to the "Selected" box and the other list of users to the "Unselected" box.
The Data being fetched through JSON request and the response is an Array List so I cannot using selected in the <option> tag inside <Select> tag. Please see the below code.
How to populate the "Selected" box with data returned as ArrayList on a JSON Call.
<div id="dual-list-box" class="form-group row">
  @*<select name="Testers" id="emp" multiple="multiple" data-title="employees" data-source='@Url.Action("AddTesterLookup")' data-value="index" data-text="name"></select>*@
  <select id="emp" multiple="multiple" data-title="employees" name="name" value="@Model.name" data-source='@Url.Action("AddTesterLookup")' data-value="index" data-text="name"></select>
</div>

<script type="text/javascript">
  $('select').DualListBox();
</script>

A: I don't know if you're using a JS or PHP Framework, but for do that you should use javascript to run an Ajax query when the first select box it's changed.
That ajax should use the value of the first select box to get the elements you will populate with javascript in the second select box.
Check this as example:
Multiple html select and jquery ajax

A: You have to data-json property set to false; and remove the data-source property. And fill the select inputs just like;
<select>
  <option>..</option>
  <option>..</option>
</select>


text:
Q: Java - Cannot find Symbol for Contstructor import java.lang.*;

public class GrammerStack extends GrammerStructure implements StringStack {
 private String structName;
 private int cap;

public GrammerStack(String structureName, int limit){
 this.structName = structureName;
 this.cap = limit;
 System.out.println(structName+"["+cap+"]");
}
public void GrammerStructure(String structureName){
 this.structName = structureName;
}

//Empty overrides.
public String[] asArray(){};
public String push(String item) throws FillException{};
public String pop() throws EmptyException{};
public boolean contains(String query){};
public void empty(){};
public double fillPercent(){};

public String getName(){ return structName; }

public void main(String args[]){
 GrammerStack("Stack1",3);
}

}

When I run: javac GrammerStack.java
I get the following:
GrammerStack.java:15: cannot find symbol
symbol  : constructor GrammerStructure()
location: class GrammerStructure
   public GrammerStack(String structureName, int limit){
                                                                                ^
GrammerStack.java:41: cannot find symbol
symbol  : method GrammerStack(java.lang.String,int)
location: class GrammerStack
       GrammerStack("Stack1",3);
       ^
2 errors

I can't figure out what is going wrong here, my method is not mismatched to the name of the file, either. "Grammer" is correct in this case.
Any help?

A: For first problem, add super(structureName); as first line in constructor. I assume you have public GrammerStructure(String name) constructor defined in super class. If this is not the case, please share your constructor.
public GrammerStack(String structureName, int limit){
  super(structureName);
  this.structName = structureName;
  this.cap = limit;
  System.out.println(structName+"["+cap+"]");
}

For second problem, you are missing the keyword new. Change below:
public void main(String args[]){
          GrammerStack("Stack1",3);
 }

with
 public void main(String args[]){
     new GrammerStack("Stack1",3);
 }

or
 public void main(String args[]){
   GrammerStack grammerStack = new GrammerStack("Stack1",3);
 }

A: This error occured because in your super class constructor, you haven't defined the no argument or default constructor.
When you define a constructor with arguments in super class, you have to define the no argument constructor too for this specific reason: the compiler will not add default constructor for you.
child class will throw that error you just mentioned because in child class constructor a default super() call will be added by javac.

A:     import java.lang.*;

    public class GrammerStack extends GrammerStructure implements StringStack {
     private String structName;
     private int cap;
   public GrammerStructure() {
}

    public GrammerStack(String structureName, int limit){
     this.structName = structureName;
     this.cap = limit;
     System.out.println(structName+"["+cap+"]");
    }
    public void GrammerStructure(String structureName){
     this.structName = structureName;
    }

    //Empty overrides.
    public String[] asArray(){};
    public String push(String item) throws FillException{};
    public String pop() throws EmptyException{};
    public boolean contains(String query){};
    public void empty(){};
    public double fillPercent(){};

    public String getName(){ return structName; }

    public void main(String args[]){
     GrammerStack("Stack1",3);
    }

    }

Your are not define default constructor without argument.When you define a constructor with arguments in super class,you must have to define default constructor without argument

A: When you define constructors in super class and sub class, there are some rules to follow: -

*

*If you haven't defined any constructor in both the classes, then compiler will add a default one in both the classes.. So, you're OK.

*If you have defined a 0-arg constructor in super class, still you're OK. Because, from any constructor in your subclass, if you haven't invoked any super class constructor, Compiler will add a super() call automatically as the first statement of every sub class constructor. (NOTE: - Compiler only adds super call to 0-arg constructor)

*If you haven't defined a 0-arg constructor in your super class, but have a parameterized constructor, then you might be in problem, if you don't give an explicit call to that parameterized constructor from each of your sub class constructor..  This is because, Compiler only adds call to a 0-arg constructor, and you don't have one there..
So, the problem with your code is the 3rd one..
To solve the issue: -

*

*Either add a 0-arg constructor in your super class
public GrammerStructure() {
}

*Or, in each of your subclass constructor, add a super call to your parameterized superclass constructor..
public GrammerStack(String structureName, int limit) {
    // Add a `super` with some parameters to match your parameterized
    // super class constructor here..
    // It should be the first statement..
}

Secondly: -
You instantiate a class by using new keyword with your constructor.. So, in your main method, you should change your invocation with this: -
public void main(String args[]){
     new GrammerStack("Stack1",3);
}


text:
Q: Column compare and return values I got two dataframes df1 and df2. I am comparing column values from dataframe one against many column values in df2 and returning unique  intersection without duplicates in another dataframe.
df1
       WORD
0     This
1       is
2        a
3    sample
4  sentence
5        to
6     check
7      NLP
8        in
9    python

df2
Noun    Verb
Car     stand
Sample  sit
        walk
        run
        is

Expected output
df3
    Noun      Verb
    sample    is

I used the following code to get following result. Although it is round-about way of achieving the result it is not quite right. It returned verb values for every noun column matched which I clearly didn't want.
import pandas as pd
df1 = pd.read_csv("1.csv")
df2 = pd.read_csv("2.csv")
df3 = df1.merge(df2, left_on=['Word'], right_on=['Noun'])
print df3.drop('Verb', 1)

   Word  Noun
0  this  this
1    is    is

A: By using numpy.intersect1d
pd.DataFrame([np.intersect1d(x,df1.WORD.values) for x in df2.values.T],index=df2.columns).T
Out[147]:
     Noun Verb
0  Sample   is

If you want to using pandas
df2.mul(df2.apply(lambda x : x.isin(df1.WORD))).apply(lambda x : sorted(x)).iloc[[-1],:]
Out[159]:
     Noun Verb
4  Sample   is