text:
Q: Stomp client on subscribe create new array javascripts I am using javascript Stomp client to subscribe when server sent the message.
The need
I need to create a new array of subscribed messages. Each message has different id. If the id exists then nothing will be pushed, but if the array does not exist then new object will be pushed to the empty array.
This is What I have tried
CODE:
var recivedData = []
    connect()
   function connect() {
        var socket = new SockJS('/info-app');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {

            console.log('Connected: ' + frame);

            stompClient.subscribe('/topic/info', function (msg) {

                    var parsedData = JSON.parse(msg.body)

                    if(!(recivedData.length)){
                        recivedData.push(parsedData)
                        console.log(recivedData)
                    }

                    if(recivedData.length){
                        if(recivedData.find(e => e.id === parsedData.id)){
                            console.log(" there")
                            console.log(recivedData)
                        }
                        if(recivedData.find(e => e.id !== parsedData.id)){
                            console.log("not there")
                            recivedData.push(parsedData)
                            console.log(recivedData)
                        }
                    }

                console.log(recivedData)

            });

        });
    }

The Problem
whenever new id enters it is pushing to the array, but if the same id enters again it is also pushing.
How can I solve that? thanks in advance

A: You don't want to execute if(recivedData.length){ block after you already pushed data into first empty array. Use else part of the if statement:
stompClient.subscribe('/topic/info', function(msg) {

  var parsedData = JSON.parse(msg.body)

  if (!recivedData.length) {
    recivedData.push(parsedData)
    console.log(recivedData)
  } else {
    if (recivedData.some(e => e.id === parsedData.id)) {
      console.log(" there")
      console.log(recivedData)
    } else {
      console.log("not there")
      recivedData.push(parsedData)
      console.log(recivedData)
    }
  }

  console.log(recivedData)
});


text:
Q: numpy or pandas groupby way to replace 2 for loops I have a following Problem there is list of main classes:
list_main_classes = [3,4]
data = pd.DataFrame({
    'label_col':[1,1,2,2,3,3,3,4,4],
    'second_classes_column':[
        "class1",
        "class2",
        "class1",
        "class2",
        "class3",
        "class3",
        "class3",
        "class4",
        "class2"
    ]})

that has a column "second_classes_column"
What I am basically trying to do is remove some Elements from the list "list_main_classes" that satisfy certain conditions. What conditions?

*

*second class columns cant be named "certain_name"

*"second_classes_column" Elements must not appear outside of the Group created by 'label_col'. Meaning that for a Group created by element 4 of the 'label_col'
there must not be an element in  the "second_classes_column" that appears in some other group. In our case this is not satisfied by element "class2" since it appeared already before (rows 2 and 4). Hence we will remove the 4, but retain 3 from the list_main_classes since it satisfies everything,

Question is there a faster way to do this, with Pandas groupby, numpy, already done with 2 for loops ?

A: You should perform a merge on the data and then a filter on the resulting dataframe.
Also if "second_classes_column" has more than one unique "label_col" assigned to it then it is invalid so you can pre-count the number of label_cols associated with each "second_classes_column".
# setup some useful variables
main_classes = pd.DataFrame({"main_classes": list_main_classes})
count_unique_classes = data.groupby("second_classes_column")["label_col"].nunique().to_dict()

def your_logic(x):
    second_id = x["second_classes_column"]
    label_col = x["label_col"]

    case1 = second_id != "certain_class"
    case2 = count_unique_classes[second_id] > 1

    return case1 and case2

# merge the two data frames
joint_df = pd.merge(data, main_classes, left_on="label_col", right_on="main_classes")

# now you can easily do the filter and perform your logic
to_drop = joint_df.apply(your_logic, axis=1)
list_main_indexes_to_drop = joint_df[to_drop].main_classes

So the result:
>>> list_main_indexes_to_drop.values
... array([4])

Your final list can be obtained using either a filter, set operations or np.setdiff1d
>>> list(set(list_main_classes) - set(list_main_indexes_to_drop))
... [3]

or
>>> np.setdiff1d(list_main_classes, list_main_indexes_to_drop)
... array([3])

Update. You might not like the your_logic and apply so you can do it with vectorised boolean operations like so:
# setup some useful variables
main_classes = pd.DataFrame({"main_classes": list_main_classes})
count_unique_classes = data.groupby("second_classes_column")["label_col"].nunique().ge(2)
invalid_classes = set(count_unique_classes[count_unique_classes].index)

# merge the two data frames
joint_df = pd.merge(data, main_classes, left_on="label_col", right_on="main_classes")

# your logic
joint_df = joint_df[
    (joint_df.second_classes_column != "certain_class") &
    (joint_df.second_classes_column.isin(invalid_classes))
]

# now you can easily do the filter and perform your logic
list_main_indexes_to_drop = joint_df.main_classes
list_main_indexes_to_drop.values

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can Not able to Build idoubs for armv7, armv7s and arm64 architecuture I am getting linker error on building idoubs for  armv7 ,armv7s and arm64 architecuture.Please suggest. Thanks.

A: Use Standard Architectures only armv7s & armv7.


text:
Q: Java creating max 3 objects of a class When we want to create only one object of class, we use singleton design pattern. I want to create maximum 3 or 5 objects of my class. Is there any way to restrict maximum number of object creation in Java?

A: Of course you could implement a singleton-like feature rather easily, but what you're apparently looking for is an Object Pool.
There are many implementations of such pools, a notable one is apache commons/pool

A: As seanizer mentioned you would be implementing something that has been done, but, if you just have this one class that you are concerned about, adding a new jar file and using it for such a trivial operation seems like overkill to me.
A simple approach is to have an array of n (3-5), and have a private constructor in your "singleton" class.  Then you will have an instanceOf method, which is the only way to get an object.
This method will look to see if the number of created objects is < n, if it is, it creates a new one and returns it.
But, what do you want to do if all the objects are already given out?
You will need to be certain to have the object returned back to the pool when you are done with it, otherwise you will run out of objects to hand out.
When you hand out an object, you can copy that to a collection, or array, to know that it is already out, or, just have an array of n of boolean that is true when the object is available to be handed out.
The basic design is simple, the complexity is in how to handle the conditions that might be error conditions, in the rest of your program.
Also, you need to ensure that you use a finally block to return the object back, so that in case of exception the object is still returned.

A: Have a static field in the class that counts the number of times an instance has been created.
class Foo {
  private static Integer num_instances = 0, MAX = 3;
  public Foo() throws Exception {
    synchronized(Foo.num_instances) {
      if(Foo.num_instances > MAX) throw new Exception();
      Foo.num_instances++;
    }
  }
}

EDIT: it's probably bad form to throw an exception from a constructor, so you could do the following instead:
class Foo {
  private static Integer num_instances = 0, MAX = 3;
  public Foo try_to_get_a_new_foo() {
    synchronized(Foo.num_instances) {
      if(Foo.num_instances > MAX) return null;
      Foo.num_instances++;
      return new Foo();
    }
  }
}

EDIT 2: If you want pooling (max num in memory at any given time), just implement finalize():
class Foo {
  private static Integer num_instances = 0, MAX = 3;
  public Foo try_to_get_a_new_foo() {
    synchronized(Foo.num_instances) {
      if(Foo.num_instances > MAX) return null;
      Foo.num_instances++;
      return new Foo();
    }
  }
  public void finalize() {
    synchronized(Foo.num_instances) {
      Foo.num_instances--;
    }
    super.finalize();
  }
}

A: Here's my friend Tripleton, he might be able to help you, his cousin Quinton is rather self-explanatory :).
Edit:
bad code removed, lest someone might actually use it, apparently the joke was quite non-obvious :)

A: May be you are looking for Multiton Pattern


text:
Q: How do i use Core Data between classes? I'm just learning core data and mostly coping, but having a little bit of trouble thinking about how I'll implement it.
I want to access the same Core Data from throughout my app. What would be the best way to access it from multiple classes? Would it be recommended to have it as a global variable (normally not recommended in object oriented programming), or to pass it as an instance variable between classes?

A: Core data model will be available throughout your app. You can easily access the managed object through out your app. You just need to make an instance of the AppDelegate class.
Say for example you have stored contacts. You can just use [managedObject valueForKey:@"name"] in any of the view controllers.
1. Create an instance of the appDelegate
self.theappDel=[[UIApplication sharedApplication] delegate];

2. Get the context,fetch request and entity description.
NSManagedObjectContext*context=[self.theappDel managedObjectContext];
NSEntityDescription*entity=[NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:context];
NSFetchRequest*request=[[NSFetchRequest alloc] init];
[request setEntity:entity];
NSManagedObject*managedObject=nil;
NSError*error=nil;
NSArray*objectList=[context executeFetchRequest:request error:&error];

3. Get the managed object from the array.
if([objectList count]>0)
managedObject=[objectList objectAtIndex:0];
NSLog(@"The name: %@",[managedObject valueForKey:@"name"])

4. Pass the name object using a singleton(or any convenient method) pattern, in other view controllers that you need it.

A: Pass the NSManagedObjectContext instance, or if you just need to handle one object the NSManagedObject instance, to the next class.
Like it's done in Xcodes Core Data templates.

A: Take a look at the MagicalRecord Library. Not only does it make a lot of common fetch requests much more succinct, it also makes it easier to access your managed object context just by using [NSManagedObjectContext defaultContext];


text:
Q: How to notify when a product is added within Magento? I'm wondering what would be the best way to notify an user when a new product is added which matches his/her interests?
I think of a cron running at least 2 times a days (or more, every hour for example)
I can also imagine to implement kind of an event system but that one may be tricky.
Do you have any feedback?
Thanks

A: At the time of new product adding time do you want send a mail to customers then don't go for RSS or cron just use the EVENT called "catalog_product_save_after" in your config.xml file and call one function in that function just write like this
public function sendMailToNotifiedCustomerOk($observer){

       $product  = $observer->getProduct();  //get the current product
       echo "<pre>";    print_r($product); echo "</pre>";exit;

}

when you clicked on save button this function will execute and show you one flag value like
 [_isObjectNew:protected] => 1

This values is 1 for only adding new products.
if you are updating or editing products then this value is
 [_isObjectNew:protected] =>

so it is zero(0)
you can write like this
if($product->_isObjectNew)
{
 //send email to your friends
}

A: You need to add a value to "Set Product as New from Date" attribute so that will appear in new product RSS feed. Doesn't make sense to make new event system. This is easy way to implement such kind of things.

A: You can create a script that runs simultaneously with the INSERT script that searches a table in your database called say "Notify" and searched loops through the table and finds everyone who signed up for say category "Toothpicks" and sends a mass email at the end to every user that is found
So you would need to set up the variable to catch the users in ($users) and one for the category ($category = mysql_real_escape_string('$_POST['category']); . Then set up a SELECT statement to pull from table "Kitchen_Goods" WHERE category = $category. Then set up the $rows variable so you can pull the username and email_address columns and set them to variables.  then concat all the email results to have a comma in between, then echo that variable as the recipients field in your mail() function.  That is a round about, incomplete way of doing it.
Or you can just use RSS which is 100 times easier lol.

A: You don't state how you save customer interests, so I'll relegate that one to magic until you say otherwise. A good way to do this is to hook an event to the catalog_product_save_after event in Magento. This function will fire whenever you save products. Create an observer that looks something like this:
public function observeProductSave($event) {
    $product = $event['product'];
    $customers = $this->getMatchingCustomerInterests($product);
    foreach($customers as $customer) {
        //send email to that customer
    }
}

public function getMatchingCustomerInterests($product) {
    // here you'll need to use your mechanism for saving
    // customer interests to grab an array/collection of
    // customers to send the emails to.
}

Obviously this code is not 100% complete, but that's the gist of it. You will probably want to add a facility to make sure that customers are not notified too many times about a product as well.
Hope that helps!
Thanks,
Joe


text:
Q: Setting Replication For MySQL Production Container in Kubernetes Use Case: A MySQL instance will be running on production with required databases. I need to configure this running container as a master and spin up one more MySQL instance as a slave.
Challenges: Facing issues in configuring running MySQL instance as a master. The issue is not able to create replication user and not able to append the master/slave configuration to my.cnf file. The reason is,

*

*To create replication user or to execute any custom SQL commands in container, we have to place initdb.sql with required SQL commands inside docker-entrypoint-initdb.d. So when container starting it execute the file present in docker-entrypoint-initdb.d and executes it, if the database had not created, if the database had created already it skips executing this .sql file residing in docker-entrypoint-initdb.d. This is the root for failing to configure master because MySQL is running with databases in production. So I cannot take this solution to configure as MySQL.

*After facing this issue we planned to put the configuration SQL commands in .sh and keep in docker-entrypoint-initdb.d and execute them by patching the deployment. In this scenario we are facing some permission issues when executing the .sh files.

I need to configure replication(master-slave) for MySQL instance(s) in kubernetes world. I gone through the lot of posts to understand how to implement this. Nothing worked out as I am expecting and as I explained above. Along with this I found a custom image(bitnami/mysql) which supports setting up the replication, which I don't want use because finally I would not be able to implement this in production env.
So it will be very grateful if anyone helps me by suggesting any approach to solve this problem.
Thank you very much in advance.!!!


text:
Q: Adding Bearer Token to ASP.NET Web API that has Basic Authentication Attribute I have an ASP.Net Web API 2 with BasicAuthenticationAttribute that is working as expected. In my application, there are different controllers and I want to add bearer token-based authentication to one of my controllers. I added those NuGet packages:
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.OAuth

Here is the WebApiConfig:
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling =
                DateTimeZoneHandling.Local;

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{id}",
                new {id = RouteParameter.Optional}
            );

            config.MessageHandlers.Add(new RequestResponseHandler());

            config.Filters.Add(new CustomExceptionFilter());

            var resolver = config.DependencyResolver; //Assuming one is set.
            var basicAuth = (BasicAuthenticationAttribute)resolver.GetService(typeof(BasicAuthenticationAttribute));
            // Web API configuration and services
            if (basicAuth != null) config.Filters.Add(basicAuth);

        }
    }

Here is the Owin Startup
public class Startup
    {
        public void Configuration(IAppBuilder app)
        {

            var configuration = GlobalConfiguration.Configuration;

            WebApiConfig.Register(configuration);
            app.UseWebApi(configuration);

            Configure(app);
        }

        private static void Configure(IAppBuilder app)
        {
            var options = new OAuthAuthorizationServerOptions()
            {
                TokenEndpointPath = new Microsoft.Owin.PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
                AllowInsecureHttp = true,
                Provider = new AuthorizationServerProvider()
            };

            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }

Here is the controller
[RoutePrefix("api/v2/game/abc101")]
    public class A101Controller : ApiController
    {
        private readonly IGameServicesABC101 _gameServices;
        private readonly IMapper _mapper;

        public A101Controller(IGameServicesABC101 gameServices, IMapper mapper)
        {
            _gameServices = gameServices;
            _mapper = mapper;
        }

        [HttpPost]
        [Authorize]
        [Route("purchase")]
        public async Task<IHttpActionResult> PurchaseGame(RequestDto game)
        {
            if (!ModelState.IsValid) return BadRequest(ModelState);
...

Basic Authentication Attribute
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
    {
        private const string Realm = "My Realm";
        private readonly Func<IUserValidate> _factory;

        public BasicAuthenticationAttribute(Func<IUserValidate> factory)
        {
            _factory = factory;
        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {

            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request
                    .CreateResponse(HttpStatusCode.Unauthorized);

                if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized)
                    actionContext.Response.Headers.Add("WWW-Authenticate",
                        $"Basic realm=\"{Realm}\"");
            }
            else
            {

                var authenticationToken = actionContext.Request.Headers
                    .Authorization.Parameter;
                try
                {
                    //Decode the string
                    var decodedAuthenticationToken = Encoding.UTF8.GetString(
                        Convert.FromBase64String(authenticationToken));

                    var usernamePasswordArray = decodedAuthenticationToken.Split(':');

                    var username = usernamePasswordArray[0];

                    var password = usernamePasswordArray[1];

                    var uv = _factory();
                    if (uv.Login(username, password))
                    {
                        var identity = new GenericIdentity(username);
                        IPrincipal principal = new GenericPrincipal(identity, null);
                        Thread.CurrentPrincipal = principal;
                        if (HttpContext.Current != null) HttpContext.Current.User = principal;
                    }
                    else
                    {
                        actionContext.Response = actionContext.Request
                            .CreateResponse(HttpStatusCode.Unauthorized);
                    }
                }
                catch
                {
                    actionContext.Response = actionContext.Request
                        .CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
        }
    }

I am using Unity in my application. Basic Authentication works as expected. When I make a request without a token to ...api/v2/game/abc101/purchase I get a response either. Shouldn't I get 401? What I am missing?
UPDATE
I am searching and trying to find how to use both basic authentication and token-based authentication for different controllers. Here is my status update.
There is no code in the Global.asax
Here is the Owin Startup
public class Startup
    {
        public void Configuration(IAppBuilder app)
        {

            var config = GlobalConfiguration.Configuration;
            WebApiConfig.Register(config);
            app.UseWebApi(config);
            Configure(app, config.DependencyResolver);
            config.EnsureInitialized();
        }

        private static void Configure(IAppBuilder app, IDependencyResolver resolver)
        {
            var options = new OAuthAuthorizationServerOptions()
            {

                TokenEndpointPath = new Microsoft.Owin.PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
                AllowInsecureHttp = true,
                Provider = new AuthorizationServerProvider((IUserValidate)resolver.GetService(typeof(IUserValidate)))

            };

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            app.UseOAuthAuthorizationServer(options);

        }
    }

Here is AuthorizationServerProvider
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        private readonly IUserValidate _userValidate;
        public AuthorizationServerProvider(IUserValidate userValidate)
        {
            _userValidate = userValidate;
        }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            if (!context.TryGetBasicCredentials(out var clientId, out var clientSecret))
            {
                context.SetError("Error", "Error...");
            }

            if (_userValidate.Login(clientId, clientSecret))
            {
                context.Validated();
            }
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type" });

            if (_userValidate.Login(context.UserName, context.Password))
            {

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("role", "admin"));

                context.Validated(identity);
            }
            else
            {

                context.SetError("Error", "Error...");
            }
        }
    }

The rest is the same as the previous code samples.
When I call ...api/v2/game/abc101/purchase I am getting 401, it is progress. But when I call http://localhost:52908/token I am getting unsupported_grant_type. I am sending requests via Postman and I am sending a POST requests with content-type x-www-form-urlencoded. Grant-Type is password and username/password is also correct.
When I call another controller http://localhost:52908/api/v2/game/purchase basic authentication does NOT work!
Hope someone can help.

UPDATE 1
Now I am getting the token, one step at a time :) How can I also use Basic authentication for another controller?
Here is Startup
public class Startup
    {
        public void Configuration(IAppBuilder app)
        {

            var config = GlobalConfiguration.Configuration;
            Configure(app, config.DependencyResolver);
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
            config.EnsureInitialized();

        }

        private static void Configure(IAppBuilder app, IDependencyResolver resolver)
        {
            var options = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new Microsoft.Owin.PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
                Provider = new AuthorizationServerProvider((IUserValidate)resolver.GetService(typeof(IUserValidate)))

            };

            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }
    }

Here is the Authorization Server Provider
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        private readonly IUserValidate _userValidate;
        public AuthorizationServerProvider(IUserValidate userValidate)
        {
            _userValidate = userValidate;
        }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            if (!context.TryGetBasicCredentials(out var clientId, out var clientSecret))
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
            }

            if (_userValidate.Login(clientId, clientSecret))
            {
                context.Validated();
            }
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            if (_userValidate.Login(context.UserName, context.Password))
            {

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("role", "admin"));

                context.Validated(identity);
            }
            else
            {

                context.SetError("invalid_grant", "The user name or password is incorrect.");
            }
        }
    }

As I mentioned before, I have Basic Authentication Attribute and somehow I have to use it in my other controller.
UPDATE 2
How can I use OverrideAuthentication and my basic authentication attribute?
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
    {
        private const string Realm = "My Realm";
        private readonly Func<IUserValidate> _factory;

        public BasicAuthenticationAttribute(Func<IUserValidate> factory)
        {
            _factory = factory;
        }
        ...

UPDATE 3
I tried this in my basic authentication attribute OnAuthorization method;
var authentication = DependencyResolver.Current.GetService<IUserValidate>();

                     if (authentication.Login(username, password))
                     {
                         var identity = new GenericIdentity(username);
                         IPrincipal principal = new GenericPrincipal(identity, null);
                         Thread.CurrentPrincipal = principal;
                         if (HttpContext.Current != null) HttpContext.Current.User = principal;

}
There are 2 problems, authentication is null, and somehow authentication token in the attribute is the bearer authentication username/password even though I use basic authentication username/password in the request. It's very weird!
/Get the authentication token from the request header
                 var authenticationToken = actionContext.Request.Headers
                     .Authorization.Parameter;

Any help please?
Thanks in advance.

A: After long googling, here is how I managed to use both basic authentication and bearer authentication for my different controllers.
In Custom basic authentication Attribute I used dependency and requestScope.GetService.
public class CustomBasicAuthenticationAttribute : AuthorizationFilterAttribute
    {
        [Dependency] public static IUserValidate authentication { get; set; }

        private const string Realm = "My Realm";

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var requestScope = actionContext.Request.GetDependencyScope();

            //If the Authorization header is empty or null
            //then return Unauthorized
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request
                    .CreateResponse(HttpStatusCode.Unauthorized);
                // If the request was unauthorized, add the WWW-Authenticate header
                // to the response which indicates that it require basic authentication
                if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized)
                    actionContext.Response.Headers.Add("WWW-Authenticate",
                        $"Basic realm=\"{Realm}\"");
            }
            else
            {
                //Get the authentication token from the request header
                var authenticationToken = actionContext.Request.Headers
                    .Authorization.Parameter;
                try
                {
                    //Decode the string
                    var decodedAuthenticationToken = Encoding.UTF8.GetString(
                        Convert.FromBase64String(authenticationToken));
                    //Convert the string into an string array
                    var usernamePasswordArray = decodedAuthenticationToken.Split(':');
                    //First element of the array is the username
                    var username = usernamePasswordArray[0];
                    //Second element of the array is the password
                    var password = usernamePasswordArray[1];

                    authentication = requestScope.GetService(typeof(IUserValidate)) as IUserValidate;

                    if (authentication != null && authentication.Login(username, password))
                    {
                        var identity = new GenericIdentity(username);
                        IPrincipal principal = new GenericPrincipal(identity, null);
                        Thread.CurrentPrincipal = principal;
                        if (HttpContext.Current != null) HttpContext.Current.User = principal;
                    }
                    else
                    {
                        actionContext.Response = actionContext.Request
                            .CreateResponse(HttpStatusCode.Unauthorized);
                    }
                }
                catch
                {
                    actionContext.Response = actionContext.Request
                        .CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
        }
    }

In one of my controller, I added those attributes
        [OverrideAuthentication]
        [CustomBasicAuthentication]

        [HttpPost, Route("purchase")]
        public async Task<IHttpActionResult> PurchaseGame(RequestDto game)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
...

Now I can use bearer token authentication for ...api/v2/game/abc101/purchase and basic authentication for ...api/v2/game/purchase.
Update
The vital part is the dependency and actionContext.Request.GetDependencyScope();. Without OverrideAuthentication it is working as expected.
Hope this solution helps for others.


text:
Q: Как подсчитать количество записей в цепочке? У меня ессть упрощенная таблица перемещения пассажирских поездов, которые показывают его перемещение из города в город:
create table testt (
    ID NUMBER,
    VALST VARCHAR2(255),
    VALEND VARCHAR2(255),
    NEXTID NUMBER
)

   ID VALST  VALEND NEXTID
----- ----- ------- ------
    1   MOS     SAN      2
    2   SAN     MOS
    3   MOS     EKB      4
    4   EKB     RYA      5
    5   RYA     SAN      6
    6   SAN     MOS
    7   MOS     KRA      8
    8   KRA     VOR      9
    9   VOR     MOS

Работает она следующим образом: В ячейке VALST показано, откуда выезжает поезд, в VALEND - куда он приезжает. В ячейке NEXTID написан идентификатор следующего рейса. То есть, например, по ID 1 поезд поедет сначала из MOS в SAN, затем, в следующем рейсе под ID 2 он поедет из SAN в MOS, и цепочка на этом закончится, так как нет следующего идентификатора.
Задача состоит в следующем: определить количество рейсов в цепочке, то есть, когда поезд выезжает из MOS, и в итоге возвращается в MOS.
В примере сверху из ID 1 размер цепочки будет равен два, а из ID 3 цепочка будет равна четырем.
Пробовал через функцию LEAD, но, к сожалению, не получилось, прошу помощи.

A: Данные представляют собой обратную иерархию (reverse hierarchy).
Решатся простым иерархическим запросом (на db<>fiddle):
select valst, level numoftrips, sys_connect_by_path (valst, ' >> ') trips
from testt t
where connect_by_isleaf = 1
start with nextid is null
connect by nextid = prior id

Результат:
VALST  NUMOFTRIPS TRIPS
------ ---------- --------------------------------
MOS             2  >> SAN >> MOS
MOS             4  >> SAN >> RYA >> EKB >> MOS
MOS             3  >> VOR >> KRA >> MOS

A: Вот так это выглядит в MySQL (извини, для ORACLE не стал делать, там сущее мучение с вводом данных в fiddle, а за диагностику проблем так и вовсе руки оторвать, но выглядеть будет практически так же):
WITH RECURSIVE
cte1 AS ( SELECT ID, VALST, VALEND, NEXTID, 1 AS length, ROW_NUMBER() OVER (ORDER BY ID) chain
          FROM testt
          WHERE NEXTID IS NULL
          UNION ALL
          SELECT testt.ID, testt.VALST, cte1.VALEND, testt.NEXTID, cte1.length + 1, cte1.chain
          FROM testt
          JOIN cte1 ON testt.NEXTID = cte1.ID ),
cte2 AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY chain ORDER BY length DESC) rn
          FROM cte1 )
SELECT ID, VALST, length
FROM cte2
WHERE rn = 1;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=a41425e1b0c3cb532c410351a95f8ace


text:
Q: how to update pages without using settimeout?Settimeout is slowing down the page in chrome.Is There any api for that I  Tried  Settimeout to  update  pages,it  works  Perfect  in  Mozilla,
But  it is Slowing  down page in  Google Chrome.

A: There are indeed alternatives to AJAX. And some of them rather amazing, to be honest.
I work for a company called Realtime (http://www.realtime.co) and we developed a very cool framework to work with real-time data.
It works on the cloud, we offer a lot of different APIs, you don't need to install anything and you can get a free account (with 1.000.000 free messages and 30.000 users per month). It allows you to push data to browsers, meaning you won't be hammering your server with AJAX requests.
On browsers, it uses websockets, if available. For older, non-websocket browsers, we will transparently fallback to whatever is that your browser can use.
Check out http://www.realtime.co and http://www.xrtml.org for downloads and documentation. Please let me know if you need any help as I am the Developer Evangelist for Realtime.


text:
Q: wx.Panel in a wx.Panel When I embed a wx.Panel in another wx.Panel (here ChildPanel is embedded in MyPanel), by default this ChildPanel doesn't use the full size of the parent. Why?
Is there a trick for saying that ChildPanel should use full space of MyPanel ?
Is it possible without a BoxSizer ?
import wx

class MyPanel(wx.Panel):
   def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)
        self.SetBackgroundColour('#00f8f8')

        # ChildPanel
        self.ChildPanel = wx.Panel(self)
        self.ChildPanel.SetBackgroundColour('#000000')

class DrawFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        MyPanel(self)
        self.Show()

app = wx.App(False)
F = DrawFrame(None, title="Test", size=(500,500))
app.MainLoop()

A: wxFrame is a special case and is the only window which resizes its only child to entirely fill up its client area. Other windows, including wxPanel, don't do this, so you do need to use a sizer -- or position the child panel manually in wxEVT_SIZE handler.
Of course, if you think about it, it makes sense: while it's pretty common to have a wxPanel entirely covering up the wxFrame, it's very rare to have a wxPanel or wxWindow as the only child of another wxPanel because it simply doesn't make any sense to do it, you're just wasting a window for nothing (and windows are a relatively heavy resource, so you shouldn't do this).


text:
Q: How to show co-ordinates of all points in a plot using pgfPlots? I'd like to show the co-ordinates of all the points which have been used for plotting a curve.
For this I have created individual nodes for all points manually, is there a better way to do this? I've gone through the documentation of tikz-pgf but I couldn't find a solution.
Here's the plot:
\documentclass[12pt,a4paper]{article}

\usepackage[a4paper,margin=2cm]{geometry}
\usepackage{pgfplots,tikz,siunitx,float,amsfonts,amsmath,amssymb}
\pgfplotsset{compat=1.16}
\usetikzlibrary{intersections, positioning, calc, math}

\begin{document}
    \begin{figure}[htb]
        \centering
        \begin{tikzpicture}

            \begin{axis}[
                axis lines=left, thick, grid=both,
                    width=0.8\textwidth, height=0.8\textwidth,
                    xmin=0,xmax=110, ymin=0,ymax=150, y=0.06cm,
                    xlabel={Upper Limits}, ylabel={Cumulative Frequency}
                ]

                \addplot[color = black,smooth,very thick,mark=*,name path=h1] coordinates {
                    (10,3)(20,7)(30,19)(40,37)(50,57)(60,82)(70,94)(80,102)(90,108)(100,110)
                };

                \legend{Less-Than type Ogive Curve}
                \draw (10,3) node [above]{$(10,3)$};
                \draw (20,7) node [above]{$(20,7)$};
                \draw (30,19) node [above]{$(30,19)$};
                \draw (40,37) node [above]{$(40,37)$};
                \draw (50,57) node [above]{$(50,57)$};
                \draw (60,82) node [above]{$(60,82)$};
                \draw (70,94) node [right]{$(70,94)$};
                \draw (80,102) node [above]{$(80,102)$};
                \draw (90,108) node [below]{$(90,108)$};
                \draw (100,110) node [above]{$(100,110)$};
            \end{axis}

        \end{tikzpicture}
        \caption{Less-Than type Ogive Curve.}
    \end{figure}

\end{document}

A: By using nodes near coords you obtain a plot very close to your desired result:
\documentclass{standalone}
\usepackage{pgfplots,tikz}
\pgfplotsset{compat=1.16}
\usetikzlibrary{intersections, positioning, calc, math}

\begin{document}
\begin{tikzpicture}

  \begin{axis}[
      axis lines=left, thick, grid=both,
      width=0.8\textwidth, height=0.8\textwidth,
      xmin=0,xmax=110, ymin=0,ymax=150, y=0.06cm,
      xlabel={Upper Limits},
      ylabel={Cumulative Frequency},
      nodes near coords=,
    ]

    \addplot[color = black,smooth,very thick,mark=*,name path=h1, scatter] coordinates {
      (10,3)(20,7)(30,19)(40,37)(50,57)(60,82)(70,94)(80,102)(90,108)(100,110)
    };

    \legend{Less-Than type Ogive Curve}
  \end{axis}

\end{tikzpicture}

You can customize thecontents of the nodes created with nodes near coords with an argument:
nodes near coords={
   $(\pgfmathprintnumber{\pgfkeysvalueof{/data point/x}},
   \pgfmathprintnumber{\pgfkeysvalueof{/data point/y}})$
},

where the keys /data point/x and /data point/y allow you to acces to data points, and the command \pgfmathprintnumber format the float number.


text:
Q: Referencing outer criteria query aliases from within an SQLProjection I am aware that you can use {alias} to refer to the root entity within an SQLProjection:
Projections.sqlProjection("MIN({alias}.field) as value", new String[]{"value"}, new Type[]{new LongType()}))

What I am trying to do is to reference an alias for a non-root entity:
Projections.sqlProjection("MIN(i.powerRestarts) as value", new String[]{"value"}, new Type[]{new LongType()}))

where i is an alias from the outer criteria query. The code above throws an SQL exception saying that i.powerRestarts cannot be found.
Is it possible to refer to a non-root alias from an SQLProjection?

A: Having done some googling, it appears that this this is not possible - Hibernate only allows inclusion of the root entity alias using {alias} in the SQL string of the SQLProjection. I did however find this issue regarding the limitation on the Hibernate JIRA pages.
Someone has kindly submitted a patch that allows the use of non-root aliases in the SQLProjection string, through a new RestrictionsExt class. Using my example from the question:
Projections.sqlProjection("MIN(i.powerRestarts) as value", new String[]{"value"}, new Type[]{new LongType()}))

The alias i can now be referenced as:
RestrictionsExt.sqlProjection("MIN({i}.powerRestarts) as value", "value", new LongType())

I had to modify the static RestrictionsExt.sqlProjection method to allow specification of the type for the column alias ("value") (here defined as LongType), as the patch didn't allow this and defaulted to StringType.
The SQLAliasedProjection class in the patch also requires access to the following private methods in org.hibernate.loader.criteria.CriteriaQueryTranslator: getOuterQueryTranslator and getAliasedCriteria. To get this to work without modifying the Hibernate source, I used reflection:
cri = ((org.hibernate.loader.criteria.CriteriaQueryTranslator) criteriaQuery).getAliasedCriteria(alias);

was changed to:
Method m = ((org.hibernate.loader.criteria.CriteriaQueryTranslator) criteriaQuery).getClass().getDeclaredMethod("getAliasedCriteria", String.class);
m.setAccessible(true);
cri = (Criteria) m.invoke(((org.hibernate.loader.criteria.CriteriaQueryTranslator) criteriaQuery), alias);

Hopefully this will help anyone else facing the same problem.


text:
Q: spring-boot:build-image with SpringBoot Version 2.3.3.RELEASE - spring-boot-maven-plugin:build-image fails with 400 Bad Request On macOS Big Sur and also on AzureDevOps pipeline I am getting failed: Docker API call to with ./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=springio/gs-spring-boot-docker*

[ERROR] Failed to execute goal
org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image
(default-cli) on project gs-spring-boot-docker: Execution default-cli
of goal
org.springframework.boot:spring-boot-maven-plugin:2.3.0.RELEASE:build-image
failed: Docker API call to
'localhost/v1.24/containers/6cf0cbedfbb65cb5a9826c7fbef5e32266e51dd50e01a5afce99701b1d3f5e2a/start'
failed with status code 400 "Bad Request" -> [Help

Reproduce :
git clone https://github.com/spring-guides/gs-spring-boot-docker.git unzip demo.zip cd demo ./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=springio/gs-spring-boot-docker
Machine:
uname -a Darwin MacBookPro 20.0.0 Darwin Kernel Version 20.0.0: Thu Jul 30 22:49:28 PDT 2020; root:xnu-7195.0.0.141.5~1/RELEASE_X86_64 x86_64
Docker Version:
docker -v Docker version 19.03.12, build 48a66213fe


text:
Q: Recursive function issue I'm working with a tree structure of Installation Places: each one may contain child InstallationPlaces and these can also contain children and so on and so on. I've got the following function:
public JsonResult GetInstPlacesTree()
{
    InstallationPlaceModel ipm = new InstallationPlaceModel();
    var dataContext = ipm.getRootInstallationPlaces();

    var instPlaces = from ip in dataContext.installationPlaces
                    select new
                    {
                        id = ip.installationPlace.id,
                        Name = ip.installationPlace.mediumDescription,
                    };

    return Json(instPlaces, JsonRequestBehavior.AllowGet);
}

This function returns only the root level of the tree.
I have got two working methods:

*

*one returns the root Installation Places;

*the other returns the children of a given Installation Place;

They both return IEnumerable variables.
getRootInstallationPlaces();
getChildInstallationPlaces(id);

How can I achieve to call all the Installation Places and respective children?
I have tried this alternative to the GetInstPlacesTree() function:
private IEnumerable<TreeViewItemModel> GetDefaultInlineData()
{
    InstallationPlaceModel ipm = new InstallationPlaceModel();
    List<TreeViewItemModel> fullTree = new List<TreeViewItemModel>();
    var gipo = ipm.getChildInstallationPlaces(currentInstallationPlace.InstallationPlaceId);
    List<TreeViewItemModel> childTree = new List<TreeViewItemModel>();
    if (gipo.installationPlaces.Count() > 0)
    {
        foreach (wsInstallationPlace.installationPlaceOutput child in gipo.installationPlaces)
        {
            TreeViewItemModel childTreeItem = new TreeViewItemModel
            {
                Text = child.installationPlace.mediumDescription,
                Id = child.installationPlace.id
            };
            childTree.Add(childTreeItem);
        }
    }
    TreeViewItemModel fatherTreeItem = new TreeViewItemModel
    {
        Text = currentInstallationPlace.InstallationPlaceMediumDescription,
        Id = currentInstallationPlace.InstallationPlaceId,
        Items = childTree
    };
    fullTree.Add(fatherTreeItem);
    return fullTree;
}

Any help?

A: I think something like the following should do what you are after. Essentially it keeps your initial method almost as-is but it populates the child Items of each top-level with a recursive call.
The recursive call grabs the children and adds each child to a List<TreeViewItemModel> to be returned but their children are in turn populated by a call to the recursive function. The recursion will end when there are no children left:
public JsonResult GetInstPlacesTree()
{
    InstallationPlaceModel ipm = new InstallationPlaceModel();
    var dataContext = ipm.getRootInstallationPlaces();

    var instPlaces = from ip in dataContext.installationPlaces
                        select new TreeViewItemModel
                        {
                            id = ip.installationPlace.id,
                            Name = ip.installationPlace.mediumDescription,
                            Items = getChildInstallationPlacesRecursive(ip.installationPlace.id, ipm)
                        };

    return Json(instPlaces, JsonRequestBehavior.AllowGet);
}

public List<TreeViewItemModel> getChildInstallationPlacesRecursive(int id, InstallationPlaceModel ipm)
{
    List<TreeViewItemModel> children = new List<TreeViewItemModel>();

    var gipo = ipm.getChildInstallationPlaces(id);

    foreach (wsInstallationPlace.installationPlaceOutput child in gipo.installationPlaces)
    {
        children.Add(new TreeViewItemModel
        {
            Text = child.installationPlace.mediumDescription,
            Id = child.installationPlace.id,
            Items = getChildInstallationPlacesRecursive(child.installationPlace.id, ipm)
        });
    }

    return children;
}

A: To make it recursive, you have to think that child places are, at the same time, roots of their own childs, then you can call the same function for them.
private IEnumerable<TreeViewItemModel> RecursivePlaces(InstallationPlace root){
     var output = new List<TreeViewItemModel>();
     output.add(new TreeViewItemModel
        {
            Text = root.installationPlace.mediumDescription,
            Id = root.installationPlace.id
        });

     foreach(var child in root.installationPlaces)
       output.AddRange(RecursivePlaces(child));

     return output;
}

//Initial call
RecursivePlaces(ipm.getRootInstallationPlace());

A: You can solve this without recursion with following approach. I wrote it in some kind of pseudo-code, so you will get an idea what I suggest to accomplish, I didn't used your exact function names and structures and classes...
queue = new List<>();
queue.Add(initialInstallation);
retVal = new List<>();

while (queue.Count > 0) {
    retVal.Add(queue[0].GetData());
    queue.Add(queue[0].GetChildren());
    queue.Remove(0);
}

return retVal;


text:
Q: Is there a way to embed fonts into a Web Component? Title says it all. I'm developing a Vue app that is going to be used as a display for my instance of Home Assistant. I tell it what JS file to load and what tag to use and HA puts it inside an iframe. The font I'm using is an otf file.
It seems like my component can only use the font when it gets included in the page's  section. Since I'm not generating the page or the iframe, I can't add anything to the head. The only thing I can figure out to do is use JS to add the font face to the head after the page is loaded. I've seen a react component do this. Is there a build option or something?
But it is my understanding the whole point of web components is to be able to include a single JS file then use the component. Does this not include fonts or other resources?


text:
Q: Accessing Fitbit Intra-Day Time Series with httr: Invalid redirect_uri I try to access Fitbit intra-day time series data. When I execute the code below, I always get the following error: "Developer information: invalid_request - Invalid redirect_uri parameter value".
require(httr)

Sys.setenv("HTTR_SERVER_PORT" = "1410/")

fitbit.app <- oauth_app("[MyAppName}", key = "[MyClientID]", secret = "[MySecret]")

fitbit.ep <- oauth_endpoint(
  request = "https://api.fitbit.com/oauth2/token",
  authorize = "https://www.fitbit.com/oauth2/authorize",
  access = "https://api.fitbit.com/oauth2/token"
)

fitbit.token <- oauth2.0_token(fitbit.ep,
                               fitbit.app,
                               scope=c("heartrate"),
                               use_basic_auth = T)

I configured my app under https://dev.fitbit.com to have a callback URL "http://localhost:1410/".
The same problem was described here: https://community.fitbit.com/t5/Web-API-Development/Having-trouble-with-redirect-uri-via-httr-in-R/m-p/1286028/highlight/false#M5194. But the answer flagged as a solution there does not work.
Also, I wonder why "response_type=code" is set, instead of "response_type=token" as I would expect. I tried to set the extra parameter type = "token", but that doesn't change it.
Can someone please help?

A: Okay, fortunately I found the problem myself. The answer might be useful to somebody else as well.
I compared the authorization URL from the code above with the one generated by a Fitbit helper page: https://dev.fitbit.com/apps/oauthinteractivetutorial.
This indicated that the httr-derived redirect_uri contained the suffix "%2F" two times in a row. That means, the encoded redirect_uri was "http://localhost:1410//" instead of "http://localhost:1410/". The solution is to substitute
Sys.setenv("HTTR_SERVER_PORT" = "1410/")

by
Sys.setenv("HTTR_SERVER_PORT" = "1410")

in the code above. Of course, I found the code fragment of setting the environmental variable to "1410/" somewhere in the net. There it was said that it was the central key to get things working. That's life.
I hope that will help others. This damn fitbit API already caused me a lot of headache.


text:
Q: Trying To Understand PHP password_hash I'm trying to learn more about PHP security best practices, and I came across password_hash and the password_compat project by Anthony Ferrara.  I think I understand how to implement it, but in testing, I came across a curious behavior that contradicts my novice understanding of password hashing.
If I save the result of the password_hash function into a MySQL database user record and then retrieve that hash for verification using password_verify, it works as expected.  However, if I do the exact same thing, but rather than pull from the database, I just hard-code the password hash via a copy/paste from the database, the password_verify function fails.
The code is below:
// Get the Username and password hash from the MySQL database.  GetPassTestuser routine returns an array where
//   position[0][0] is the username and position[0][1] is the password hash.
$arrUser = GetPassTestuser("mike24");
echo("User Name: ".$arrUser[0][0]."
");
echo("Password hash: ".$arrUser[0][1]."
");

// Run password_verify with the password hash collected from the database.  Compare it with the string "mytest"
//  (This returns true in my tests).
if (password_verify("mytest",$arrUser[0][1])){
    echo("Password verified");
} else {
    echo("Password invalid");
}
echo("
Now On to our second test...
");
// Now run password_verify with a string representation directly copied/pasted from the database.  This is
//   being compared with "mytest", which in my mind should return a true value.  But it doesn't and this test
//   fails.  Not sure why.
if (password_verify("mytest","$2y$10$S33h20qxHndErOoxJL.sceQtBQXtSWrHieBtFv59jwVwJuGeWwKgm")){  // String shown here is the same as value contained in $arrUser[0][1]
    echo("2nd Test Password verified");
} else {
    echo("2nd test Password invalid");
}

While this isn't something I'd do in real code, I'm just trying to understand what the difference is.  Why does it work OK when I use the string variable that supposedly contains the exact same hash, but doesn't work when it's hard coded?
Thanks!

A: FROM PHP DOC

To specify a literal single quote, escape it with a backslash (). To specify a literal backslash, double it (\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.
If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

Use single quotes
Replace
"$2y$10$S33h20qxHndErOoxJL.sceQtBQXtSWrHieBtFv59jwVwJuGeWwKgm"

With
'$2y$10$S33h20qxHndErOoxJL.sceQtBQXtSWrHieBtFv59jwVwJuGeWwKgm'

Or
"\$2y\$10\$S33h20qxHndErOoxJL.sceQtBQXtSWrHieBtFv59jwVwJuGeWwKgm"

A: Regarding my comment, I figured this would work better as an answer:
if (password_verify("mytest",'$2y$10$S33h20qxHndErOoxJL.sceQtBQXtSWrHieBtFv59jwVwJuGeWwKgm')){  // String shown here is the same as value contained in $arrUser[0][1]
    echo("2nd Test Password verified");
} else {
    echo("2nd test Password invalid");
}

A: Have a look at the Strings chapter in the PHP manual. In short, your hard-coded hash is a PHP string with variable interpolation:
"$2y$10$S33h20qxHndErOoxJL.sceQtBQXtSWrHieBtFv59jwVwJuGeWwKgm"
 ^  ^  ^

Since those variables don't exist, you'll end up with blank substrings a three notices. You should have seen the notices. If you didn't, please check your error reporting settings.
(Hint: use single quotes everywhere except where you do want variable interpolation.)


text:
Q: Can't enter UEFI Boot Manager on Dell R610 This system seems to have a hybrid BIOS / UEFI setup.
Before doing anything, I reset the NVRAM of the machine using the Clear NVRAM jumper on the motherboard..
I can get into the BIOS, and I have set a BIOS password.
When I try to enter the UEFI boot manager, it asks for my 'Setup Password'.
But the password I set for the BIOS doesn't work, and neither does a blank password.  Any ideas?

A: Figured it out:
First, I thought maybe my use of symbols (non-alphanumeric characters) was screwing up the password somehow.  I removed these from the BIOS password but I still wasn't getting into the UEFI successfully.
Decided to re-read the user manual again (which does not mention UEFI setup password specifically, only "Setup Password"), but more carefully this time.
Ran across this line:

You can use up to 32 characters in your password.
  As you type, placeholders appear in the field.
The password assignment is not case-sensitive. To erase a character, press Backspace or the left-arrow key.

[Italics Mine]
Well this got me thinking.  I configured a multi-case password like aBcD1234 in the BIOS, and I was attempting to enter the exact password to enter the UEFI, but it was being rejected.
Here's what was happening: because the BIOS was case-insensitive, it was recording my original password of aBcD1234 as the all-lowercase abcd1234 and passing that on to the access control of the UEFI boot manager.  Apparently the UEFI boot manager password prompt is case-sensitive and so it was not accepting my entry of aBcD1234.  When I tried abcd1234, I was able to enter the UEFI boot manager.


text:
Q: Copy subset of multimap into a new multimap // this has data from elsewhere, just showing its the same type
multimap<string,string> map_with_data;
string string_key = "some_string";

// not working:
multimap<string,string> new_map;

new_map = map_with_data[string_key];

I want a return of a multimap with only the key pairs with the key string_key. What is the right way to do this or is this method of direct copying even possible?
I'm getting: error: no match for 'operator[]' (operand types are 'std::multimap<std::basic_string<char>, std::basic_string<char> >' and 'std::string {aka std::basic_string<char>}')|

A: Something like the following would be my first choice:
auto r = map_with_data.equal_range(string_key);

multimap<string, string> new_map(r.first, r.second);

This finds all the items in the existing map with the specified key, then initializes the new map from those iterators. If there is no item in the existing map with that key, you'll get map_with_data.end() for both r.first and r.second, so your new_map will end up empty (as you'd probably expect).
If you really wanted to, you could use lower_bound and upper_bound instead of equal_range:
multimap<string, string> new_map {
    map_with_data.lower_bound(string_key),
    map_with_data.upper_bound(string_key) };

I prefer the code using equal_range though.
Demo code:
#include <map>
#include <string>
#include <iostream>
#include <iterator>

using namespace std;

namespace std {
    ostream &operator<<(ostream &os, pair<string, string> const &p) {
        return os << "(" << p.first << ", " << p.second << ")";
    }
}

int main() {

    multimap<string, string> map_with_data {
        {"A", "B"},
        {"A", "C"},
        {"B", "B"},
        {"B", "C"}
    };

    auto r = map_with_data.equal_range("A");

    multimap<string, string> new_map(r.first, r.second);

    copy(new_map.begin(), new_map.end(),
        ostream_iterator<pair<string, string>>(std::cout, "\n"));
}

Result:
(A, B)
(A, C)


text:
Q: How to go to a certain path (folder containing a certain file) in Total Commander? Let's say I have a certain - very long - path to a file (let's say: c:\Documents and Settings\Username\Application Data\Mozilla\Firefox\Profiles\ )  and I would like to quickly access that directory in Total Commander. Is there any dialog box / keyboard shortcut which would allow me to simply paste the path there and enter that location, instead of the tedious process of digging into the directory tree?

A: If you click twice on the top, where current path is displayed, it will change to edit field, where you can just enter new path and press Enter.
You can switch to edit mode if cursor is on the [..] and you press Shift+F6.
Another option is to write path into command line, preceding it with cd like this:
cd path_to_the_directory

then press enter.

A: If you find yourself browsing to a specific folder a lot of times, you can add it to the quickselect (the little button with the asterisk), you can add the current folder (optionally including the other pane folder), and you can manage this into a tree set of folders.

A: Create tabs (press Ctrl + T) for folders you use often.
Browse to the folder then right click on the tab and lock the tab.
The tabs are always shown when you start total commander it saves a lot of browsing to folders when you have created tabs for the most used folders.

A: The selected answer doesn't work if you're in the root since there is no [..] there.
There is a keyboard shortcut you can assign to focus the path textbox: cm_EditPath.
Set a shortcut in Options -> Misc -> Redefine hotkeys


text:
Q: Updating the ListFragment     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_schedule, container, false);

        // array adapter + list fragment
        arrayAdapter = new ArrayAdapter<>(getActivity(),
                R.layout.simple_list_item_1_custom,
                schedules.get(getArguments().getInt(ARG_SECTION_NUMBER) - 1)); //

        arrayAdapter.setNotifyOnChange(true);
        setListAdapter(arrayAdapter);
        return rootView;
    }

This is the onCreateView of my class that extends ListFragment, I am trying to update the contents of the list from my activity, so far I've tried clearing the arrayAdapter and calling notifyDataSetChanged on it, and it doesn't work. The only way I can get my list to update is if I swipe two tabs and go back again, then it shows all the changed values. Any suggestions?

A: This is the onCreateView of your fragment. This is fired every time when you create your fragment or swipe between tabs. As I understand, you just add values to the db onClick and when you go and come back your fragment you see the new values.
Please, try adding new values to your adapter on onClick button then try updating your list in the same scope with the NotifyDataChanged mechanisim of the adapter.
If I get wrong idea about whay you are doing pleas share more code.


text:
Q: Partitioning a Stream I am working with a Stream of Person data and I've run into a partitioning issue related to the data.
I have a Stream of data which I'll represent below in a table:
ID  Name Ticket IsEmployee
1   A      Y        Y
2   B
3   C      Y
4   D

I am trying to return a List that is sorted by:

*

*whether or not they're an Employee

*if they have any Tickets

*then by Name

I've looked into Collections.groupBy and Collections.partitioningBy, but so far haven't been able to come up withe the correct result.
My expectations are to return a list in the following order (by ID):
1   [name="A",Ticket="**[100,101]**", IsEmployee="**Y**"],
3   [name="C",Ticket="**[200,201]**", IsEmployee=""],
2   [name="**B**",Ticket="", IsEmployee=""],
4   [name="D",Ticket="", IsEmployee=""]

Any thoughts on how this might be accomplished without having to totally break apart the Stream?
Below is what my Person looks like:
public class Person {

   private long id;
   private String name;
   private List<Ticket> tickets;
   private String employeeType;  // This is just a 'Y'/'N' value.  This property has morphed into something else but I'm stuck using it.

   public long getId(){
    return id;
   }
   public String getName(){
    return name;
   }
   public List<Ticket> getTickets(){
    return tickets;
   }
   public String getEmployeeType(){
    return id;
   }
   // Setters are the exact same as getters, meaning I have no transient methods
}

A: Since you are saying "I am trying to return a List that is sorted by…", it's not clear why you started looking for grouping or partitioning, instead of aiming exactly at, what your problem description is about, get a List and sort it by your criteria:
// collect into a mutable List, if it isn't a mutable List in the first place
List<Person> list=stream.collect(Collectors.toCollection(ArrayList::new));

// sort by your specified criterie (note: false < true)
list.sort(Comparator.comparing((Person p) -> !p.getEmployeeType().equals("y"))
                    .thenComparing(p -> p.getTickets().isEmpty())
                    .thenComparing(Person::getName) );

You can also specify the operation as part of the Stream operation, e.g.
List<Person> list=stream
    .sorted(
        Comparator.comparing((Person p) -> !p.getEmployeeType().equals("y"))
                  .thenComparing(p -> p.getTickets().isEmpty())
                  .thenComparing(Person::getName) )
    .collect(Collectors.toList());

but there is no technical benefit. The Stream implementation has to collect the entire contents into a temporary buffer internally, to sort it before it is collected (i.e. copied) into the resulting List. The in-place sorting of ArrayList may get away with lesser or even without data copying (not that it matters for four elements, but in general).


text:
Q: Is this ERD diagram correct? The criteria is as follows:

*

*The bank is organized into branches. Each branch is located in a
particular city and is identified by a unique name.

*A customer is associated with a particular banker, who may act as
personal banker for that customer.

*Bank employees (bankers) are identified by their employee-id values.
The bank administration stores the name and telephone number of each
employee, address.

*There are some employees whose role is manager. Each manager
manages a number of employees and each employee reports to his own
manager. Each branch has only one employee as its manager and each
employee can manage only one branch and the employees in that
branch.

*The bank offers two types of accounts saving and current accounts. Both
types of accounts can be held by more than one customer, e.g. joint
accounts, and a customer can have more than one account.

*In addition, each savings account has an interest rate, and overdrafts are
recorded for each current account.
I haven't included any attributes, but are my entities, relations and cardinalities correct?


text:
Q: Have Doxygen link type to file for C I'm creating a module in C. When I refer to that module in the documentation, I want a link to the header file, not the struct (because the functions and other useful information are at the file level).
The file my_iterator.h contains
  typedef struct {
    int foo;
    int bar;
  } my_iterator_t;

I would like references to my_iterator to create a link to my_iterator.h.  For example,
/**
  Create a new, specially configured my_iterator
*/
my_iterator_t* special_factory_in_another_module();

Putting "my_iterator.h" in the documentation would create the correct link, but would sound strange.  Putting my_iterator_t in the documentation would sound better, but not link to a useful place.

A: Although it is a bit verbose, this does what I want:
/**
 * Create a new, specially configured [my_iterator](@ref my_iterator.h)
 */
my_iterator_t* special_factory_in_another_module();


text:
Q: Problem rendering a PowerPoint to png in C# using COM under an IIS service first of all, my program CAN render a pptx to png, the quality is just greatly reduced when rendering on Windows Server 2008 R2 and I'm wondering why.
I tested my program on windows 7 x64 using Cassini and the rendering to png of the pptx is perfect. But when I deploy my program on IIS and try to render the pptx, the quality of its rendering is reduced.
This is the link the same image, one rendered under windows 7 cassini and the other under windows server 2008.
The perfect quality one: http://dl.dropbox.com/u/2458800/exemple-high-quality.png
The low quality one: http://dl.dropbox.com/u/2458800/exemple-low-quality.png
It appears to be some sort of an antialiasing problem.
Finally, here is my code:
var powerPoint = new Application();

var presentation = powerPoint.Presentations.Open(sourceFile,
      MsoTriState.msoFalse, MsoTriState.msoTriStateMixed, MsoTriState.msoFalse);

presentation.Export(destinationDir, "png", 960, 720);

presentation.Close();

powerPoint.Quit();

EDIT:
Well I knew that going with PowerPoint COM would be a problem on a server. Tried Aspose and that solved the problem.

A: using PPT automation in a service (IIS is a service) is NOT supported by MS... see http://support.microsoft.com/default.aspx?scid=kb;EN-US;q257757#kb2
Use a 3rd-party solution without automation (for example Aspose)... not affiliated..

A: Use, say, SysInternals' ZoomIt utility to see the difference.  The text that was rendered by the server is not anti-aliased.
Microsoft sternly warns that Office programs were designed to run on a work station and are not suitable for use in a server environment.  This is one of the side-effects.  You'll have to ask the server administrator to put the server's video adapter in a 32 bpp mode with anti-aliasing enabled.  I hope it has one.  Ask more about this at serverfault.com


text:
Q: CSS height 100% of its parent i have this page: http://www.nyccriminallawyer.com/felonymisdemeanor/
what i want to do is make the left inner box (the white one with Felony/Misdemeanor as title called .in_left) to be of 100% height of its parent (called .inner)
codes are here:
.in_left {
float: left;
width: 721px;
margin-top: 10px;
font-family: 'Open Sans', sans-serif;
line-height: 24px;
background-color: white;
border-radius: 4px 4px 4px 4px;
box-shadow: 0px 0px 11px -4px #000;
}

.inner {
background: #CCD7CC;
margin-top: 1px;
color: #5A5A5A;
padding: 10px;
clear: both;
overflow: hidden;
}

i have tried height: 100% and min-height as well, but it doesn't work.

A: Don't use float on .in_left and .in_right, use display:table-cell; on those and, most importantly, use display:table; on their container:
.inner {
    display: table;
}
.in_left {
    width: 229px;
    /* other style */
    display: table-cell;
}
.in_left {
    width: 721px;
    /* other style */
    display: table-cell;
}

A: You cannot extend a child to be 100% the height of its parent, but you can make it look like it extends using the Faux Columns technique.

A: Setting the height of an element 100% only works if the parent elements height is somehow fixed (like height: 300px). But you can set the child element absolutely positioned (to its immediate parent) and set it's position in four directions:
.in_left {
  ...
  position: relative;
}

.inner {
  ...
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}

Demo here: http://jsbin.com/OkIQUCi/1/


text:
Q: PDE Method of Characteristics with -1 in the denominator of third term I want to solve the equation with characteristic terms
$$\frac{ds_0}{k_1x_2(s_3-s_0)}=\frac{ds_3}{k_2(s_0-s_3)}=\frac{dt}{-1}=\frac{dG}{0}$$
I have calculated $$c_1=G$$ from $$\frac{dG}{0}$$
And $$c_2=k_2s_0+k_1x_2s_3$$ from first two terms. But I am not able to calculate $$c_3$$ for $$G(t,s_0,s_3)$$

A: $$\frac{ds_0}{k_1x_2(s_3-s_0)}=\frac{ds_3}{k_2(s_0-s_3)}=\frac{dt}{-1}=\frac{dG}{0}$$
You correctly found the second characteristic equation :
$$k_2s_0+k_1x_2s_3=c_2\quad\implies\quad s_3=\frac{c_2-k_2s_0}{k_1x_2}$$
From $\frac{ds_0}{k_1x_2(s_3-s_0)}=\frac{dt}{-1}$ :
$$\frac{ds_0}{c_2-k_2s_0-k_1x_2s_0}=-dt$$
Solving leads to the third characteristic equation :
$$\bigg((k_2+k_1x_2)s_0-c_2 \bigg)e^{-(k_2+k_1x_2)t}=c_3$$
$$k_1x_2(s_0-s_3)e^{-(k_2+k_1x_2)t}=c_3$$


text:
Q: Object internal reference declarations I'm watching out for a shortcut way to use values from a dictionary as an internal reference inside the dictionary. The code shows what I mean:
var dict = {
    'entrance':{
        'rate1': 5,
        'rate2':10,
        'rate3':20,
    },

    'movies':{
        'theDarkKnight':{
            '00:00':<entrance.rate1>,
            '18:00':<entrance.rate2>,
            '21:00':<entrance.rate3>
        },
        ...
    };

is there a sneaky way to do this?

A: You could use mustache and define your json as a "mustache template", then run mustache to render the template. Take into account you would need to run (n) times if you have nested dependencies. In this case you have 3 dependencies ABC --> AB --> A.
var mustache = require('mustache');

var obj = {
  A : 'A',
  AB : '{{A}}' + 'B',
  ABC : '{{AB}}' + 'C'
}

function render(stringTemplate){
  while(thereAreStillMustacheTags(stringTemplate)){
    stringTemplate = mustache.render(stringTemplate, JSON.parse(stringTemplate));
  }
  return stringTemplate;
}

function thereAreStillMustacheTags(stringTemplate){
  if(stringTemplate.indexOf('{{')!=-1)
    return true;
  return false;
}

console.log(render(JSON.stringify(obj)));

And the output is:
{"A":"A","AB":"AB","ABC":"ABC"}

A: No. The best you can do is:
var dict = {
    'entrance' : {
        'rate1' : 5,
        'rate2' : 10,
        'rate3' : 20,
    }
};
dict.movies = {
    'theDarkKnight' : {
        '00:00' : dict.entrance.rate1,
        '18:00' : dict.entrance.rate2,
        '21:00' : dict.entrance.rate3
    },
    ...
};


text:
Q: Main stream synonym of "clown fiesta" meaning consummate display of ineptitude I seem to remember having read or heard a possibly compound noun describing a hilariously incompetent performance. The context at the time was football (soccer).
Trying to remember what it was I came up with clown fiesta but that appears to be a rather niche term "used by the League of Legends gaming community". (I don't even know league of legends, so I wonder where I picked that one up.)
If the field of inexpertise is specified I think "comedy" as in "comedy defending" (context: football again) can be used but I am looking for a stand-alone term.

A: The Cambridge dictionary indicates that the informal term joke would be appropriate:

a person or thing that is very bad or silly

There are also various lesser-used terms that contain the f-word.

A: At least in the UK a term which acquired currency recently is omnishambles. According to its Wikipedia entry it was the Oxford English Dictionary word of the year for 2012. It does have the advantage that anyone who knows what a shambles is and is familiar with the prefix omni- can immediately grasp what it means.


text:
Q: Why doesn't function variable initialize correctly in this example? Executing the following code:
def foo(b=[]):
    b.append(1)
    print(b)
foo()
foo()
foo()

The result is unexpectedly:
[1]
[1, 1]
[1, 1, 1]

Investigating variable "b" memory address for different function calls:
def foo(b=[]):
    b.append(1)
    print(id(b))
foo()
foo()
foo()

returns the same value three times, whereas apparently variable initialization should create new [] object each time. Could you explain this to me please?


text:
Q: Problem compiling stl map insert I'm having trouble compiling the following code:
typedef std::map<mUUID, block_ptr_t> BlockMap;
BlockMap _store;

std::pair< BlockMap::iterator, bool > it;
it = _store.insert(hint, std::make_pair(entry.block_uid, block));

The error is:
error: no match for 'operator=' in 'it = BlockStore::_store.std::map<_Key, _Tp, _Compare, _Alloc>::insert [with _Key = mUUID, _Tp = Block*, _Compare = std::less<mUUID>, _Alloc = std::allocator<std::pair<const mUUID, Block*> >](lb, ((const std::pair<const mUUID, Block*>&)(& std::pair<const mUUID, Block*>(((const std::pair<mUUID, Block*>&)((const std::pair<mUUID, Block*>*)(& std::make_pair(_T1, _T2) [with _T1 = mUUID, _T2 = Block*](block))))))))'
/usr/include/c++/4.4/bits/stl_pair.h:68: note: candidates are: std::pair<std::_Rb_tree_iterator<std::pair<const mUUID, Block*> >, bool>& std::pair<std::_Rb_tree_iterator<std::pair<const mUUID, Block*> >, bool>::operator=(const std::pair<std::_Rb_tree_iterator<std::pair<const mUUID, Block*> >, bool>&)

It seems to be related to the assignment because if I don't assign it to "it" it compiles without error.

A: The version of insert that takes a hint returns only an iterator, not a pair.

A: First of all, your example is incomplete - _store is defined nowhere.
Second, it seems you are trying to assign an iterator to a std::pair - why do you need a pair, anyway?
The following should work, provided that _store is of type BlockMap:

BlockMap::iterator it;
it = _store.insert(std::make_pair(entry.block_uid, block));


text:
Q: PHP: test == return false when he should not I'm working with symfony2, and i really don't understand what's happen with this.
 i have a == test, who don't return true when he should !At the very first iteration of that foreach, the == 's for test answer one time true, but after the first foreach iteration he don't find the other match... I had tried a lot of var_dump, and the var_dump say that: $service->getId()  is  int(24),  and $discountsID is int(24), but the == test isn't true.
So help me, i'm pretty noob with php, and i really don't get what's happen there..
foreach ($services as $service) {
    for ($i = 0; $i < count($discountsID); ++$i) {
        if ($service->getId() == $discountsID[$i]) { //the fail test..
            $bool = $discounts[$i]->getId();
        } else {
            $bool = -1;
        }
    }

    $view_data['services'][] = array(
        'discountId' => bool,
    );
}

A: You may also want to include a condition in your for that terminates the loop where your if condition is reached.  Many persons don't like break (neither I do) but this would work:
if( $service->getId() == $discountsID[$i] ){ //the fail test..
    $bool = $discounts[$i]->getId();
    break;
}

A: Above the test, add this:
var_dump($service->getId());
var_dump($discountsID[$i]);
die();

And see if the outcome matches
Also this seems wrong to me:
foreach ($services as $service) {
$service->getId()

What does $services consist of?


text:
Q: PostgreSQL accessing multiple elements from array by using positional array I'd like to know whether it is possible in PostgreSQL to output an array from multiple elements of an array by using another array indicating a series of positions for elements.
To be precise:
array1 = [1,2,1]
array_positions(array1,'1') = {1,3}
array2 = ['hello', 'bye', 'hello']

Desired result:
array2[array_positions(array1,'1')] = {'hello', 'hello'}

I receive ERROR:  array subscript must have type integer
Any suggestions?

A: The missing part is a function/operator that returns array elements from specified positions (I really surprised that it is absent in the release, hope it will be fixed). Lets create them:
create or replace function array_from_positions(anyarray, int[]) returns anyarray
  immutable language sql
as $$
  select array_agg(a.x order by b.i)
  from
    unnest($1) with ordinality as a(x,i)
      right join unnest($2) with ordinality as b(x,i) on (a.i=b.x)
$$;

Test:
select
  array_from_positions('{a,b,c,d}'::text[], '{2,1,10}'),
  array_from_positions('{1,2,3,4}'::int[], '{2,1,10}');

┌──────────────────────┬──────────────────────┐
│ array_from_positions │ array_from_positions │
├──────────────────────┼──────────────────────┤
│ {b,a,NULL}           │ {2,1,NULL}           │
└──────────────────────┴──────────────────────┘

create operator ## (
  procedure = array_from_positions,
  leftarg = anyarray,
  rightarg = int[] );

Test:
select
  '{a,b,c,d}'::text[] ## '{2,1,10}',
  '{1,2,3,4}'::int[] ## '{2,1,10}';

┌────────────┬────────────┐
│  ?column?  │  ?column?  │
├────────────┼────────────┤
│ {b,a,NULL} │ {2,1,NULL} │
└────────────┴────────────┘

And final test for your example:
with your_table(array1,array2) as (values
  ('{1,2,1}'::int[], '{hello,bye,hello}'::text[]))
select array2 ## array_positions(array1, 1) from your_table;

┌───────────────┐
│   ?column?    │
├───────────────┤
│ {hello,hello} │
└───────────────┘

A: This may or may not be too complicated to be useful, but it does prove it's possible:
SELECT vals.*
FROM (
  VALUES(array['hello', 'bye', 'hello'])
) AS t (arr)
JOIN lateral unnest(t.arr) WITH ORDINALITY AS vals(element, idx) ON TRUE
WHERE vals.idx = ANY(array_positions(array[1,2,1], 1));


text:
Q: Why is this D3 drag not working? I'm new to D3 and just started playing with it. I want to move a pre-created rect (or circle) through drag and drop. Here is my fiddle.
// Create the SVG
var svg = d3.select("body").append("svg")
  .attr("width", 700)
  .attr("height", 400);

// Add a background
svg.append("rect")
  .attr("width", 700)
  .attr("height", 400)
  .style("stroke", "#999999")
  .style("fill", "#F6F6F6")

svg.append("circle")
.attr({ cx: 50, cy: 50, r: 5, fill: "red" })
.style("cursor", "pointer")
.call(drag);

svg.append("rect")
.attr({ x: 20, y: 20, width: 10, height: 10, fill: "blue" })
.style("cursor", "pointer")
.call(drag);

// Define drag beavior
var drag = d3.behavior.drag()
    .on("drag", dragmove);

function dragmove(d) {
  var x = d3.event.x;
  var y = d3.event.y;
  d3.select(this).attr("transform", "translate(" + x + "," + y + ")");
}

Two questions:

*

*How to make the drag move work?

*Why is my rect not showing up?

A: http://jsfiddle.net/5hemY/1/
Quick debugging led me to find that drag wasn't defined yet when you were trying to .call() it


text:
Q: AssertEqual failing when comparing two seemingly identical IndexErrors I have a DynamicArray class shown below. (I have only included relevant methods. The rest can be viewed from https://www.geeksforgeeks.org/implementation-of-dynamic-array-in-python/)
import ctypes

class DynamicArray:
    '''
    Dynamic Array class
    '''

    def __init__(self):
        self.n = 0 # count number of elements
        self.capacity = 1 # default capacity
        self.A = self.make_array(self.capacity)

    def __len__(self):
        """
        Return number of elements in the array
        """
        return self.n

    def __getitem__(self,k):
        """
        Return element at k index
        """

        #Check if K index is out of bounds#
        if not 0 <= k < self.n:
            return IndexError('{} is out of bounds'.format(k))

        return self.A[k] #Retrieve from the array at index k#

Then I have another unit test file down below
from DynamicArray import DynamicArray
import unittest

class MyTestCase(unittest.TestCase):
    def setUp(self) -> None:
        self.a = DynamicArray()  # empty array

        self.b = DynamicArray()
        self.b.append(0)

        self.c = DynamicArray()
        self.c.append(0)
        self.c.append(1)

    def test_getitem(self):
        self.assertEqual(self.a.__getitem__(0),IndexError('0 is out of bounds'))

When I run the test I expect self.a.__getitem__(0) to throw IndexError('0 is out of bounds') and I can't see why the assertion fails? The only difference is that self.a.__getitem__(0) will yield IndexError('{} is out of bounds'.format(0)), which seems to me the same as IndexError('0 is out of bounds')
I tried running below code to see if the string by themselves were any different
    if '{} is out of bounds'.format(0) == '0 is out of bounds':
        print('str equal')
    if '{} is out of bounds'.format(0).__len__() == '0 is out of bounds'.__len__():
        print('len equal')
    if IndexError('{} is out of bounds'.format(0)) == IndexError('0 is out of bounds'):
        print('IndexError equal')

and confirmed that only the third if statement did not print
below is the photo of the console

Thanks in advance. Constructive criticisms and feedbacks are welcome.

A: Exceptions can't be conpared with assertEqual.
with self.assertRaises(IndexError, msg='0 is out of bounds'):
    self.a[0]

And Exceptions must be raiseed to be captured.
You're returning IndexError
raise IndexError('{} is out of bounds'.format(k))

https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises


text:
Q: Project hangs on QProcess::start when starting QtAssistant I am using QProcess::start to launch Qt Assistant with my custom help project file. It works fine until i load project(not help project file) to my programm. Programm generates images from specific data using custom library. Even when all processes ends and i see generated images and nothing else happens, when i trying to launch Qt Assistant, my programm hangs at QProcess:start function when trying to start process. The code is:
show() function(public):
if (!run())
    return false;
QByteArray ba("setSource ");
ba.append("qthelp://insyn_help/doc/");

proc->write(ba + page.toLocal8Bit() + '\n');
return true;

run() function(private):
if (!proc)
    proc = new QProcess();
if (proc->state() == QProcess::Running)
    return true;
QString app = QString(QT_BIN_DIR) + QDir::separator() + QString("assistant");
QString path = QString(PREFIX) + QString(HELP_INSTALL_PATH) + QString("/help_project.qhc");
QStringList args;
args << QLatin1String("-collectionFile")
     << QLatin1String(path.toLatin1())
     << QLatin1String("-enableRemoteControl");

QFileInfo help_project(path);
if (help_project.exists()) {
    proc->start(app,args);
    if (!proc->waitForStarted()) {
        m_exitCode = 1;
        emit closed();
        return false;
    }
}

This code is a part of AssistantLauncher class which was registered using qmlRegisterType and added to main.qml as a member of application window. My programm doesn't touch it anywhere (except calling a method show()). It is separate object (except it is a part of appWindow). The question is why does the process can not start only after my programm did some work? And why QProcess::start even dont have timeout.
UPD: I moved proc->start(app,args); to the child process, which i getting by using fork() and now my programm hangs on pid_t child = fork(). So the problem is that new process can not be created.

A: The answer is to do not use fork() because it is dangerous in big projects. More at http://www.evanjones.ca/fork-is-dangerous.html . posix_spawn also hangs my project. Now i decided to fork() new process at the beginning and send commands to it through the pipe.


text:
Q: ChartJS: Fixed width for data-part, the rest for labels I'm using ChartJS to display multiple charts on a page.
Each chart has a different dataset, and different labels (some have short labels, some have long labels).
Currently the width of the actual 'data-part' (the part of the chart showing e.g. Bars) depends on how much space the labels take. I would like to make all charts have a fixed size for the data-part, and let the labels take up the remaining size.
See for example the following screenshot. Here I display 2 charts, but the actual data-part is different for both, because one has shorter labels than the other.

What I would like is to set for example a fixed width of 400px for the data-part, and let the labels take the remaining space left on the page. That way the charts would be aligned perfectly above each other.
Even better would be if I could set that for each chart the data-part takes a percentage of the width (e.g. 70%), so the labels take the rest (30%).
I have checked the ChartJS documentation, but the only I can find it setting the width for the entire chart-component.

A: Cheeky solution - you can add a dummy chart before your charts having the same labels.
Let's call this dummy chart as chart D and your main chart as chart M.
In M, you would fix it's width and hide the labels by writing in options -

scales: {y: {ticks: {display: false}}}

Now you have a fixed data width.
In D, you would just display the labels and hide the data part (hiding grid lines, legend, title, etc.).
So now you have two charts side-by-side, one is displaying just the labels and the other displaying the bars, just need to position it in such a way that no matter how long the label is, it does not overlap with M. Repeat the step similarly for all charts and have the same width for M1,M2,M3,...
This is a solution that seemed to work for me.


text:
Q: Javascript Accordion - Fix Issue Where it Scrolls to Bottom of Accordion When Clicking Accordion Title Accordion works great except for one issue: when i try to open another Accordion (2, 3 or 4), it auto-scrolls to the bottom of that accordion instead of staying where i clicked and staying at the TOP of that accordion section.
Codepen to test it out.
TEST IT OUT

*

*open up section 2

*Then scroll down to section 3 and click it to open it, you'll see that it auto scrolls to the bottom of section 3.  Or click around to any of them and you'll see it does it at random / but mostly on all of them.

NOTE
Need first accordion open when the page opens.
I'd like it though that if click on Accordion Title 4 that it stays at the same point on the screen instead of taking me to the bottom of the panel.
IMPORTANT NOTE: it does seem that when all accordion panels are closed, and i try to open one, the problem DOES NOT Occur. For example, if the first accordion is open by default, and I open Accordion 4 it scrolls to bottom of Accordion 4 instead of staying where i clicked "Accordion 4". If I close the first one though, and they're all closed, it doesn't seem to have that issue.
Anyone know why it would be doing this, or a fix to the Javascript code?
JAVASCRIPT CODE
  // W3C's JS Code
  var acc = document.getElementsByClassName("accordion");
  var i;

  // Open the first accordion
  var firstAccordion = acc[0];
  var firstPanel = firstAccordion.nextElementSibling;
  firstAccordion.classList.add("active");
  firstPanel.style.maxHeight = firstPanel.scrollHeight + "px";

  // Add onclick listener to every accordion element
  for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
      // For toggling purposes detect if the clicked section is already "active"
      var isActive = this.classList.contains("active");

      // Close all accordions
      var allAccordions = document.getElementsByClassName("accordion");
      for (j = 0; j < allAccordions.length; j++) {
        // Remove active class from section header
        allAccordions[j].classList.remove("active");

        // Remove the max-height class from the panel to close it
        var panel = allAccordions[j].nextElementSibling;
        var maxHeightValue = getStyle(panel, "maxHeight");

      if (maxHeightValue !== "0px") {
          panel.style.maxHeight = null;
        }
      }

      // Toggle the clicked section using a ternary operator
      isActive ? this.classList.remove("active") : this.classList.add("active");

      // Toggle the panel element
      var panel = this.nextElementSibling;
      var maxHeightValue = getStyle(panel, "maxHeight");

      if (maxHeightValue !== "0px") {
        panel.style.maxHeight = null;
      } else {
        panel.style.maxHeight = panel.scrollHeight + "px";
      }
    };
  }

  // Cross-browser way to get the computed height of a certain element. Credit to @CMS on StackOverflow (http://stackoverflow.com/a/2531934/7926565)
  function getStyle(el, styleProp) {
  var value, defaultView = (el.ownerDocument || document).defaultView;
  // W3C standard way:
  if (defaultView && defaultView.getComputedStyle) {
    // sanitize property name to css notation
    // (hypen separated words eg. font-Size)
    styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
    return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
  } else if (el.currentStyle) { // IE
    // sanitize property name to camelCase
    styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
      return letter.toUpperCase();
    });
    value = el.currentStyle[styleProp];
    // convert other units to pixels on IE
    if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
      return (function(value) {
        var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
        el.runtimeStyle.left = el.currentStyle.left;
        el.style.left = value || 0;
        value = el.style.pixelLeft + "px";
        el.style.left = oldLeft;
        el.runtimeStyle.left = oldRsLeft;
        return value;
      })(value);
    }
    return value;
  }
}


text:
Q: Can a user log into a Windows domain on a Win7 workstation before the network drivers come up? I have a user who uses a pretty high end 3D package called Virtual Gibbs.  Just last month I built him a new super fast computer with an SATA 6G/s SSD.  For some odd reason when the user first logs on in the morning the login script doesn't run (I should say the machine is authenticating on a Windows 2008r2 domain.)  If he wait a few minutes after booting before logging in then the login script runs fine.  I'm assuming that somehow the login process is being loaded in the OS before the network drivers?  Maybe because of the speed of the SSD?  Is there anyway to make Windows 7 wait for the network to come up before it allows the user to login and initiate a non-existent login script?
Thanks

A: There's a GPO setting under Computer Configuration|Administrative Templates|System|Logon called "Always wait for the network at computer startup and logon", which turns off Fast Logon Optimization, which I believe is relevant for Windows 7 (this GPO setting has been around since at least W2K3 and was intended for Windows XP clients). Enable this GPO setting in an appropriate GPO and see if it resolves the issue.

A: To answer the question in your title: Yes, it is possible to login without network connectivity, if the user has been logged in on the computer at least once with contact to the AD.


text:
Q: Campo file com Jquery Estou criando um upload através de um modal dessa forma:

        <button type="button" class="close" data-dismiss="modal">×</button>

ALTERAR FOTO

          <form method="post" id="form-upload" novalidate enctype="multipart/form-data">
               Tamanho da imagem: 1170 x 300

                    <button class="btn btn-success waves-effect waves-light">Foto</button>

                <input type="file" id="submit" name="FotoCapa" class=""/>
                <input type="text" class="md-form-control md-form-file">

          </form>

          <button type="submit" class="btn btn-primary">Alterar</button>
        <button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>

Com Jquery, estou fazendo dessa forma:

O problema é que quando tento pegar o valor com PHP:
$foto = $_FILES["FotoCapa"]['name'];
echo json_encode($foto);

No console aparece o seguinte erro:
(index):596 Uncaught TypeError: Cannot read property '0' of undefined
    at HTMLButtonElement.<anonymous> ((index):596)
    at HTMLButtonElement.dispatch (jquery-3.1.1.min.js:3)
    at HTMLButtonElement.q.handle (jquery-3.1.1.min.js:3)

Quando altero essa linha:
formData.append('image', $('#fotoCapa').prop('files'));

O console retorna null.

A: O erro está na hora em que você invoca a função, se chamá-la no evento click, o arquivo ainda não existe, tanto que a janela de seleção de arquivos do navegador nem chega a abrir, você tem que chamá-la no evento change, quado a janela já foi aberta e o arquivo foi selecionado pelo usuário.
Seu código com as alterações:

$(function(){
    $('#submit').change(function(e) {
      e.preventDefault();
      alert($('#submit').prop('files')[0].name)
      var formData = new FormData();
      formData.append('image', $('#submit').prop('files')[0]);
      $.ajax({
          url: 'alterar-foto-capa.php',
          data: formData,
          type: 'post',
          success: function(response){
             console.log(response);
              if(response){
                 $('#success').html("
A foto foi alterada com sucesso!
");
                  $('#fotoCapa').val('');
              }else{
                $('#success').html("
" + response + "
");
             }
          },
          processData: false,
          cache: false,
          contentType: false
      });
   });
});

        <button type="button" class="close" data-dismiss="modal">×</button>

ALTERAR FOTO

          <form method="post" id="form-upload" novalidate enctype="multipart/form-data">
               Tamanho da imagem: 1170 x 300

                    <button class="btn btn-success waves-effect waves-light">Foto</button>

                <input type="file" id="submit" name="FotoCapa" class=""/>
                <input type="text" class="md-form-control md-form-file">

          </form>

          <button type="submit" class="btn btn-primary">Alterar</button>
        <button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>

Quando for resgatar via PHP, vai ter que utilizar o mesmo nome que usou em formData.append()


text:
Q: statvfs issue - printf / debugger Im trying to use statvfs to find free space on a file system.
Here's the code:
const char* Connection::getDiskInfo()
{
struct statvfs vfs;
int nRet = statvfs( "/u0", &vfs );
if( nRet ) return NULL;

char* pOut = (char*)malloc( 256 );
memset( pOut, 0, 256 );

sprintf( pOut, "<disk letter='%s' total='%lu' free='%lu' totalfree='%lu'/>",
    "/", ( vfs.f_bsize * vfs.f_blocks ) / ( 1024 * 1024 ),
    ( vfs.f_bsize * vfs.f_bavail ) / ( 1024 * 1024 ),
    ( vfs.f_bsize * vfs.f_bfree  ) / ( 1024 * 1024 ));

return pOut;
}

In the debugger (NetBeans 6.9) I see the appropriate values for the statvfs struct:
f_bavail = 105811542
f_bfree = 111586082
f_blocks = 111873644
f_bsize = 4096

this should give me total=437006 but my output insists that total=2830. Clearly Im doing something ignorant in my formatting or math.
If I add the line:
unsigned long x = ( vfs.f_bsize * vfs.f_blocks );

x evaluates to 2967912448 while the debugger shows me the appropriate values (see above).
system: Linux version 2.6.18-194.17.1.el5PAE
i386
I've read the other entries here referring to this function and they make it seem pretty straightforward. So where did I go astray?

A: What is the size of fsblkcnt_t?  If it's 32-bit then it's an overflow problem and you simply need to temporarily use a 64-bit size during the calculation.


text:
Q: How can we apply editable marker for polygon in google map I am working on polygon distance area,with this i want to add marker and want to get the distance between that, I found code for that, but i am not able to edit that polygon area and not able to add markers, i tried lot but it is not working for me, can anyone please help me for this, how can i resolve this issue ?
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Polygon Arrays</title>

A: To add markers, edit your script and place this code under triangleCoords:
// Add Markers to Coordinates
    for(var i = 0; i < triangleCoords.length; i++) {
      var pos = triangleCoords[i];
      var marker = new google.maps.Marker({
        map: map,
        position: pos,
        draggable: true
      });
      marker.setMap(map);
      markers.push(marker);
    }

To do some specific with markers, go here: Learn About Marker
To get distance, use Distance Matrix: Learn About Distance Matrix
Hope that helps you get moving.
JSBin: copy of your code w/ marker