text:
Q: Does "is potentially faster" imply "is not slower"? Someone said to me, "X is potentially faster than Y". Without any clarification at that point, I immediately assumed that the speaker thought that X was at least not slower than Y.
It was revealed in a further discussion, however, that the speaker did not know much about the current performance of either X or Y. What they meant was that, if both were given equal opportunities for optimisation, X would certainly end up faster (and, probably, that it might already be the case).
I agree that "potentially so and so" can certainly translate that way, i.e. something merely has the potential to be so and so. My question, however, is about an implication of "potentially" when it is used in a comparison.
So, when I hear, "X is potentially faster than Y", is it normal, without more information on the subject, for me to assume that X is at least not slower or should I wait for more information before jumping to a conclusion? Does it depend on the situation (e.g. heard in a conversation vs read in a technical article)?

A: No. A potential state can be quite remote and independent from a current state.

A: No. "is potentially faster" makes a restricting statement on the speed, namely that it "is [not [definitely [not faster]]]". In other words, it is possible that it is faster.
No further restrictions to the speed are made. Thus, it might or might not have the same or a lower speed.

A: No, not at all. A Ford Edsel is potentially faster than a Ferrari, if the Ferrari's gearbox is blown.
'potentially' is a weasel-word up there with 'theoretically' or 'hypothetically'. Especially beware when wielded by marketing people.

A: A lot of great answers but I like simple answers so I just wanted to say that "potentially faster" is not mutually exclusive with "potentially slower"

A: No. The implication I get from "X is potentially faster than Y" is either:

*

*In some circumstances we know about (for example, in the circumstance that the code is optimized for both X and Y), X is faster. In other circumstances we know about, it is the same speed, or slower.

*We don't know in which circumstances X is faster; for any particular case, it could be faster, or it could be the same speed or slower.

In neither case is there an implication that X is never slower than Y.

A: No. The words potential and potentially are used with overlapping but possibly contradictory meanings (bolding mine):
potential  adj.

*

*Capable of being but not yet in existence; latent or undeveloped: a potential problem; a substance with many potential uses.

[AHDEL]
...........
Adv.    1.  potentially - with a possibility of becoming actual; "he is potentially dangerous"; "potentially useful"
[Based on WordNet 3.0, Farlex clipart collection. © 2003-2012 Princeton University, Farlex Inc.] [same link]
So 'we know it is possible to develop it' vs 'it may be possible to develop it'.
The speaker needs to be encouraged to estimate the probability X will be faster than Y by 2020 say.
The only logical thing to infer (assuming the speaker is not being totally disingenuous, and is not misinformed) is that, at the moment, X is not faster than Y. It could well be slower.

A: In an engineering context, "is potentially faster" would suggest that something is likely to be faster, but by an amount that may or may not be significant.  It does not imply certainty that the thing will not be slower, but does imply a belief that it is unlikely to be significantly slower.
In things like computer science, there are many situations where performing an operation on a some number of objects will take a certain amount of time to set up the operation and then a certain amount of time per object.  Often a willingness to accept a longer set-up time will allow one to reduce the per-object time [which may be helpful when processing many objects, and counter-productive when processing a small number].  To my ear, "Is potentially faster" might typically be used to describe a change that slightly increases setup time and reduces per-item time; the reduction in per-object time might or might not be sufficient to make up for the increased setup time, but even if it doesn't make up for the setup time the shortfall won't generally be significant.

A: I agree with all the posts here, but I also think it's reasonable to infer that the speaker intends you to believe that X will not be slower than Y.
Lawyers would argue that the statement is without meaning.  While X has the potential to be faster than Y, it may also have potential to be a marshmallow.  There is no reliable literal interpretation.  The spirit of the statement however, is that, while X is not necessarily faster than Y, it certainly is not slower than Y.

A: "X is potentially faster than Y"
This statement, alone, is meaningless.
What logical inference can be drawn from such a barren premise?
The end. Why all the cud-chewimg over such a lightweight topic? Save your strength...
dbmllc
a:a


text:
Q: When can I safely use the "=r" register operand constraint? Consider the following code:
#include <stdio.h>

void main() {
    uint32_t num = 2;

    __asm__ __volatile__ ("CPUID");
    __asm__ __volatile__ ("movl $1, %%ecx":);
    __asm__ __volatile__ ("andl $0, %%ecx": "=r"(num));

    printf("%i\n", num);
}

My initial expectation was that this code would print 0, and it does if I comment out the CPUID line, but as-is it was giving me garbage.  After some trial, error, and research I realized that I was getting the value of a random register.  Apparently GCC doesn't assume that I want the result of the statement being executed.
The problem is that I've seen (other people's) code that relies on that statement properly getting the result of the AND, regardless of what is going on with the other registers.  Obviously such code is broken, given my observations, and the "=r" should be replaced with "=c".
My question is, can we ever rely on the "=r" constraint behaving consistently or according to the obvious expectation?  Or is GCC's implementation too opaque/weird/other and it's best just to avoid it in every situation?

A: In order to use the =r output specifier you need to give gcc the freedom to pick the register that it wants to use.  You do that by specifying the inputs and outputs generically with %0 for the output and the inputs starting with %1 for the first input.
In your case you are saying that num can be in a register.  But there is nothing in the asm instruction that uses the output register.  So gcc will essentially ignore this.
The reason that you are getting a different value if you comment or don't comment the CPUID instruction is that CPUID can write to eax,ebx,ecx, and edx.  I tried your example on my system and got 0 as the result in both cases.  But I noticed that the assembly that is generated is printing the value of eax.  So I guess when I ran this program CPUID was writing 0 to eax.
If you did want to use the =r constraint you would need to do something like this:
  asm("CPUID \n\t"
      "movl $1, %0 \n\t"
      "andl $0, %0 \n\t"
      :"=r"(num) );

Otherwise if your asm code specifically mentions a register then you will need to specify it in the constraint list.  In your example that means using =c.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trouble emitting information on clientside with socket.io I am using express.js, mongoose, jquery and socket.io
I am trying to pass the object "allFightScores" to the socket on clientside. Here is where I am requesting information from mongoose in my routes/index.js:
var models = require('../models/index.js');
var passport = require('passport');
var crawl = require('../crawler.js');
var flash = require('connect-flash');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

exports.submit_scores = function(req, res){

  var scored_fight = new models.UserScore({
    "f1": req.body.f1,
    "f2": req.body.f2,
    "f1_roundScores": req.body.f1_roundScores,
    "f2_roundScores": req.body.f2_roundScores,
    "f1_score": req.body.f1_score,
    "f2_score": req.body.f2_score,
    "user_email": req.body.user_email
  });

  models.UserScore.find({
    "f1": scored_fight.f1,
    "f2": scored_fight.f2,
    "f1_score": scored_fight.f1_score,
    "f2_score": scored_fight.f2_score,
    "user_email": scored_fight.user_email
  }, function(err, data){
    if (data.length === 0){
      scored_fight.save(function(err, user_fight){
        if (err) {
          return "error";
        }
        else {
          models.UserScore.find({"f1": user_fight.f1, "f2": user_fight.f2}, function(err, allFightScores){
            console.log("from index-routes " +allFightScores);
            io.sockets.emit('show scores', allFightScores)
          })
        }
      })
      //put a callback on the user_scored_fight data, also emit that data with the average scores;
      res.json(scored_fight);
    }
    else if (data[0].f1 === scored_fight.f1 && data[0].f2 === scored_fight.f2 && data[0].user_email === scored_fight.user_email) {
      res.json(200);
      console.log("data already judged.");
    }
  })
}

Here is where I am catching the data on my clientside (public/javascripts/script.js):
jQuery(function($){
  socket = io.connect();

  var $group_f1_score = $('#gf1_score');
  var $group_f2_score = $('#gf2_score');

  socket.on('show scores', function(mongooseData){
    console.log("mongooseData from scripts " + mongooseData)

    $group_f1_score.empty();
    $group_f2_score.empty();

  //sum fighter scores for all user submissions
    var f1_sumScore = 0;
    var f2_sumScore = 0;
    for (var i = 0; i < mongooseData.length; i++){
      f1_sumScore += mongooseData[i].f1_score;
      f2_sumScore += mongooseData[i].f2_score;
    }
    //get the simple average
    var f1_avgScore = f1_sumScore/mongooseData.length;
    var f2_avgScore = f2_sumScore/mongooseData.length;

    $group_f1_score.append(f1_avgScore);
    $group_f2_score.append(f2_avgScore);
  })
})

I am not sure why the data is not emitting to my clientside and am out of ideas. Am I querying the data and passing it in the callback correctly?

A: I can't see this in your code:
server.listen(port);


text:
Q: Salesforce APEX Test Class for Simple Trigger I've been going nuts over this.  Nothing in my IF loop is firing through my test class and I cannot figure out why.  I have done a lot of reading online and it appears that I am doing things correctly but it still hasn't solved my code coverage.  This is the last line that runs:
If (isWithin == True){
after that I can't get anything to run within that IF loop, I have reversed the logic and it still doesn't run.  I feel like I will kick myself when someone points it out but here is my code:
trigger caseCreatedDurringBusinessHours on Case (after insert) {

//Create list and map for cases
List<case> casesToUpdate = new List<case>();
Map<Id, case> caseMap = new Map<Id, case>();

// Get the default business hours
BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];

// Create Datetime on for now in the local timezone.
    Datetime targetTime =System.now();

// Find whether the time now is within the default business hours
Boolean isWithin;
    if ( Test.isRunningTest() ){
        Boolean isWithin = True;
    }
    else{
        Boolean isWithin = BusinessHours.isWithin(bh.id, targetTime);
    }

// Update cases being inserted if during business hours
If (isWithin == True){

    // Add cases to map if not null
    For(case newcase : trigger.new) {
        if(newcase.id != null){
            caseMap.put(newcase.Id, newcase);
        }
    }

    // Check that cases are in the map before SOQL query and update
    If(caseMap.size() > 0){

        // Query cases
        casesToUpdate = [SELECT Id, Created_During_Business_Hours__c FROM case WHERE Id IN: caseMap.keySet()];

        // Assign new value for checkbox field
        for (case c: casesToUpdate){
                c.Created_During_Business_Hours__c = TRUE;
        }

        // if the list of cases isnt empty, update them
        if (casesToUpdate.size() > 0)
        {
            update casesToUpdate;
        }

    }

}

}
and here is my test class:
@isTest
private class BusinessHoursTest {

@isTest static void createCaseNotInBusinessHours() {
    case c = new case();
    c.subject = 'Test Subject';
    insert c;

}

}

A: I think you can just copy the main logic to the apex class and just call the method of apex class from the apex trigger.
So it will make it more easy to write the test class.
Let me know if you need more help in this.

A: I'm sure you've figured this out by now but this block of code is re-defining the isWithin variable inside of the if/else blocks:
Boolean isWithin;

if (Test.isRunningTest()) {
    Boolean isWithin = True;
} else {
    Boolean isWithin = BusinessHours.isWithin(bh.id, targetTime);
}

That needs to be:
Boolean isWithin;

if (Test.isRunningTest()) {
    isWithin = True;
} else {
    isWithin = BusinessHours.isWithin(bh.id, targetTime);
}

Or rather a ternary operator for the cleanest code:
Boolean isWithin = !Test.isRunningTest() ? BusinessHours.isWithin(bh.id, targetTime) : true;


text:
Q: How to authenticate user who will be accessing my website hosted on bluemix via facebook login I did purchase a domain from bigrock and hosted it on bluemix & have used node.js bolierplate + mongodb as a service. It's hosted fine,but now I need to autheticate user via facebook.I searched on google and found that we have facebook API for this, but I am not sure how to use it on domain hosted on bluemix.Can someone please provide me any reference to use this?Currently i dont see any option to use fb api on it...
thanks in advance.

A: Probably you should use Single Sign On Service provided on bluemix dashboard to authenticate user of fb.
You can follow below link to sort out this issue:
http://heidloff.net/nh/home.nsf/article.xsp?id=11.12.2014081049NHEAFB.htm

A: You will need to add single sign on service as which is provided by bluemix as service binding to get user authentication via facebook.

A: You need to try single sign on authentication provided by bluemix.
Below is the getting started link with this:
https://www.ng.bluemix.net/docs/#services/SingleSignOn/index.html#sso_gettingstarted
You can easily implement fb login using this option.


text:
Q: R cli progress bar within purrr::map I need to present a progress bar that show the progress of a purrr::pmap.
I use the cli package for user facing information generally, and there is a progress bar in there that seems proficient. However, I cannot get access to a created progress bar inside of another function.
library(cli)
library(purrr)

a <- 1:1000
p <- cli::cli_progress_bar(total = length(a))
te <- function(x){
  cli::cli_progress_update(id=p)
  return(1/x)
}

cli_progress_done(id=p)

a |> purrr::map(te)

It seems that the id argument is not used? Is there a way to access the progress bar inside of the inner function so that I can update the progress?
Thanks!
Fredrik

A: You could use the  .progress argument (its based on cli) in purrr::map():
a <- 1:1000
map(a, function(x){Sys.sleep(1/100); (1/x)}, .progress = list(
  type = "iterator",
  format = "Calculating {cli::pb_bar} {cli::pb_percent}",
  clear = TRUE))


text:
Q: pandas rolling function with Lamdba I was working on the older pandas 0.24.0 version where I had code:
df["A"] = df['B'].rolling(window=2).apply(lambda x: x[0] - x[1])

However the pandas version was upgraded to 1.1.0, which causes this code to not work.
I tried using different variations of rolling function with expanding as well.
Can someone help write the above line of code to work in pandas 1.1.0?
Thanks

A: This is more like shift
df['A'] = df['B'] - df['B'].shift()


text:
Q: ForAll Loop breaks inline images of email in Lotus Notes I do have a Lotus Notes email containing inline images. When I run the following lines of code which simply changes the subject of the email the inline images is lost.
Sub Initialize

Dim ns As New NotesSession
Dim nc As NotesDocumentCollection
Dim nd As NotesDocument

Set nc = ns.Currentdatabase.Unprocesseddocuments()
Set nd = nc.GetFirstDocument()

    ForAll Items In nd.Items

    End ForAll

Call nd.Replaceitemvalue("Subject", "Forall")
Call nd.Save(True, False)

End Sub

The problem is caused by the ForAll loop which actually doesn't do anything. If the loop is commented out the inline images still remain on the email.

I'm hoping any of you guys has an idea or advise how to solve this issue.
Cheers,
Martin

A: Your message body is probably being converted from Notes rich text to MIME when the item is accessed and then being re-saved, with a loss of fidelity.
Try setting ns.ConvertMIME = false at the beginning of your code.


text:
Q: How do I use data from the params array in Ruby on Rails 4? I have a form that passes several numbers to a method called calculate.  I need use those numbers to run through an equation and produce a result.
params.inspect produces the following output:

{"utf8"=>"✓", "authenticity_token"=>"Mi7YZLMPbbYXozIE/XkC53Qhpck+kCihnp0sLuPSwEs=",     "braidcalc"=>{"braider_id"=>"6", "number_of_carriers"=>"24", "carrier_speed"=>"90", "capstan_diameter"=>"24", "core_diameter"=>"1", "wire_diameter"=>"1", "wire_material"=>"copper"}, "commit"=>"Run Calculation", "controller"=>"start", "action"=>"calculate"}

I can't seem to get the syntax right.  I know this example is far from correct syntax, but it should communicate what I'm trying to accomplish:
def calculate (number_of_carriers, carrier_speed, capstan_diameter, core_diameter, wire_diameter)
  result = <calculation using numbers from params>
  return result
end

I'm very new to Ruby on Rails and I'm translating an old application from Visual Basic to learn it.

A: In the controller, you can do:
braidcalc = params[:braidcalc]
result = calculate(braidcalc[:number_of_carriers], braidcalc[:carrier_speed], braidcalc[:capstan_diameter], braidcalc[:core_diameter], braidclac[:wire_diameter])

in your method:
def calculate (number_of_carriers, carrier_speed, capstan_diameter, core_diameter, wire_diameter)
  result = number_of_carrier.to_i + carrier_speed.to_i # or whatever
  return result
end

A: Assuming that calculate method is defined in the same controller then in this case you don't need to pass params as they are readily available and accessible within the controller.
Here is how calculate method should look:
def calculate
  result = params[:braidcalc][:number_of_carriers].to_i + params[:braidcalc][:carrier_speed].to_i   ## perform calculations as per your requirement
  return result
end

You call it from any other action from the same controller using:
def action_name
    result = calculate
    ....
end


text:
Q: [odoo10]How to save the record while odoo warning is happend? In my custom module I added the
application_no = fields.Char(string="Application Number")

_sql_constraints = [
 ('application_no_unique',
 'UNIQUE(application_no)',
 "Application Number already exist.Please specify another number or make sure the application number is correct"),

]
and I use sql constraint to shows warning.
It works correctly, When we entered duplicate application number it shows the warning and access to saving the record is prevented
Question

How to save the record while warning happens??
note

I think SQL constraint is not suited for this.
is any other method for this functionality?

A: I think it might help you to use an onchange method :
@api.onchange('your_field')
def your_onchange(self):
    count=self.search_count([('your_field','=',self.your_field)])
    return {
        'warning': {'title': _('Warning'), 'message': _('Warning message'),},
         }

This will show you the message and you can save without problems. I hope this help you.


text:
Q: Symfony TinyMCE Implementation I have a small issue implementing TinyMCE into a Symfony project.   I get the text editor to come up and save rich text to a database field.   But when I go to "echo" it on a page, I get all the HTML tags instead of the rich text itself.  Is there a special way that I need to "echo" this so that it parses the html?  I also want it so that when people manually type in html tags, that they are displayed as regular text (to avoid people people adding hyperlinks and other unwanted things to their posts).  Here is what displays:

Test

Bold Test

Underline Text

Instead of this:
Test Bold Test Underline Text

A: Symfony2 uses output escaping for security. You can read about it here: http://symfony.com/doc/current/book/templating.html#output-escaping
To echo a variable without escaping it you can do this:
{{ article.body|raw }}

In order to clean up and restrict which tags can be used you will want to use HTMLPurifier which has a bundle here: https://github.com/Exercise/HTMLPurifierBundle
For Symfony 1.4
Symfony 1.4 has similar output escaping. You can get the raw data with:
$sf_data->getRaw('varName');

or if it's a method on an object you can add ESC_RAW as a parameter to the method call (warning: symfony will do some magic here)
$myObject->getMessage(ESC_RAW);

more on 1.4 output escaping here


text:
Q: Instagram Subscription for Edited posts I created an Instagram subscription https://www.instagram.com/developer/subscriptions/
My callback is hit every time a user creates a NEW post. Is there a way to know if a post has been EDITED? It doesn't look like this functionality is supported on the Instagram developer site and I cannot find a solid answer to this problem.

A: There is no way to be notified when a post has been edited.  You'd have to store the post when you're first notified, and then poll it to check for changes (not recommended).


text:
Q: How to read the csv files from Azure Blob Storage in Java with folder structure as 'dir1 / dir2 / dir3 / 20210301-20210331'? I have scheduled an export in my azure blob storage account, it's a monhtly run which creates a csv file under folder like dir1 / dir2 / dir3 / StartDateOfMonth-EndDateOfMonth.
I have below things to do.
1- I want to read this file in java without downloading it.
2 - Want to read parallelly using spring batch master-worker pattern.
Issue facing:-
1- I am not getting absolute path using below line
CloudAppendBlob cloudAppendBlob=  container.getAppendBlobReference("blob_file_name");

log.info("cloudAppendBlob.getUri().getPath() = {}",cloudAppendBlob.getUri().getPath());

2- If anyone helps me to how to do it in Spring Batch master-worker pattern, it would be very helpful for me. [ Normal Spring Batch master-worker pattern I know for a CSV  to read it file from local path ]

A:
1- I want to read this file in java without downloading it.

You can use one of the file item readers (flat file, xml file, json file, etc) provided by Spring Batch and configure it with a org.springframework.core.io.UrlResource. Here is a quick example:
UrlResource resource = new UrlResource("remote/url/to/your/file");
FlatFileItemReader<String> itemReader = new FlatFileItemReaderBuilder<String>()
   .resource(resource)
   // set other properties
   .build();

2 - Want to read parallelly using spring batch master-worker pattern.

You can use the remote partitioning technique provided by Spring Batch where each file is processed in a partition (ie a worker per file). Spring Batch provides the MultiResourcePartitioner that was specifically designed for that. You can find more details in the Partitioning section and a complete example here.

A: I have found a solution for downloading the .csv files from Azure Blob Storage in Java with folder structure as 'dir1 / dir2 / dir3 / StartDateOfMonth-EndDateOfMonth'
@Override
        public List listBlobs(String containerName) {
                List uris = new ArrayList<>();
                String fileName=null;
                try {
                        CloudBlobContainer container = cloudBlobClient.getContainerReference(containerName);
                        Iterable<ListBlobItem> blobs = container.listBlobs("$Directory", true); //for $Directory please find screenshot I have given below. this is the name that you provide during the creation of Export in your Azure Storage account
                        BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(environment.getProperty("azure.storage.ConnectionString")).buildClient();

                        BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName);

                        FileOutputStream fout = null;

                        for (ListBlobItem fileBlob : blobs) {
                                log.info("fileBlob instanceof CloudBlob = {}",fileBlob instanceof CloudBlob);
                                if (fileBlob instanceof CloudBlob) {
                                        CloudBlob cloudBlob = (CloudBlob) fileBlob;
                                        uris.add(cloudBlob.getName());
                                        log.info("File Name is = {}", cloudBlob.getName());
                                        BlobClient blobClient = containerClient.getBlobClient(cloudBlob.getName());
                                        System.out.println(blobClient.getBlobUrl());
                                        System.out.println(blobClient.getBlobUrl().trim());
                                        if (blobClient.exists()) {
                                                Path p = Paths.get(cloudBlob.getName());
                                                String file = p.getFileName().toString();
                                                String directory = p.getParent().toString();
                                                log.info("Downloading Blob File = {} from Directory {}",file,directory);

                                                File dir = new File("$LOCAL_PATH"+directory);

                                                dir.mkdirs();
                                                fout = new FileOutputStream("$LOCAL_PATH" + cloudBlob.getName());
                                                blobClient.download(fout);

                                                CloudAppendBlob cloudAppendBlob=  container.getAppendBlobReference(cloudBlob.getName());
                                                uris.add(cloudAppendBlob.getUri().toURL());
                                                log.info("cloudAppendBlob.getUri().getPath() = {}",cloudAppendBlob.getUri().toURL());

                                        }
                                }
                        }

                        for (ListBlobItem blobItem : container.listBlobs()) {
                                uris.add(blobItem.getUri().toURL());
                                //System.out.println("blobItem.getUri().getPath()= "+blobItem.getUri().getPath());
                        }

                } catch (StorageException e) {
                        e.printStackTrace();
                } catch (URISyntaxException e) {
                        e.printStackTrace();
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }

                return uris;
        }

This code will download all the files from all sub-directories, to download from the specific directory of the month, you can add a check for date matching for the directory name.


text: Q: Router in Extjs 5.1 I want to access My Extjs application internal url from other Application Hyperlink click which redirect to my application. Someone told me to use router is router. Is this router safe from security point of view?


text:
Q: How to do correlation for web_custom_request body My web_custom_Request Body:
"Body=AJAXREQUEST=_viewRoot&uniqueToken=1&primaryDependentListId=dataForm%3Awarehouse&dataForm%3Awarehouse=2010&dataForm%3AbussinessUnit=1&dependantId=&RegionID=2010&dataForm%3AfltrListFltrId%3AfieldName=&dataForm%3AfltrListFltrId%3AfilterName=FL_venkat&dataForm%3AfltrListFltrId%3Aowner=venkat&dataForm%3AfltrListFltrId%3AobjectType=FL_FILTER&dataForm%3AfltrListFltrId%3AfilterObjectType=&dataForm%3AfltrListFltrId%3Afield0value1=&dataForm%3AfltrListFltrId%3Afield0=FILTER.FILTER_NAME&"
        "dataForm%3AfltrListFltrId%3Afield0operator=&dataForm%3AfltrListFltrId%3Afield1value1=&dataForm%3AfltrListFltrId%3Afield1=FILTER.IS_DEFAULT&dataForm%3AfltrListFltrId%3Afield1operator=&dataForm%3AfltrListFltrId%3Afield2value1=&dataForm%3AfltrListFltrId%3Afield2=FILTER.IS_PRIVATE&dataForm%3AfltrListFltrId%3Afield2operator=&dataForm%3AfltrListFltrId%3Afield3value1=&dataForm%3AfltrListFltrId%3Afield3=FILTER.OWNER&dataForm%3AfltrListFltrId%3Afield3operator=&dataForm%3AfltrListFltrId%3Afield4value1=&"
        "dataForm%3AfltrListFltrId%3Afield4=FILTER.IS_DELETED&dataForm%3AfltrListFltrId%3Afield4operator=&dataForm%3AfltrListFltrId%3AfltrCondition=&dataForm%3AfltrListFltrId%3AfltrCrtSel=&stackId=Stack0&stackId=Stack0&clickedidhdn=101&ItemMaskComp_dependantId=&ItemMaskComp_returnId=&defaultBU=1&dataForm%3AItemLookup_selectOneMenu=-1&dataForm%3AisFind=&findHiddenParam=&dataForm%3AItemLookup_PrimaryAliasText=&dataForm%3AItemLookup_PrimaryAliasTextds=&dataForm%3AItemLookup_PrimaryXREF_Textds=&itemName=&"
        "dataForm%3AItem_LookUP_ItemObjectId=&dataForm%3AownerUserId1=&userSetName=&dataForm%3AtaskHdrIdOut=null&dataForm%3AisHeaderDetail=Header&dataForm%3AidInptPrintRendere=false&taskCriteriaName=&dataForm%3AtaskCreationCriteria1=&dataForm%3AallocInvnDtlId1=&pgBrkSetName=&docIdSetName=&taskIdSetName=&dataForm%3AdocIdValue=&dataForm%3AtaskIdValue1=&dataForm%3AviewTaskValue1=&dataForm%3AviewTaskTemp1=&dataForm%3AmenuIdforDisable="
        "rm_PrintTaskLabel_167271477_menuItem%2CdataForm%3Arm_167271477_menuItemBtn%2Crm_PrintTaskLabel_167271477_rCMItem%2CrmButton_1PrintTaskLabel1_167271477&currentInvnNeedType=&dataForm%3AtranName=TaskListReport&targetLink=&dataForm%3AprimaryKeys=&dataForm%3Alview%3AfilterId%3AradioSelect=quick&dataForm%3Alview%3AfilterId%3A_fltrExpColTxt=DONE&dataForm%3Alview%3AfilterId%3A_filtrExpColState=collapsed&dataForm%3Alview%3AfilterId%3Afield1=TaskID&dataForm%3Alview%3AfilterId%3Afield1operator=%3D&"
        "dataForm%3Alview%3AfilterId%3AsubObject1=&dataForm%3Alview%3AfilterId%3Afield1value1ecId=&dataForm%3Alview%3AfilterId%3Afield1value1=2748136&dataForm%3Alview%3AfilterId%3Afield2=TaskType&dataForm%3Alview%3AfilterId%3Afield2operator=%3D&dataForm%3Alview%3AfilterId%3AsubObject2=&dataForm%3Alview%3AfilterId%3Afield2value1=&dataForm%3Alview%3AfilterId%3Afield3=HeaderStatus&dataForm%3Alview%3AfilterId%3Afield3operator=%3D&dataForm%3Alview%3AfilterId%3AsubObject3=&"
        "dataForm%3Alview%3AfilterId%3Afield3value1=&dataForm%3Alview%3AfilterId%3Afield6=Item&dataForm%3Alview%3AfilterId%3Afield6operator=DY&dataForm%3Alview%3AfilterId%3AsubObject6=&dataForm%3Alview%3AfilterId%3AitemLookUpId=&dataForm%3Alview%3AfilterId%3Afield8=CreateDateTime&dataForm%3Alview%3AfilterId%3Afield8operator=BT&dataForm%3Alview%3AfilterId%3AsubObject8=&dataForm%3Alview%3AfilterId%3Afield8value1=&dataForm%3Alview%3AfilterId%3Afield8value2=&dataForm%3Alview%3AfilterId%3Afield9=WMOrder&"
        "dataForm%3Alview%3AfilterId%3Afield9operator=%3D&dataForm%3Alview%3AfilterId%3AsubObject9=&dataForm%3Alview%3AfilterId%3Afield9value1ecId=&dataForm%3Alview%3AfilterId%3Afield9value1=&dataForm%3Alview%3AfilterId%3Afield4=WaveNumber&dataForm%3Alview%3AfilterId%3Afield4operator=%3D&dataForm%3Alview%3AfilterId%3AsubObject4=&dataForm%3Alview%3AfilterId%3Afield4value1=&dataForm%3Alview%3AfilterId%3Afield5=Priority&dataForm%3Alview%3AfilterId%3Afield5operator=%3D&dataForm%3Alview%3AfilterId%3AsubObject5="
        "&dataForm%3Alview%3AfilterId%3Afield5value1=&dataForm%3Alview%3AfilterId%3Afield20=TaskGenerationReferenceCode&dataForm%3Alview%3AfilterId%3Afield20operator=%3D&dataForm%3Alview%3AfilterId%3AsubObject20=&dataForm%3Alview%3AfilterId%3Afield20value1=&dataForm%3Alview%3AfilterId%3Afield21=TaskGenerationReferenceNumber&dataForm%3Alview%3AfilterId%3Afield21operator=%3D&dataForm%3Alview%3AfilterId%3AsubObject21=&dataForm%3Alview%3AfilterId%3Afield21value1ecId=&dataForm%3Alview%3AfilterId%3Afield21value1"
        "=&dataForm%3Alview%3AfilterId%3Afield22=TaskCompletionReferenceCode&dataForm%3Alview%3AfilterId%3Afield22operator=%3D&dataForm%3Alview%3AfilterId%3AsubObject22=&dataForm%3Alview%3AfilterId%3Afield22value1=&dataForm%3Alview%3AfilterId%3Afield23=TaskCompletionReferenceNumber&dataForm%3Alview%3AfilterId%3Afield23operator=%3D&dataForm%3Alview%3AfilterId%3AsubObject23=&dataForm%3Alview%3AfilterId%3Afield23value1ecId=&dataForm%3Alview%3AfilterId%3Afield23value1=&dataForm%3Alview%3AfilterId%3Afield28="
        "DocumentID&dataForm%3Alview%3AfilterId%3Afield28operator=%3D&dataForm%3Alview%3AfilterId%3AsubObject28=&dataForm%3Alview%3AfilterId%3Afield28value1ecId=&dataForm%3Alview%3AfilterId%3Afield28value1=&dataForm%3Alview%3AfilterId%3AcurrentAppliedFilterId=-1&dataForm%3Alview%3AfilterId%3AfilterId_quickFilterGroupButton_mainButtonCategory=-1&dataForm%3Alview%3AfilterId%3AfilterId_quickFilterGroupButton_mainButtonIndex=-1&dataForm%3Alview%3AfilterId%3AfilterId_quickFilterGroupButton_changeDefault=false&"
        "dataForm%3Alview%3AfilterId%3AfilterId_savedFilterGroupButton_mainButtonCategory=-1&dataForm%3Alview%3AfilterId%3AfilterId_savedFilterGroupButton_mainButtonIndex=-1&dataForm%3Alview%3AfilterId%3AfilterId_savedFilterGroupButton_changeDefault=false&dataForm%3Alview%3AfilterId%3AdummyToGetPrefix=&dataForm%3Alview%3AfilterId%3Aowner=venkat&clickedid=101&fotype=WM_TASK_LIST_INQ&tranId=29&customParams%20=tranId%3D29%26fotype%3DWM_TASK_LIST_INQ%26fromLeftNav%3Dtrue%26clickedid%3D101%26stackId%3DStack0&"
        "queryPersistParameter=%26tranId%3D29%26fotype%3DWM_TASK_LIST_INQ%26clickedid%3D101%26stackId%3DStack0&dataForm%3Alview%3AfilterId%3AobjectType=WM_TASK_LIST_INQ&isJSF=true&filterScreenType=ON_SCREEN&dataForm%3Alview%3AdataTable%3Apager%3ApageInput=&dataForm%3Alview%3AdataTable%3ApagerBoxValue=&dataForm%3Alview%3AdataTable%3AisPaginationEvent=&dataForm%3Alview%3AdataTable%3ApagerAction=&dataForm%3Alview%3AdataTable_deleteHidden=&dataForm%3Alview%3AdataTable_selectedRows=%23%3A%23&"
        "dataForm%3Alview%3AdataTable_selectedRows=&dataForm%3Alview%3AdataTable%3AisSortButtonClick=taskHdr.taskId&dataForm%3Alview%3AdataTable%3AsortDir=asc&dataForm%3Alview%3AdataTable%3AcolCount=&dataForm%3Alview%3AdataTable%3AtableClicked=&dataForm%3Alview%3AdataTable%3AtableResized=false&dataForm%3Alview%3AdataTable%3A0%3APK_0=DUMMYROW&dataForm%3Alview%3AdataTable%3A0%3AstatCodeVal=&dataForm%3Alview%3AdataTable%3A0%3AstatCodeDescVal=&dataForm%3Alview%3AdataTable%3A0%3AtaskHeaderIdValue=&"

A: Build your own string to go inside of the web_custom_request().   This is a common problem where you may have a variable number of name|value pairs going back from one iteration to the next.   This leverages heavily your foundation (non performance testing tool skills ) in the string manipulation skills in programming language of your tool, in this case LoadRunner and 'C.'

A: This request body is URL-encoded. In order to transform it to a more readable form, you may try a DFE (Data Format Extension) approach:

*

*Enable DFE and create a DFE chain with Url Encoding DFE.

*Apply this chain to the request body, refer to this page.

This would decode it to XML form. Then you'd be able to correlate data in the request.
Also this looks like a common POST request so I suspect that you are possibly using URL-based script recording level with custom requests. If it is so, you should consider switching to HTML-based script and re-generating the script. This would convert this custom request to a higher-level call, e.g., web_submit_form(). Check this and this for more information, the last link requires an HPE Passport account.


text:
Q: Implement Semantic Zoom without listview, Gridview? I am trying to implement Semantic Zoom control but not with listview, Gridview or grouping. My UI has following XAML
ZoomIn
<!--Your ZoomIn view here-->
                <ScrollViewer>
                    <StackPanel>
                        <Grid x:Name="Item1" />
                        <Grid x:Name="Item2" />
                        <Grid x:Name="Item3" />
                        <Grid x:Name="Item4" />
                        <Grid x:Name="Item5" />
                    </StackPanel>
                </ScrollViewer>

ZoomOut
         <!--Your ZoomOut view here-->
            <ScrollViewer>
                <StackPanel>
                    <Image x:Name="ImageItem1" />
                    <Image x:Name="ImageItem2" />
                    <Image x:Name="ImageItem3" />
                    <Image x:Name="ImageItem4" />
                    <Image x:Name="ImageItem5" />
                </StackPanel>
            </ScrollViewer>

On clicking on an image in Zoomout it should take to the corresponding to Grid in Zoomin view.
How can i achieve this? Till now I have implemented Semantic zoom using listview, gridview and grouping.

A: It's sloppy to use a control like SemanticZoom for controls it is not intended to use.
Having said that, you can do this:
<SemanticZoom>
    <SemanticZoom.ZoomedInView>
        <GridView>
            <GridView.Header>
                <StackPanel>
                    <TextBlock>One</TextBlock>
                    <TextBlock>Two</TextBlock>
                    <TextBlock>Three</TextBlock>
                </StackPanel>
            </GridView.Header>
        </GridView>
    </SemanticZoom.ZoomedInView>
    <SemanticZoom.ZoomedOutView>
        <GridView>
            <GridView.Header>
                <StackPanel>
                    <TextBlock>Four</TextBlock>
                    <TextBlock>Five</TextBlock>
                    <TextBlock>Six</TextBlock>
                </StackPanel>
            </GridView.Header>
        </GridView>
    </SemanticZoom.ZoomedOutView>
</SemanticZoom>

Best of luck!


text:
Q: How do I download Ubuntu One files to my mac? I have Ubuntu One files on my phone uploaded to the website because I own a mac. I'd like to download them all to said mac, how can I do that?
Do I really have to download every single file one by one?

A: I'm currently maintaining an open source Ubuntu One client for OS X. Check it out on Github.

A: File synchronization on Apple products are not yet supported, but "only" Ubuntu, Windows and Android. The client is both free software and mostly platform agnostic, so it should be relatively easy to add support for OS X as well, but everything takes time.
The web interface doesn't support downloading folders (yet). In other words; yes, if you're using OS X you'll currently have to download the files one at a time -- unless you port the client yourself, or maybe you can find a third-party port.

A: I could not get the Uno client to work so I wrote this python script which lets you download/update files on any platform: https://github.com/ddimmich/unbuntuone-python
Instructions are provided on github.

A: We have released as of today a Mac OS X beta version which you can find here: http://voices.canonical.com/ubuntuone/2012/10/11/ubuntu-one-for-mac-os-x-now-in-beta/


text:
Q: Why ALL PRIVILEGES ON `db`.* gives access to all databases? I've installed Ubuntu 12.10(quantal) and mysql-server-5.5.
When I execute:
drop user ''@'localhost';
create database `redmine`;
grant all on `redmine`.* to 'redmine'@'localhost';

User redmine@localhost can access not only redmine database, but also other databases.
How do I prevent him from accessing any database except redmine?
P.S.
I can't reproduce this on other distributions. What is a proper behaviour? Is this a bug?
UPDATE1:
mysql> show grants;
+--------------------------------------------------------------+
| Grants for redmine@localhost |
+--------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'redmine'@'localhost' |
| GRANT ALL PRIVILEGES ON `redmine`.* TO 'redmine'@'localhost' |
+--------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> use test;
Database changed
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| x |
+----------------+
1 row in set (0.00 sec)

A: The grants you gave on the redmine database have nothing to do with access to the test database.
The problem is the way mysql was installed. It allows full access to the test database. It is not a bug. I wrote a past post (Question and Answer) on why anybody can access a test database and how to fix it:

*

*MySQL : Why are there "test" entries in mysql.db? (Question)

*MySQL : Why are there "test" entries in mysql.db? (Answer)

In essence, the problem is the table mysql.db. It contains entries that allow everyone and his grandmother to do anything in a test database or any database whose first five characters are test_. Removing those entries with DELETE FROM mysql.db WHERE LEFT(db,4)='test'; will immediately solve your particular problem.
I have other posts on how to thoroughly strip anonymous users from mysql.user and why

*

*Cannot drop anonymous user from mysql.user

*mysqladmin user account not secure?

*MySQL error: Access denied for user 'a'@'localhost' (using password: YES)

*Grant table privileges to a user connecting from any host
Please read these carefully because my past answers will show you things like
SELECT USER(),CURRENT_USER();

This will break down the difference between how you logged in and how mysqld allowed you to login.

A: You can verify by connecting using 'redmine'@'localhost' and see how many databases by executing this query:

Show databases;

Also, you can execute another query to see exactly what are privileges given to 'redmine'@'localhost':

show grants for 'redmine'@'localhost';


text:
Q: how to get the x values from the sorted 'y' array i have a x,y dataset. It looks like this:
 var x = ['Test', 'Test2', 'Test3']
 var y = [0, 80, 20]

First Step I order it descending:
y.sort(function(a,b) {return b - a}))

then this came out:
console.log(y) // var y = [80, 20, 0]

Now my problem is, that I need also the x ordered by the y values (sorry for my English)!!
y: 80 -> x: Test2, y: 20 -> x: Test3, y:0 -> x: Test0

But I don't know how to do that. If I map then it map the x to y values in wrong order. It would be very kind if you can help me.


text:
Q: case when with hsqldb ? how? i am using libreoffice base (new version) with HSQLDB and want to do a query where in a certain column when that column or cell data is not empty i want the resulting cell output to be "X", otherwise it should stay empty. how can i do that with HSQLDB syntax?
i googled but actually could not find anything in this regard.

A: Tested in HSQLDB 1.8.
SELECT B.NAME
FROM "Table1" A
LEFT OUTER JOIN
    (SELECT ID, 'X' AS NAME FROM "Table1") B
ON A.ID = B.ID AND A.NAME <> ''

Table1:
ID NAME
~~ ~~~~
1  George
2  Sally
3

Result:
X
X
(empty)

EDIT:
HSQLDB does have CASE WHEN. Documentation: http://www.hsqldb.org/doc/1.8/guide/ch09.html#N1251E.
SELECT CASE WHEN NAME<>'' THEN 'X' ELSE '' END FROM "Table1"

SELECT CASEWHEN(NAME<>'', 'X','') FROM "Table1"


text:
Q: perform_async not working in sidekiq I'm trying to use sidekiq to process some requests in background (it's integrated with padrino framework).
My expectation was that once the worker got called, the request handler would return immediately the answer to user.
In order to be sure it was working properly I implemented a worker that would print some messages and sleep for some 44s prior to finish it's processing (to simulate a long processing in background).
For my surprise, the request got stuck until the worker had the job finished. Only after that the request handler could return an answer to user.
At first I thought that the sleep function could be the problem, so I replaced the sleep function by a busy while but I have the same behavior: the request handler got hanged until the worker finished its task.
Any idea why is this happening?
You can see the following :
request handler:
get :hardworker, map: '/hardworker' do
  logger.info "I'll call HardWorker"
  HardWorker.perform_async(44)
  logger.info "HardWorker was called"
  return "The job should still be running in background."
end

Sidekiq worker:
class HardWorker
  include Sidekiq::Worker

  def perform(count)

    logger.info "Doing hard work"
    Sidekiq.redis { |c| logger.info "redis location: [#{c.client.location }]" }

    redis_info = Sidekiq.redis { |conn| conn.info }
    logger.info "connected clients: [#{redis_info['connected_clients']}]"

    sleep count

    logger.info "hard work was done"
  end
end

The redis server is running:
ps -ef | grep redis

returns
redis     1232     1  0 16:54 ?        00:00:09 /usr/bin/redis-server 127.0.0.1:6379

as well as sidekiq server:
bundle exec sidekiq -r ./config/boot.rb -v
2015-06-06T20:31:26.207Z 3343 TID-8614g INFO: Booting Sidekiq 3.3.4 with redis options {:url=>"redis://127.0.0.1:6379/0", :concurrency=>25}

Also, from logs I put in the worker we can see that client apparently is connected to redis:
INFO -  redis location: [127.0.0.1:6379]
INFO -  connected clients: [3]

sidekiq version: 3.3.4
redis server: 2.8.4
ruby: 2.1.2p95
Note: I mounted sidekiq web tool on my padrino and it shows 0 for all stats (Processed, Failed, Busy, Enqueued, Retries, Scheduled, Dead) both prior and after the worker has executed.
The sample project can be downloaded from here: https://github.com/plicatibu/sidekiq-problem.git

A: Well I found your bug, in your boot.rb file you have this line:
require 'sidekiq/testing/inline' if RACK_ENV == 'development'

This bit of code, uses Sidekiq's Testing framework which bypasses redis and runs it almost as if it's a ruby class (ie it doesn't ever get queued on redis).  Remove that line and only use it in your test suite (if you need it).
You'll also need to remove that  pid file from your YML file, you don't need that and if you do, it's probably only for production.  My 2cents - remove it.
Once you do that, you're good to go:
Here's your rackup with a get request to /hardworker:
[2015-06-07 07:54:25] INFO  WEBrick 1.3.1
[2015-06-07 07:54:25] INFO  ruby 2.2.2 (2015-04-13) [x86_64-darwin14]
[2015-06-07 07:54:25] INFO  WEBrick::HTTPServer#start: pid=74128 port=9292
   INFO -  I'll call HardWorker
   INFO -  HardWorker was called
  DEBUG -       GET (0.0131s) /hardworker - 200 OK
::1 - - [07/Jun/2015:07:55:32 -0400] "GET /hardworker HTTP/1.1" 200 46 0.0291

Here's sidekiq processing that job in the background:
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
          ss
     sss  sss         ss
     s  sss s   ssss sss   ____  _     _      _    _
     s     sssss ssss     / ___|(_) __| | ___| | _(_) __ _
    s         sss         \___ \| |/ _` |/ _ \ |/ / |/ _` |
    s sssss  s             ___) | | (_| |  __/   <| | (_| |
    ss    s  s            |____/|_|\__,_|\___|_|\_\_|\__, |
    s     s s                                           |_|
          s s
         sss
         sss

   INFO -  Running in ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14]
   INFO -  See LICENSE and the LGPL-3.0 for licensing details.
   INFO -  Upgrade to Sidekiq Pro for more features and support: http://sidekiq.org/pro
   INFO -  Starting processing, hit Ctrl-C to stop
  DEBUG -
   INFO -
   INFO -  Doing hard work
   INFO -  redis location: [127.0.0.1:6379]
   INFO -  connected clients: [3]
   INFO -  hard work was done
   INFO -


text:
Q: Identifying the symmetry of a polar function
What is the purpose of $1+\cos(-\theta) \neq -r$

A: It looks like they check symmetry about the $y$-axis in two different ways:

*

*by verifying if $r(-\theta)=-r(\theta)$;

*by verifying if $r(\pi-\theta)=r(\theta)$.

What is the purpose of $1+\cos(-\theta) \neq -r$

So this refers to the first of the two above.
Side note: where is the argument about the symmetry with respect to the origin? They conclude "therefore not symmetric about the origin" but I would expect something like verifying whether  $r(\theta+\pi) = r(\theta)$ to arrive at that conclusion.


text:
Q: I want to install pyqt5(Python 3.4) on Travis-ci, but it doesn't work I want to install pyqt5 on travis-ci but it doesn't work.
I already tried many ways like pip install pyqt5 and I don't know how to fix this error: "Could not find any downloads that satisfy the requirement sip>=4.19.1 (from pyqt5)"
language: python

python:
  - "3.4"
install:
 - pip install cx_freeze==4.3.3
 - pip install libyaz0
 - pip install sarclib
 - pip install pyqt5

log: https://api.travis-ci.org/v3/job/529770981/log.txt

A: try adding this block to your .travis.yml
addons:
  apt:
    packages:
      - python3-pyqt5


text:
Q: What are the pros and cons of using `select table_name.*`? I've heard that this is the wrong way to write queries in general but I wonder something people say to new users of SQL.
Is it really bad form or just plain lazy?
So, not to solicit too much opinion on this, what are some good reasons for it's use in queries besides not having to type out every field name. Also, do these reasons outweigh the harm in it's use?

A: When using the wildcard * the system has to process what all the column names are for that table, and return them.
Therefore using * is worse for performance than actually typing them all out manually.
The general rule is to avoid using it if you don't have to, and instead specify the columns which you actually require.

A: When your program knows about the structure of your table at compile-time or through configuration, using select * is not a good idea: any change in the structure of your table could break the structure of the results coming back from the query, ultimately causing run-time errors.
However, there are cases when * is indispensable. Specifically, if your program "learns" dynamically of the structure of your tables by reading metadata coming back from a query, using the "all columns" request lets your program pick up changes to your tables dynamically.
It goes without saying that using * for ad-hoc queries in your favorite flavor of SQL Studio/SQLPlus/etc. is very common and convenient.

A: Using select * relies upon the order of columns being preserved.  From a relational point of view the order of columns is irrelevant.  The following two tables are identical when operating upon them:
create table alpha (int id, int value);
create table beta (int value, int id);

The only single thing that is different between them is the order of columns.  The column names & types are identical.  The order of columns should be treated in all cases as an internal implementation detail, and as such should never be programmed to.
There are occasional circumstances, where you just want to select all columns, w/o regard to order.  (For example, data analysis programs might do certain kinds of queries to determine the structure of a table -- but again, the structure is the names/data types of the columns, not their order.
Don't use it.

A: The book SQL Antipatterns covers this topic in depth in the chapter "Implicit Columns".
The most typical use of a wildcard for the fieldnames in a query is when writing an ad-hoc query. It is faster to type '*' than it is to type in each field name that you want returned. Programmer time is fairly expensive, so it makes sense not to worry about the slight performance gain when running an ad-hoc query, where you'll waste more time typing in the names.
However, you still should have some knowledge of the database schema, because waiting for the values from a blob column on a large number of rows can waste a lot of time too, especially if all you wanted was the primary key value.
Using SELECT *, you might be getting good performance on a particular query because it's returning a small result set of maybe a few hundred bytes, however, add a couple of blob fields to the table for some other function, and maybe now the result set is in the millions of bytes, and suddenly your query is slow, even though the data that you actually use is very small. To avoid this problem, name the columns in your query.
If you're using SELECT * just so you automatically have the values of new columns when they're added, you'll still be victim to the above scenario. It's a trade off, which you will have to choose.
It's valid to use SELECT * as long as you have a reason, with the exception that laziness is not a valid reason.


text:
Q: PHP MSSQL use "Where" to select a date range I'm trying to populate a list menu where the selections will either be in the past or the future based on the gamedate.
i want 1 menu to list games that have been played, based on the current date, and 1 menu to list games that have not been played. basically if $gamedate>$daynow or $gamedate<=$daynow
i've looked up examples online but none of my attempts have worked. perhaps i need to know how to convert $gamedate to a unix time stamp but everything i try doesn't work.
I've tried: strtotime, DateTime::, and using "WHERE" and "between" to create a date range
$gamedate is assigned from a MSSQL db and the field is in date format
my thought was to convert $gamedate to the UNIX timestamp and use that to compare to time(). am i correct in thinking this is an integer so using ">" or "<" would work? i'm open to other ways as well.
<?PHP
$daynow=time()

$sql="Select convert(varchar(5), gamedate, 101) AS d, * WHERE gamedate>=$daynow ORDER BY gamedate ASC"
$stmt=sqlsrv_query($conn, $sql);
while ($row=sqlsvr_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
echo"this game has not yet been played";
}
?>

or
<?PHP
$sql="Select convert(varchar(5), gamedate, 101) AS d, * ORDER BY gamedate ASC"
$stmt=sqlsrv_query($conn, $sql);
while ($row=sqlsvr_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$gamedate=$row['gamedate'];
$daynow=time();
if ($gamedate>$daynow){
echo"this game has not yet been played";}
elseif ($gamedate<=$daynow){
echo"this game has been played";}
}
?>

everything i find is how to covert a timestamp to a string
thank you

A: Check this: What is the preferred format to store date/times in a SQL Server database when PHP is your primary language? I think it would be more helpful since that quesiton is related to MSSQL


text:
Q: Force Trigger event listner with button onclick Using below code to make basic audio background music player to play files in a folder. On open and after Play (either button or on scale), it plays a random file in the Music folder. When that file ends, it loads another random file and plays it, then continues to repeat the process.  The Question - Is it possible add a button onclick = (i.e. Next Song) to trigger the "ended" event and trigger the next song when clicked.  I think I need to add a music.stop() also. I'm just trying to force the playing song to end and have the loop load the next song.  It appears that the "ended" event is a read only event and can't be manually changed to a true.

  <button onclick="document.getElementById('player').play()">Play Music</button>
  <button onclick="document.getElementById('player').pause()">Pause Music</button>
  <button onclick="document.getElementById('player').muted=true">Mute</button>
  <button onclick="document.getElementById('player').muted=false">Un-mute</button>
  <button onclick="document.getElementById('player').volume += 0.1">Vol +</button>
  <button onclick="document.getElementById('player').volume -= 0.1">Vol -</button>

A: The easiest way is by assigning the event listener to a variable and then calling that function from your onclick.
var endedListener = function() {
    x=x+1;
    music.src = "Music2/song"+(Math.floor(Math.random()*23))+".mp3";
    music.load();
    music.play();
    };
music.addEventListener("ended", endedListener);

<button onclick="endedListener()">Next</button>

Keep in mind that calling endedListener does not actually stop the audio from playing. It just triggers your own function logic.


text:
Q: Solutions to quintic equation Abel's Theorem shows that there is no general formula that gives the solution to $x^5+Ax^4+Bx^3+Cx^2+Dx+E=0$ with radicals. My math is not sufficient to understand Abel's theorem. Considering motivation from lower degrees where we try to remove terms, e.g. depressing a cubic, does it(or other theorems) say anything about the existence of special case formulas in radicals? For example, $D=0$ or $B=C$. I am less interested in the case $E=0$.

A: By shifting the unknown by $-\dfrac A4$, you deplete the equation and absorb one degree of freedom. So introducing a constraint such as $D=0$ or $B=C$ does not make the equation less general.
$D=0$ is what you get by changing $x\leftrightarrow \dfrac1x$ and depleting.
By resolution of a cubic, you can find a shift the enforces $B=C$.


text:
Q: Why do we usually start programs with public static void main('String[] args')? I understand why public static void main is used, I also know that String[] args creates a 1-D array called args which contains strings. But why must we have this with in the parenthesis?

A: The String[] args is to supply all the arguments that may be delivered to your program from the command line. Say for example you wanted a filepath as a parameter to your main, you can type it with the command line and it will pass that as the first element in the array. It allows you to pass nothing, or many things when running your main.

A: The Java language was specified that the main method must take exactly one parameter of type String[].  It can be named any valid identifier you want; it's only a convention that it's named args.  It can even be String....  Here's the specification, from the JLS, Section 12.1.4:

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:
public static void main(String[] args)

public static void main(String... args)

It could even be
public static void main(String[] zzyzx)

but the parameter must be there.


text:
Q: UIWebview not fetching the linked CSS resource I am trying to load a local html content into uiwebview. I already have the html content ready with me, and i am adding a reference a online css file to the content by the mechanism as shown in the code below. However, the problem i am facing is when i load the webview, there is no styling. Also, I verified in the Charles Proxy, there is no outgoing call for fetching iphone.css file to my base server. Ideally, while loading a html page, uiwebview should get all the referred resources, but for some reason unknown to me, it is not fetching the css file.
Please review and let me know if there is some issue with my code that i am not able to identify here?
NSString* htmlString = @"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <link type=\"text/css\" href=\"http://<base_server>/resources/iphone.css\" /><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />%@";

        UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        NSLog(@"%@",[NSString stringWithFormat:htmlString,entry.body]);
        [webview loadHTMLString:[NSString stringWithFormat:htmlString,entry.body] baseURL:[NSURL URLWithString:@"http://<base_server>/"]];

        [self addSubview:webview];

A: It's hard to tell if there are any typos in the HTML with all of the double quote escaping going on in that string. Why don't you pull the HTML out of the string and into a file, read that file in and place your content in the body. There may be a mistake with the markup in that string. This would allow you to read it easier in a seperate file.
Something like:
NSError *error;
NSStringEncoding encoding;
NSString *htmlFilePath = [[NSBundle mainBundle] pathForResource: @"Sample"
                                                         ofType: @"html"];
NSString *htmlString = [NSString stringWithContentsOfFile:htmlFilePath
                                             usedEncoding:&encoding
                                                    error:&error];

NSString *html = [NSString stringWithFormat:htmlString, entry.body];

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];

[webview loadHTMLString:html baseURL:baseURL];


text:
Q: SUDO asks for "Encryption passphrase" on new setup with LUKS SUDO keeps asking for Encryption passphrase on my latest setup. I'm not sure what encryption the passphrase is for, except that I suspect that it is related to LUKS encryption. Also I noted it doesn't matter which passphrase I enter
The output I get is for instance the following:
rohdef@rohdef-januar ~/g/januar-k8s (main)> sudo true
[sudo] password for rohdef:
Encryption passphrase:

If relevant the setup I used for the disk encryption is How to Dual-Boot Ubuntu 20.04 (or 22.04) and Windows 10 with Encryption with the modifications that I resized an existing Windows rather than installing it after and that I did not re-enable bitlocker.
What is the Encryption passphrase it asks for, and how do I disable it?


text:
Q: Explanation as to why the inverse image of a closed set, under a continuous function, is closed. The fact that the inverse image of a closed set, under a continuous function, is closed seems strange to me. What if the function that maps the sets is given as:
$$f(x)=0$$
This is a continuous function, but no matter what set it maps, the image will be the set $\{0\}$ which is closed no matter what set It mapped. I am obviously wrong since the statement is known to be true, but I am not sure why I am wrong. Can someone explain why my reasoning is flawed?
I thought it might be because the function had to be in terms of the elements in the set. Just a guess?


text:
Q: Baire space which doesn't contain a dense completely metrizable subspace Let us work with separable metrizable spaces.
It's known that if $X$ contains a dense completely metrizable subspace then $X$ is Baire.
Moreover, if we assume that $X$ embeds into any space as a Borel set ($X$ is absolutely Borel), then it contains a dense completely metrizable subspace.
What's an example of a Baire space which doesn't contain a dense completely metrizable subspace?

A: Take a Bernstein set $B$ in the reals, as $B \subseteq \Bbb R$, it's separable metric. The defining property for $B$ is that it intersects $P$ for any uncountable closed subset of the reals, but also $\Bbb R\setminus P$.
There are no constructive examples of such a set, and they are proved to exist by well-ordering the reals and doing a transfinite recursion. If you believe in AC, they do exist.
Then $B$ is a Baire space (not too hard to show, e.g. use Cantor's intersection theorem) but it doesn't contain a completely metrisable subspace (as these always contain Cantor sets, and these cannot be a subset of $B$).
A nasty beast, but they do exist.


text:
Q: Can I use a React element in the message property of yup's createError(...)? The yup documentation specifically states that I should return a string in context.createError({ message: "string here" }). However, I would like to do something like this:
return context.createError({
    message: (

            {suggestions.map((s, i) =>
{s}
)}

    )
});

It does seem to work fine, but I'm unsure if there is some small possibility of this breaking?


text:
Q: Navigation doubts in iphone I have to pass a value from one view-controller to another view-controller,my this code works fine
NSString *localStringtextnote;

-(IBAction)_clickbtnsyncNote:(id)sender
{
localStringtextnote = textVieww.text;
        Googledocmainpage *detailViewController = [[Googledocmainpage alloc] initWithNibName:@"Googledocmainpage" bundle:nil];

        detailViewController.localStringtextnote = localStringtextnote;
        // ...
        // Pass the selected object to the new view controller.

        [self.navigationController pushViewController:detailViewController animated:YES];

        [detailViewController release];

but i want to pass localStringtextnote through this way
Googledocmainpage *aSecondViewController = [[Googledocmainpage alloc] initWithNibName:@"Googledocmainpage" bundle:nil];
    aSecondViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:aSecondViewController animated:YES];
    [self.navigationController pushViewController:aSecondViewController animated:YES];

how to pass a value through the above page rediriction method?i hope u understand my question.thanks in advance.

A: Use  like this
Googledocmainpage *aSecondViewController = [[Googledocmainpage alloc] initWithNibName:@"Googledocmainpage" bundle:nil];

aSecondViewController.localStringtextnote = localStringtextnote;

    aSecondViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:aSecondViewController animated:YES];
   // [self.navigationController pushViewController:aSecondViewController animated:YES];

also why are you using both way (pushing the view and presentModelView , use only one in a time).


text:
Q: Generating new point file based on specified distances and azimuths/angles from previous point in ArcMap? I have a shapefile of multiple points (upwards of 100). I would like to generate a new shapefile with points that are a specified distance and direction away from the previous points. For example, each point has a unique distance and angle/bearing associated with it. I have read into the create features and using the distance/direction tool. However, this is very tedious as I have many points, and will continue to. I have also found the "Bearing Distance to Line" tool and I believe this does exactly what I want it to. however, it generates a line, and not a point.
Is there a way to do it that makes a line, or a way to make new shapefile with only points at the end of each line?

A: There are a few ways to do this using arcpy and numpy (getting the new points is basically a trig problem which is where numpy comes in handy); however, unless you're decently familiar with python already, that would probably take too long to be worth it for that number of points. Therefore, I will suggest a more jury-rigged approach that should work. If you can use the Bearing Distance to Line tool to get a line with the end point you want, then you can use the Feature Vertices to Points tool and select out the points you want and export them to a new feature class.


text:
Q: python function that mimics a web search I need to write a python function that mimics a web search. For example, I have three websites and keywords that correspond to the websites. The function should return the set of all the webpages that all the words appear on. I have turned the webpages and keywords into strings by doing this and creating a set of tuples:
d = {("www.page0.com", {"dog", "cat", "fish"}),("www.page1.com", {"cat", "rat", "frog", "dog"}), ("www.page2.com", {"cat", "rat", "fish", "goat"})}

Now, I need to write a function that creates and returns a dictionary that maps words to pages.  Thus, the keys will be the word strings and the values will be sets of pages where that word appears. So for our example above, 2 of the dictionary entries would be:
"cat": {"www.page0.com", "www.page1.com", "www.page2.com"}
"goat": {"www.page2.com")

I've created the function:
def createPageDict(d):
    return dict((v(x), y) for v in d)
createPageDict(d)

A: You can try the following function:
from collections import defaultdict
def create_dict(d):
    ret = defaultdict(set)
    for site, vals in d:
        for v in vals:
            ret[v].add(site)
    return ret

pages = create_dict(d)
for i, j in pages.items():
    print(i, j)

Gives:
dog {'www.page0.com', 'www.page1.com'}
cat {'www.page0.com', 'www.page2.com', 'www.page1.com'}
fish {'www.page0.com', 'www.page2.com'}
rat {'www.page2.com', 'www.page1.com'}
frog {'www.page1.com'}
goat {'www.page2.com'}

Note that I turned your d into
d = (("www.page0.com", ("dog", "cat", "fish")),("www.page1.com", ("cat", "rat", "frog", "dog")), ("www.page2.com", ("cat", "rat", "fish", "goat")))

because sets are an unhashable type, so your d literal was incorrect.
If you don't want to use defaultdict, you just have to check if the key is in your dictionary before adding to the set:
def create_dict(d):
    ret = {}
    for site, vals in d:
        for v in vals:
            if v in ret:
                ret[v].add(site)
            else:
                ret[v] = {site}
    return ret


text:
Q: in this code how to compare the Id coming from the URL with the one in the database and then show data to that specific id so i have this code in the controller to view a list of vecation to specfic employee by his id
    public JsonResult GetVacatioinList(int? Id)
    {
        db.Configuration.ProxyCreationEnabled = false;
        List<Vacations> VList = db.Vacations.Include(c => c.VacationType).Select(x => new Vacations
        {

            EmployeesId = x.EmployeesId,
            Id = x.Id,
            VacationType = x.VacationType,
            StartDate = x.StartDate,
            EndDate = x.EndDate,
            Duration = x.Duration

        }).Where(x=> x.EmployeesId == Id).ToList();

        return Json(VList, JsonRequestBehavior.AllowGet);
    }

and this button will show the id for specific employee in URL

now i need to compare the ID coming from URL with one in database for that user if both the same show the vacations for that employee
i tried this and it shows all the vacation when i didn't add the where condition in the LINQ statement in controller  but with where there is no data shown
this is my jquery code that i used


text:
Q: Bootstrap header reverts to white when small I have the following code:

but when the page is shown on a small device such as a phone the background becomes white so nothing can be read.

A: You can try something like this

Just added overflow:hidden in style. This should solve the problem.

A: I would suspect that your styled col-md-12 div is collapsing to width 0 at small sizes (though I can't know without knowing the styles of the content). If you use col-xs-12 the width will be 100% on all device sizes - is there a reason not to do that? I suspect it would solve your problem.

A: class="col-md-12" is meaningless  in your code.Furthermore md stand for mid size view which of course can't work in small devices. So just delete that class.


text:
Q: Linux Netfilter: Enqueue packets to the user-space before defragment The question is: How can I enqueue packets to the user-space with netfilter NFQUEUE before defragment?
According to Linux kernel source, nf_defrag_ipv4 is installed in NF_INET_PRE_ROUTING (known as PREROUTING in iptables/nftables) and NF_INET_LOCAL_OUT (OUTPUT).
So I tried the following anti-defrag nftables filter (original: https://stackoverflow.com/a/30638753/5167443) for NF_INET_LOCAL_OUT, but I'm still getting defragmented packets.
sudo nft add table filter
sudo nft add chain filter predefrag { type filter hook output priority -- -450 \; }
sudo nft add filter predefrag skuid nfqhooked counter queue num 42

In the above filter, -450 stands for a priority that precedes NF_IP_PRI_CONNTRACK_DEFRAG=-400. i.e., the filter is expected to work before nf_defrag_ipv4.
I'm using Linux 3.19 (Ubuntu 15.04) and this my own binding for libnetfilter_queue.so.1.

A: I just resolved by myself.
I had misunderstood that netfilter handles TCP reassembly that is actually handled by "TCP Auto Corking".
Now I can get fragmented (i.e. non-corked) packets by just writing 0 to /proc/sys/net/ipv4/tcp_autocorking.
http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=f54b311142a92ea2e42598e347b84e1655caf8e3


text:
Q: Adding inside a while loop php I have a script that pulls values from a MySQL database and puts into into a variable. Each time it iterates, it pulls a new value. I want to add these values together. Here's what I have:
while ($row = mysql_fetch_array( $result )) {

$getvalue = mysql_query("SELECT value FROM pointvalues WHERE code = '$row[code]'")or die(mysql_error());
$rowcode1 = mysql_fetch_array($getvalue);
$finalValue = $rowcode1["value"];
}

I want to keep adding $finalValue to itself.

A: I recommend  saving yourself all that work and simply changing your query to:
SELECT SUM(value) FROM pointvalues WHERE code = x

Reference: SUM


text:
Q: replace date value in the field in delimited file I have a file (ph.lst) which contains below records. I need to remove the number which comes after .txt. That number is generated randomly so we cannot expect the same on all the time.
test_wkly_20200428010453_PD.txt.1589553864|test_wky|05-01-2020 16:07:53|35858

I want remove .1589553864 and my output should be
test_wkly_20200428010453_PD.txt|test_wky|05-01-2020 16:07:53|35858

I have tried
sed -i 's/\.[0-9]$*//' ph.lst
Please help

A: Try this sed command:
sed -i 's/txt\.[0-9]*/txt/' ph.lst

Replaces txt. followed by any amount of numbers with txt.

A: The command that you say you have tried,
sed -i 's/\.[0-9]$*//' ph.lst

is only a tiny bit wrong.  The $ would match the end of the line, but this is not what you want to match at that point.  Instead, use
sed 's/\.[0-9]*//' ph.lst

or,
sed 's/\.[[:digit:]]*//' ph.lst

This would delete every digit that occurs directly after the first dot (and the dot) on each line of input. The output would be written to standard output, so you can redirect it into a new file.
With awk, you would do the same sort of thing with
awk -F '|' 'BEGIN { OFS=FS } { sub("\.[[:digit:]]*", "", $1) }; 1' ph.lst

This parses the lines of ph.lst as |-delimited fields and removes the substring using same regular expression as with sed (here only acting on the first field).


text:
Q: How do runtime-created sub views communicate with the view controller? For iOS development, if you create and add a sub view at runtime, how would you allow it to communicate with the view controller? Since the sub view isn't instantiated within a nib, you can't use Interface Builder to drag a connection to an IBAction method on the controller. I can't see an obvious way to grab a handle to the controller from the view. Or am I looking at it the wrong way and should instead be communicating with it indirectly via NSNotificationCenter?

A: What are you trying to communicate? IBActions are for predifined (or newly defined if you want to go through the hassle of adding ur UI element to IB) UI elements that can trigger some selector upon some interaction, for that you can always have the same effect programatically... For example, to create a UIButton at run time you can do..
 UIButton *button=[[UIButton alloc] initWithFrame:frame];
   [button addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

Anything that you can do in interface builder you can do programatically as well...you just have to look for the methods that will bind actions to the UI element ...hope this helps.
After reading your comment:
You can consider creating the buttons from the view controller instead of the view, probably the might be the correct way to do it (dont know your circumstance though)...If not then either the view can handle your events and use a protocol to delegate the events to the view controller, or you can use a protocol to register as a target to the UI element, there are many ways to go about solving your problem, what are your circumstances?

A: Most views don't communicate directly with the view controller. Rather, they are connected to an IBOutlet, or they use target-action to call a method on the view controller.
For the former, just declare an IBOutlet property as you normally would and set it after you create the view. (Note that technically, you don't need the IBOutlet keyword as you're not making a connection in IB, but I don't think it hurts anything.)
self.myViewOutlet = myNewView;

If your UIView is a subclass of UIControl, use addTarget: action: forControlEvents: to have methods of your view controller called when certain events happen on the control.
[myNewControl addTarget:self action:@selector(mySelector:) forControlEvents:UIControlEventTouchDragInside];

A: Answering it myself... I was creating these subviews from within a parent view so didn't have access to the controller there either, so the self in the code examples from the other answers wasn't possible. But then after thinking about it a bit, I've decided to move the code into the controller itself but instead chose to use a delegate rather than a target-action because it's a custom message, not just a simple touch event. Thanks to those who helped.


text:
Q: snapshot connectionstate is always waiting while using stream as FirebaseAuth.instance.onAuthStateChanged i am trying to create an authentication using firebase_auth using email and password the code has 3 pages 1.Main page where it checks  if the connection has established or user is already logged in or not. and navigates to the respective pages which is done by a function _handleWidnowDisplay() .
But for some reason the app is stuck in if (snapshot.connectionState == ConnectionState.waiting){} block and doesn't connect to firebase .
While adding the firebase dependencies i had some issues which was solved by adding android.useAndroidX=true and android.enableJetifier=true to gradel.properties.
import 'package:flutter/material.dart';
import 'screens/MyLogin.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'screens/MainPage.dart';

void main() => runApp(new MaterialApp(
      color: Colors.red,
      home: _handleWidnowDisplay(),
    ));

Widget _handleWidnowDisplay() {
  return StreamBuilder(
    stream: FirebaseAuth.instance.onAuthStateChanged,
    builder: (BuildContext context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Scaffold(
            appBar: AppBar(
              title: new Text("MyLogin"),
              backgroundColor: Colors.red.shade900,
            ),
            body: new Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                color: Colors.red.shade900,
                child: new Center(
                  child: new Text("Loding....."),
                )));
      } else if (snapshot.hasData) {
        return MainPAge();
      } else {
        return MyLogin();
      }
    },
  );
}

A: If it is stuck in waiting, my first instinct will be to check your device's connectivity. Edit the AndroidManifest.xml to allow INTERNET_PERMISSION. I dont see the methodto actually log in, thus changing the status to not waiting so make sure that is actually being called.


text:
Q: Return all possible permutations and combinations of numbers from n arrays whose sum is less than m and greater than r I have two arrays:
array1: [0 1 2 3]
array2: [0 1 2 3 4 5 6 7]
array3: [0 1 2 3 4 5]

I want to find combination from each array like 1 element from each array such that the sum >= m eg.3 and sum <=r eg. 6
Example:
array1  array2  array3 elements
1          1    1       (sum is 3)
1          5    0       (sum is 6)

1          6     1       (wrong result sum is greater than 6)

Thanks in advance.
I don't understand how to solve this problem . A pseudocode will be very helpful.

A: Let there be N=3 sorted arrays A(size = p),  B(size = q) and C(size=r).
Choose a number say X and try finding a sum of N=3 numbers x1 + x2 + x3
such that X = x1 + x2 + x3. Finding x1, x2 and x3 can be done using dynamic programming.
Now,
Consider the sequence ABC and use binary search to find x1 in array A, x2 in array B and x3 in array C.
Consider the sequence ACB and use binary search to find x1 in array A, x2 in array C and x3 in array B.
Consider the sequence BAC and use binary search to find x1 in array B, x2 in array A and x3 in array C.
You will find that there are N! number of such sequences.
You will be required to repeat the above process for all X such that [m]<=[X]<=[r].
Total Complexity would be (r - m + 1) * (N!) * ((log p) + (log q) + (log r)).
Total Complexity does not include the dynamic programming part.

A: As I have mentioned in my comment; compared to the brute force, in JS by a dynamical programming approach you may get the results much faster, like in total around 10ms for your test case, as follows;

function getCombos(arr,n,m){

  function getBinaryMap(d){
    return Array(a.length).fill()
                          .reduce((p,c,i) => p.concat(d >> i & 1),[]);
  }

  var a = arr.reduce((p,c) => p.concat(c.filter(e => e !== 0 && e <= m)),[]);
      t = [0],
      r = [];
  a.forEach(e => t = t.concat(t.map((f,i) => (f + e >= n && f + e <= m && r.push(getBinaryMap(t.length + i)), f + e))));
  return r.map(e => e.reduce((p,c,i) => c ? p.concat(a[i]) : p,[]));;
}

var arrays = [[0, 1, 2, 3],[0, 1, 2, 3, 4, 5, 6, 7],[0, 1, 2, 3, 4, 5]];
    result = getCombos(arrays,3,6);

console.log(JSON.stringify(result));


text:
Q: Every convergent sequence in a metric space has a unique limit. I'm reading through a proof in my lecture notes:

Every convergent sequence of a metric space has a unique limit.

Suppose $\lim_{n \to \infty} x_n = l$ and $\lim_{n \to \infty} x_n = m.$ Then for every $\epsilon > 0,$ there exists $N$ such that for every $n \geqslant N,$
$$d(l,m) \leqslant d(l,x_n) + d(x_n,m) < \epsilon + \epsilon = 2 \epsilon. $$
So $(\star) \hspace{1mm} 0 \leqslant \frac{d(l,m)}{2} < \epsilon \Longrightarrow \hspace{1mm} (\star^\prime) \hspace{1mm} \frac{d(l,m)}{2} =0 \Longrightarrow l = m.$
I can follow the proof up until the jump from $(\star)$ to $(\star^\prime)$. Why does $\frac{d(l,m)}{2}=0$?

A: It's badly stated. The point is that
$$0\le\frac{d(\ell,m)}2<\epsilon$$
for every $\epsilon>0$, which is possible only if $\frac{d(\ell,m)}2=0$: otherwise it would be less than itself!

A: One has the following statement:

Let $X$ be a Hausdorff space and $(x_n)_{n\in\mathbb{N}}\in X^\mathbb{N}$, then $(x_n)_{n\in\mathbb{N}}$ has at most one limit in $X$.

Assume that $(x_n)_{n\in\mathbb{N}}$ is convergent to $x_1\in X$ and assume there exists $x_2\in X\setminus\{x_1\}$ such that $(x_n)_{n\in\mathbb{N}}$ is convergent to $x_2$. Since $x_1\neq x_2$ and $X$ is Hausdorff, there exists $V_1$ an open neighborhood of $x_1$ in $X$ and $V_2$ an open neighborhood of $x_2$ in $X$ such that $V_1\cap V_2=\varnothing$. Since $(x_n)_{n\in\mathbb{N}}$ is convergent to $x_1$ there exists $N_1\in\mathbb{N}$ such that for all $n\geqslant N_1,x_n\in V_1$, likewise there exists $N_2\in\mathbb{N}$ such that for all $n\geqslant N_2,x_n\in V_2$. Define $N:=\max(N_1,N_2)$, one has $x_N\in V_1\cap V_2$, a contradiction.
Now, notice that, one has:

Let $(X,d)$ a metric space, then $X$ is Haussdorf.

Let $(x,y)\in X^2$ such that $x\neq y$, then one has:
$$d:=d(x,y)>0.$$
$V_x:=B\left(x,\frac{d}{2}\right)$ is an open neighborhood of $x$ and $V_y:=B\left(y,\frac{d}{2}\right)$ is an open neighborhood of $y$, one has:$$V_x\cap V_y=\varnothing.$$
Indeed, otherwise there exists $z\in V_1\cap V_2$ and one has:
$$d(x,z)<\frac{d}{2}\textrm{ and }d(y,z)<\frac{d}{2}.$$
Using triangle inequality it follows: $$d=d(x,y)<d,$$
which is a contradiction.
N.B. This answer is only here to show you that uniqueness of a limit of a sequence is not only true in metric spaces which are a particular case of Hausdorff spaces.

A: If $d(l,m)/2<\epsilon$ for every $\epsilon>0$, then $d(l,m)/2=0$ otherwise $d(l,m)/2<d(l,m)/2$ which is a contradiction.


text:
Q: How to convert columns to Hex and then concatenate to have a new column with fixed length? I have 3 numeric columns say as below:
import pandas as pd
df = pd.DataFrame()
df['col1']=[123456, 123456, 123456 ]
df['col2']=[7, 65, 150]
df['col3']=[1, 35, 60]

I want to create a new column concatenating these three columns after converting each of them to Hex numbers so that col1 is converted to 5 digit Hex, col2 is converted to 3 digit Hex and col3 is converted to 2 digit Hex. I can convert each one of them to Hex applying lambda function however, I am not able to consistently have 10 characters in the new column. Any suggestion?

A: Use:
#create dictionary for columns names with lengths
d = {'col1':5, 'col2':3, 'col3':2}

#convert to format in nested list comprehension
#https://stackoverflow.com/a/12638477
L = [["{0:0{1}x}".format(x, v) for x in df[k]] for k, v in d.items()]
print (L)
[['1e240', '1e240', '1e240'], ['007', '041', '096'], ['01', '23', '3c']]

#join strings together
df['new'] = [''.join(x) for x in zip(*L)]
print (df)

     col1  col2  col3         new
0  123456     7     1  1e24000701
1  123456    65    35  1e24004123
2  123456   150    60  1e2400963c


text:
Q: How to write a cron job ( Scheduled task ) in spring web flux? I am implementing forget password feature in spring web flux application and where I am sending an OTP with a expiration of 5 min upfront. So I want to invalidate them by executing a cron job every 2 seconds.
Though this is a web flux project I want to test by writing a hello world as a cron job at first like this.
I added @EnableScheduling in starter main class and i have written a test class like.
@Scheduled(cron = "*/2 * * * * *")
    public Disposable invalidateOtp(){

       return Mono.fromCallable(() -> {
           return "Hello";
       }).subscribe();

    }

But I would say this method does not execute after every 2 seconds. Can anyone suggest me why?

A: Here is very good article about how to run Scheduled tasks with cron expression or with fixed rate or fixed delay: The @Scheduled Annotation in Spring. This should give you all you need. However, At some point I felt that all options provided in Spring boot were not convinient enough especially for human readability of the params. You have to specify time in milliseconds or with cron-expression which is not very easily readable. So, I wanted to be able specify time like "9m" for 9 minutes or "3h" for 3 hours and so forth. So, I wrote my own background task scheduler that can easily be used with Spring boot. I published it in Open source library called MgntUtils which is written and maintained by me. Here is a Javadoc page that explains my idea and how to use the feature. (This is part of MgntUtils library javadoc) You can get the library as Maven artifact here or on the github (with javadoc and source-code included). On the github you can look in the package: com.mgnt.lifecycle.management.backgroundrunner.example. That package contains complete working example of 2 scheduled tasks. If you download the source you can just run them out of the box and see how they work

A: I finally found the answer. I forget to annotate my service class @Service. Otherwise spring will not found any bean.


text:
Q: Architecting...a slideshow I know this sounds silly and I could use some out-of-the-box solution, but I really want to build my own simple image slideshow. I've been doing application development in Silverlight/WPF for some time, but for whatever reason I can't wrap my head around this.

*

*I have an observable collection of SlideshowItem

*Each SlideshowItem has Source which indicates where the image for it is located

*I show a translucent box for each SlideshowItem (horizontal list using a stackpanel) and when you click, you should transition to that slide

So here's my problem: If I have that list with a stackpanel template, and under the list is an image taking up the size of the canvas, I can bind the context of the image to the selected SlideshowItem. That's all well and good. But when I click/change the selected index of the list, I want to do a crossfade or slide between two images.
How should I represent this in Silverlight? Should I actually have a scroll panel or something with all the images and then change between them? Or is it sufficient to use a single image control? Can I do this with states, or do I need to explicitly run a storyboard? Any samples would be appreciated.

A: You can use the TransitioningContentControl from the Silverlight Toolkit, however if you want to roll your own you will need two content controls and swap out the "Active" one on SelectionChanged events. You also can fire your storyboards here.
ContentControl _active;
private void LB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

    if (_active == Content1)
    {
        _active = Content2;
        Content2Active.Begin();
    } else
    {
        _active = Content1;
        Content1Active.Begin();
    }

    _active.Content = LB.SelectedItem;
}

And the Xaml looks something like this. I just use strings and text, but this approach should work reasonable well for images too:
<Grid x:Name="LayoutRoot" Background="White" MaxHeight="200">
    <Grid.Resources>
        <Storyboard x:Name="Content1Active">
            <DoubleAnimation From="0" To="1" Storyboard.TargetName="Content1" Storyboard.TargetProperty="(UIElement.Opacity)" />
            <DoubleAnimation To="0" Storyboard.TargetName="Content2" Storyboard.TargetProperty="(UIElement.Opacity)" />
        </Storyboard>
        <Storyboard x:Name="Content2Active">
            <DoubleAnimation From="0" To="1" Storyboard.TargetName="Content2" Storyboard.TargetProperty="(UIElement.Opacity)" />
            <DoubleAnimation To="0" Storyboard.TargetName="Content1" Storyboard.TargetProperty="(UIElement.Opacity)" />
        </Storyboard>
    </Grid.Resources>

    <StackPanel>
        <ListBox x:Name="LB" SelectionChanged="LB_SelectionChanged" xmlns:sys="clr-namespace:System;assembly=mscorlib">
            <sys:String>Red</sys:String>
            <sys:String>Green</sys:String>
            <sys:String>Blue</sys:String>
        </ListBox>
        <Grid>
            <ContentControl x:Name="Content1" FontSize="40" Foreground="{Binding Content, RelativeSource={RelativeSource Self}}">
            </ContentControl>
            <ContentControl x:Name="Content2" FontSize="40" Foreground="{Binding Content, RelativeSource={RelativeSource Self}}">
            </ContentControl>
        </Grid>
    </StackPanel>
</Grid>

A: Definitely you don't need the entire Image collection displayed in a scrollviewer/stackpanel. You can implement this in many different ways. I can explain a simple idea of Using one Image :  As you said , define a SelectedSlide property in your ViewModel and bind that to an Image control ( Preferably a ContentControl with Image as its part of the ContentTemplate, so that you can have descriptions and other items in the same). This solution can give you the opportunity to add some storyboards so that if you increase your SelectedIndex(Another VM property) fire a storyboard to do a 'Left Move' animation and if you decrease do a 'Right Move' animation makes user feels like slides are coming from one side and going the other way. You can do pretty good UX on that set of storyboards.
Update (Idea 2) : Yes if we need the notion of the previous one leaving the view when new one coming in, we can architect it by using two ContentControls wrapped inside a CustomControl ( lets call it as SlideShowControl). SlideShowControl will have its mechanism to properly set DataContext of the two ContentControl based on the selectedIndex position. I have successfully made this control in one of my projects, the logic here is to switch the ContentControls through a storyboard so that we can have many different effects by swapping the storyboard. Suppose you move from Index 1 to 2, ContentControlA will animate to left, and B will come in to the View, and based on your next click ControlA will go sit either left or right of the View, and comes with new DataContext of the selected View.


text:
Q: standard Brownian motion. Calculate the probability that W(3) > W(2) > W(1). Assume that W(t) is the standard Brownian motion. Calculate the probability that
W(3) > W(2) > W(1).
Hi I am really bad with BM so can anyone please help me here?

A: Equivalently you want to calculate $W(3)-W(2)>0$ and $W(2)-W(1)>0$.
Recall that $W(3)-W(2)\sim N(0,1)$ and $W(2)-W(1) \sim N(0,1)$ are independent.
Therefore, $$\mathbb{P}(W(3)>W(2)>W(1)) =\mathbb{P}(W(3)-W(2)>0)\cdot\mathbb{P}(W(2)-W(1)>0)=\frac{1}{4}$$


text:
Q: javascript int to binary but print is infinity   data = parseInt(num);
  bin =0;
  pow=1;
  var rem=0 ;
 while(data != 0){
  rem = data % 2;
 data = data / 2;
  bin = rem * pow + bin;
  pow = pow *10;
  }

  document.write(bin);

for example 53 is 110110. but print is infinity in javascript. Where is my fault?

A: You could do the following:
parseInt('53').toString(2); // returns 110110

or just
(53).toString(2);

full:
var num = prompt("Please enter an integer between 0 and 255", "");

document.write(parseInt(num, 10).toString(2));


text:
Q: Wicket 6 Set Checkbox of CheckGroup unchecked by default I'm using CheckGroup and Check  to set up a listview of CheckBoxes. The Wicket example show the checkboxes unchecked by default: Wicket Checkgroup Example
I've been looking and testing for a while, but mine are checked by default and I need them to be unchecked.
Here is my code (Note that it's a custom class which i'll add to a form later):
private CheckGroup<String> checks;
private List<String> propertyColumnNames;
private Map<String, String> readableColumnNames;

checks = new CheckGroup<String>("checkGroup", propertyColumnNames);

ListView<String> checksList = new ListView<String>("columns", propertyColumnNames) {
  private static final long serialVersionUID = 1L;

  @Override
  protected void populateItem(ListItem<String> item) {
    Check<String> check = new Check<String>("check", item.getModel());
    check.setLabel(new Model<String>(readableColumnNames.get(item.getModel().getObject())));
    item.add(check);
    item.add(new SimpleFormComponentLabel("column", check));
  }
};
checksList.setReuseItems(true);
checks.add(checksList);
add(checks);

How can I get them unchecked by default ?
Regards,

A: The problem is here:
checks = new CheckGroup<String>("checkGroup", propertyColumnNames);

Here you're telling CheckGroup to check every checkbox which is in propertyColumnNames. You need to give an empty collection as the model to CheckGroup.


text:
Q: Why can't the second-derivative of a function (with respect to some variable) be written as follows? Let us suppose we have a function $f(r)$, where $r$ itself is a function, $r(x,y,z)$.
Why is it incorrect to write:
$$\frac{\partial^2 f}{\partial x^2} = \frac{\partial^2 f}{\partial r^2} \cdot \frac{\partial^2 r}{\partial x^2} $$
The PDE equation
Please forgive my lack of knowledge on this topic. I would really like to understand why this is the case.

A: The first derivative gives you a product via the chain rule:
$$
\dfrac{\partial }{\partial x}(f\circ r) = \dfrac{\partial}{\partial r} f \cdot \dfrac{\partial}{\partial x}r
$$
As a consequence we have to deal with the Leibniz rule in the next step. It is basically what defines a derivative besides linearity: $D_p(f\cdot r)= (D_{r(p)}f)\cdot r +f\cdot (D_pr).$ You cannot just drop one of the terms. 'Multiplication becomes addition by differentiation' is a rule of thumb. It is a deep truth hidden in the Leibniz rule, since in the end it corresponds to the functional formula of the exponential function, which is why differential equations can often be solved by using an ansatz with the exponential function.


text:
Q: Cypress save cookie value I want to save a cookie value using Cypress, but unfortunately I always get undefined in the log console using this code
let cookieValue;
cy.getCookie('SOME_COOKIE')
    .should('have.property', 'value')
    .then((cookie) => {
        cookieValue = cookie.value;
    })
cy.log(cookieValue);

When I try this
let cookieValue;
cy.getCookie('SOME_COOKIE')
    .should('have.property', 'value', 'Dummy value')
    .then((cookie) => {
        cookieValue = cookie.value;
    })
cy.log(cookieValue);

I can see the actual value I want in the error message.

A: Cypress work asynchronously and you can't consume the cookie value as you did.
From the docs

Want to jump into the command flow and get your hands on the subject directly? No problem, simply add a .then() to your command chain. When the previous command resolves, it will call your callback function with the yielded subject as the first argument.

You should go ahead with your test code inside the then callback and not relying on the external let cookieValue assignment.
Try this
cy.getCookie('SOME_COOKIE')
    .should('have.property', 'value')
    .then((cookie) => {
        cookieValue = cookie.value;
        // YOU SHOULD CONSUME `cookieValue` here
        // .. go ahead inside this `then` callback
    })

A: you can also use Async and await instead of adding code inside then()
const getmyCookie = async (cookiename) => {
    return cy.getCookie(cookiename)
        .should('exist')
        .then(async (c) => {
            cy.log(c.value)
            return c.value
        })
}

Use it in your test and ensure your it block is async
it('Sample Test', async function () {
   ... some code

   const cookie = await getmyCookie('cookiename')
   cy.log(cookie)

   ... some code
})


text:
Q: How to control concurrency of a subdag or taskgroup in Airflow? I have a simple ETL workflow composed of three tasks for each table I want to extract :
1_extract_to_tmp >> 2_push_to_s3 >> 3_delete_tmp
As I want to reproduce the same steps for multiple tables, I was thinking of grouping these task in a TaskGroup or a subDAG and instanciate it dynamically for each table to extract. My final DAG will look like this :

From what I read, the TaskGroup is the prefered solution now to do that.
The problem is that I also need to control how much extractions are done in parallel because I don't have enough local disk space for all data and apparently the subDag operator does not comply to pool setting and the TaskGroup does not have one.
Do you know a way to achieve this ?
Am I doing it wrong ?
Maybe my DAG should not be designed like that.

A: TaskGroup is just a UI feature. It doesn't really contains logic so any parallelism limitation you want to enforce can be done regardless to the usage of TaskGroup.
You didn't explain what exactly you want to limit.
If you want to limit the overall tasks that can run in parallel with on your dag (overwrite the airflow.cfg default) then set concurrency in your DAG contractor:
dag = DAG(dag_id='my_dag', concurrency=5, ...)

If you are looking to limit concurrency usage to protect a specific resources (database, api,  etc...) then use pools:
my_op = PythonOperator(python_callable=func,
                          task_id='my_task',
                          pool='my_pool',
                          dag=dag)

The task will be executed only if there are free slots in the pool. The number of available slots are defined when you create the pool.
As for SubDags I wouldn't recommand using it at all. While it's not officially deprecated it probably will be. See https://github.com/apache/airflow/issues/12292