text:
Q: Using mechanize to upload files to Sharepoint is failing, I can't figure out why Below is the code that I am using. Can anybody please tell me what I am missing here?
br.select_form("aspnetForm")
br.form.set_all_readonly(False)
FILENAME="2BProcessed.txt"
#br['ctl00$PlaceHolderMain$UploadDocumentSection$ctl03$InputFile']=FILENAME
br.form.add_file(open(FILENAME), 'text/plain', FILENAME)

print br.form
print "------------------------------------------------"
br.method="POST"
response = br.submit()
#print response.read()
for f in br.forms():
    print f

and here is what the forms look like before (empty), when a file is selected, and finally after submiting the form
Form before posting
<aspnetForm POST httP://server.addrees.removed... multipart/form-data
  <HiddenControl(MSOWebPartPage_PostbackSource=) (readonly)>
  <HiddenControl(MSOTlPn_SelectedWpId=) (readonly)>
  <HiddenControl(MSOTlPn_View=0) (readonly)>
  <HiddenControl(MSOTlPn_ShowSettings=False) (readonly)>
  <HiddenControl(MSOGallery_SelectedLibrary=) (readonly)>
  <HiddenControl(MSOGallery_FilterString=) (readonly)>
  <HiddenControl(MSOTlPn_Button=none) (readonly)>
  <HiddenControl(MSOSPWebPartManager_DisplayModeName=Browse) (readonly)>
  <HiddenControl(MSOSPWebPartManager_ExitingDesignMode=false) (readonly)>
  <HiddenControl(__EVENTTARGET=) (readonly)>
  <HiddenControl(__EVENTARGUMENT=) (readonly)>
  <HiddenControl(MSOWebPartPage_Shared=) (readonly)>
  <HiddenControl(MSOLayout_LayoutChanges=) (readonly)>
  <HiddenControl(MSOLayout_InDesignMode=) (readonly)>
  <HiddenControl(MSOSPWebPartManager_OldDisplayModeName=Browse) (readonly)>
  <HiddenControl(MSOSPWebPartManager_StartWebPartEditingName=false) (readonly)>
  <HiddenControl(MSOSPWebPartManager_EndWebPartEditing=false) (readonly)>
  <HiddenControl(_maintainWorkspaceScrollPosition=0) (readonly)>
  <HiddenControl(__REQUESTDIGEST=0x86FE3811F793DC67C1CA3282A8213erwerC0CD91108B06F41D5C600B09C3A22E0661289A176933917B7D6786859B7717A924AE49E31E5C4B9A01DD25A2EC2,28 Jul 2015 15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uxuY2gn08bbL4JgmPox8f) (readonly)>
  <HiddenControl(ctl00$PlaceHolderSearchArea$ctl01$ctl00=https://server.address.removed/wnp0/04693Ka00000878) (readonly)>
  <HiddenControl(ctl00$PlaceHolderSearchArea$ctl01$ctl01=https://server.address.removed/wnp0/04693Ka00000878/Shared Documents) (readonly)>
  <TextControl(ctl00$PlaceHolderSearchArea$ctl01$S3031AEBB_InputKeywords=Search this site...)>
  <HiddenControl(ctl00$PlaceHolderSearchArea$ctl01$ctl05=0) (readonly)>
  <HiddenControl(destination=/wnp0/04693Ka00000878/Shared Documents/Data) (readonly)>
  <FileControl(ctl00$PlaceHolderMain$UploadDocumentSection$ctl03$InputFile=<No files added>)>
  <CheckboxControl(ctl00$PlaceHolderMain$UploadDocumentSection$ctl03$OverwriteSingle=[*on])>
  <TextControl(ctl00$PlaceHolderMain$ctl04$ctl02$uploadLocation=/Data/)>
  <SubmitControl(ctl00$PlaceHolderMain$ctl04$ctl02$selectTargetButton=Choose Folder...) (readonly)>
  <IgnoreControl(ctl00$PlaceHolderMain$ctl03$RptControls$btnOK=<None>)>
  <IgnoreControl(ctl00$PlaceHolderMain$ctl03$BtnCancel=<None>)>
  <TextControl(__spText1=)>
  <TextControl(__spText2=)>>

Forme before submitting it:

<aspnetForm POST httP://server.addrees.removed04693Ka00000878 ...multipart/form-data
  <HiddenControl(MSOWebPartPage_PostbackSource=)>
  <HiddenControl(MSOTlPn_SelectedWpId=)>
  <HiddenControl(MSOTlPn_View=0)>
  <HiddenControl(MSOTlPn_ShowSettings=False)>
  <HiddenControl(MSOGallery_SelectedLibrary=)>
  <HiddenControl(MSOGallery_FilterString=)>
  <HiddenControl(MSOTlPn_Button=none)>
  <HiddenControl(MSOSPWebPartManager_DisplayModeName=Browse)>
  <HiddenControl(MSOSPWebPartManager_ExitingDesignMode=false)>
  <HiddenControl(__EVENTTARGET=)>
  <HiddenControl(__EVENTARGUMENT=)>
  <HiddenControl(MSOWebPartPage_Shared=)>
  <HiddenControl(MSOLayout_LayoutChanges=)>
  <HiddenControl(MSOLayout_InDesignMode=)>
  <HiddenControl(MSOSPWebPartManager_OldDisplayModeName=Browse)>
  <HiddenControl(MSOSPWebPartManager_StartWebPartEditingName=false)>
  <HiddenControl(MSOSPWebPartManager_EndWebPartEditing=false)>
  <HiddenControl(_maintainWorkspaceScrollPosition=0)>
  <HiddenControl(__REQUESTDIGEST=0x86FE3811F793DC67C1CA3282A4324325BE6BACC0CD91108B06F41D5C600B09C3A22E0661289A176933917B7D6786859B7717A924AE49E31E5C4B9A01DD25A2EC2,28 Jul 2015 15:52:24 -0000)>
  <HiddenControl(__VIEWSTATE=/wEPDwUJMzMyMzUzNDEyD2QWAmYPZBYCAgrweertAgMPFgIeB2VuY3R5cGUFE211bHRpcGFydC9mb3JtLWRhdGEWCgIRD2QWBGYPZBYEAgEPZBYCZg9kFgQCAg9kFhICAQ8WAh4HVmlzaWJsZWhkAgMPFggeE0NsaWVudE9uQ2xpY2tTY3JpcHQFigFqYXZhU2NyaXB0OkNvcmVJbnZva2UoJ1Rha2VPZmZsaW5lVG9DbGllbnRSZWFsJywxLCAxLCAnaHR0cHM6XHUwMDJmXHUwMDJmc3B4Z3JvdXAucmJjLmNvbVx1MDAyZnducDBcdTAwMmYwNDY5M0thMDAwMDA4NzgnLCAtMSwgLTEsICcnLCAnJykeGENsaWVudE9uQ2xpY2tOYXZpZ2F0ZVVybGQeKENsaWVudE9uQ2xpY2tTY3JpcHRDb250YWluaW5nUHJlZml4ZWRVcmxkHgxIaWRkZW5TY3JpcHQFIVRha2VPZmZsaW5lRGlzYWJsZWQoMSwgMSwgLTEsIC0xKWQCBw8WAh8BaGQCCQ8WAh8BaGQCCw8WAh8BaGQCDw8WAh8BaGQCEQ8WAh8BaGQCEw8WAh8BaGQCFQ8WAh8BaGQCAw8PFgoeCUFjY2Vzc0tleQUBLx4PQXJyb3dJbWFnZVdpZHRoAgUeEEFycm93SW1hZ2VIZWlnaHQCAx4RQXJyb3dJbWFnZU9m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9jdW1lbnRTZWN0aW9uJGN0bDAzJE92ZXJ3cml0ZVNpbmdsZQVHY3RsMDAkUGxhY2VIb2xkZXJUb3BOYXZCYXIkUGxhY2VIb2xkZXJIb3Jpem9udGFsTmF2JFRvcE5hdmlnYXRpb25NZW51VjQPD2QFBEhvbWVkOhC8IAD1XERhAgYCUaHvvTQe4BY=)>
  <HiddenControl(__EVENTVALIDATION=/wEWCgLi07HcCgKpn5bCCwLEiLTXBQLNrvertyCDQKMpf/RBQL7opj3BAKLy4KjDQLHnuf8DwLI6ZCjDAC/5mtuxuY2gn08bbL4JgmPox8f)>
  <HiddenControl(ctl00$PlaceHolderSearchArea$ctl01$ctl00=https://server.address.removed/wnp0/04693Ka00000878)>
  <HiddenControl(ctl00$PlaceHolderSearchArea$ctl01$ctl01=https://server.address.removed/wnp0/04693Ka00000878/Shared Documents)>
  <TextControl(ctl00$PlaceHolderSearchArea$ctl01$S3031AEBB_InputKeywords=Search this site...)>
  <HiddenControl(ctl00$PlaceHolderSearchArea$ctl01$ctl05=0)>
  <HiddenControl(destination=/wnp0/04693Ka00000878/Shared Documents/Data)>
  <FileControl(ctl00$PlaceHolderMain$UploadDocumentSection$ctl03$InputFile=2BProcessed.txt)>
  <CheckboxControl(ctl00$PlaceHolderMain$UploadDocumentSection$ctl03$OverwriteSingle=[*on])>
  <TextControl(ctl00$PlaceHolderMain$ctl04$ctl02$uploadLocation=/Data/)>
  <SubmitControl(ctl00$PlaceHolderMain$ctl04$ctl02$selectTargetButton=Choose Folder...)>
  <IgnoreControl(ctl00$PlaceHolderMain$ctl03$RptControls$btnOK=<None>)>
  <IgnoreControl(ctl00$PlaceHolderMain$ctl03$BtnCancel=<None>)>
  <TextControl(__spText1=)>
  <TextControl(__spText2=)>>

  -------------Form after  using .submit() -----------------------------------

<aspnetForm POSThttP://server.addrees.removed04693Ka00000878/_layouts/UploadEx.aspx?List=%7bDAD046C2-93DB-47E9-85D1-B37BA16BC0F0%7d&RootFolder=%2fwnp0%2f04693Ka00000878%2fShared+Documents%2fWiFi+Installation+Data multipart/form-data
  <HiddenControl(MSOWebPartPage_PostbackSource=) (readonly)>
  <HiddenControl(MSOTlPn_SelectedWpId=) (readonly)>
  <HiddenControl(MSOTlPn_View=0) (readonly)>
  <HiddenControl(MSOTlPn_ShowSettings=False) (readonly)>
  <HiddenControl(MSOGallery_SelectedLibrary=) (readonly)>
  <HiddenControl(MSOGallery_FilterString=) (readonly)>
  <HiddenControl(MSOTlPn_Button=none) (readonly)>
  <HiddenControl(MSOSPWebPartManager_DisplayModeName=Browse) (readonly)>
  <HiddenControl(MSOSPWebPartManager_ExitingDesignMode=false) (readonly)>
  <HiddenControl(__EVENTTARGET=) (readonly)>
  <HiddenControl(__EVENTARGUMENT=) (readonly)>
  <HiddenControl(MSOWebPartPage_Shared=) (readonly)>
  <HiddenControl(MSOLayout_LayoutChanges=) (readonly)>
  <HiddenControl(MSOLayout_InDesignMode=) (readonly)>
  <HiddenControl(MSOSPWebPartManager_OldDisplayModeName=Browse) (readonly)>
  <HiddenControl(MSOSPWebPartManager_StartWebPartEditingName=false) (readonly)>
  <HiddenControl(MSOSPWebPartManager_EndWebPartEditing=false) (readonly)>
  <HiddenControl(_maintainWorkspaceScrollPosition=0) (readonly)>
  <HiddenControl(__REQUESTDIGEST=0x86FE3811F793DC67C1CA3282A84C015BE6BACC0CD91108B06F41D5C600B09C3A22E0661289A176933917B7D6786859B7717A924AE49E31E5C4B9A01DD25A2EC2,28 Jul 2015 15:52:24 -0000) (readonly)>
  <HiddenControl(__VIEWSTATE=/wEPDwUJMzMyMzUzNDEyD2QWAmYPZBYCAgEPZBYCAgMPFgIeB2VuY3R5cGUFE211bHRpcGFydC9mb3JtLWRhdGEWCgIRD2QWBGYPZBYEAgEPZBYCZg9kFgQCAg9kFhICAQ8WAh4HVmlzaWJsZWhkAgMPFggeE0NsaWVudE9uQ2xpY2tTY3JpcHQFigFqYXZhU2NyaXB0OkNvcmVJbnZva2UoJ1Rha2VPZmZsaW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GQCAg8WAh8BaGQCAw9kFgZmD2QWAmYPDxYCHwxlZGQCAQ9kFgICAQ8PFgIfDAUYL1dpRmkgSW5zdGFsbGF0aW9uIERhdGEvZGQCAg8WAh8BaGQCAg8PFgIfAWhkZAIHD2QWAgIBD2QWAmYPFgQeCWFjY2Vzc2tleQUBQx4Hb25jbGljawXhAXdpbmRvdy5sb2NhdGlvbj0nXHUwMDJmd25wMFx1MDAyZjA0NjkzS2EwMDAwMDg3OFx1MDAyZlNoYXJlZCBEb2N1bWVudHNcdTAwMmZGb3Jtc1x1MDAyZkFsbEl0ZW1zMS5hc3B4P1Jvb3RGb2xkZXI9XHUwMDI1MkZ3bnAwXHUwMDI1MkYwNDY5M0thMDAwMDA4NzhcdTAwMjUyRlNoYXJlZFx1MDAyNTIwRG9jdW1lbnRzXHUwMDI1MkZXaUZpXHUwMDI1MjBJbnN0YWxsYXRpb25cdTAwMjUyMERhdGEnIGQYAgUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFQWN0bDAwJFBsYWNlSG9sZGVyTWFpbiRVcGxvYWREb2N1bWVudFNlY3Rpb24kY3RsMDMkT3ZlcndyaXRlU2luZ2xlBUdjdGwwMCRQbGFjZUhvbGRlclRvcE5hdkJhciRQbGFjZUhvbGRlckhvcml6b250YWxOYXYkVG9wTmF2aWdhdGlvbk1lbnVWNA8PZAUESG9tZWRzdhFBs3mk/C4sRCsvYb44ydiL+Q==) (readonly)>
  <HiddenControl(__EVENTVALIDATION=/wEWCgKctKHNAgKpn5bCCwLEiLTXBQLNrvW5AwLY47yCDQKMpf/RBQL7opj3BAKLy4KjDQLHnuf8DwLI6ZCjDLQQtRpJaA+c51Db8+nAhd28gOn9) (readonly)>
  <HiddenControl(ctl00$PlaceHolderSearchArea$ctl01$ctl00=https://server.address.removed/wnp0/04693Ka00000878) (readonly)>
  <HiddenControl(ctl00$PlaceHolderSearchArea$ctl01$ctl01=https://server.address.removed/wnp0/04693Ka00000878/Shared Documents) (readonly)>
  <TextControl(ctl00$PlaceHolderSearchArea$ctl01$S3031AEBB_InputKeywords=Search this site...)>
  <HiddenControl(ctl00$PlaceHolderSearchArea$ctl01$ctl05=0) (readonly)>
  <HiddenControl(destination=/wnp0/04693Ka00000878/Shared Documents/Data) (readonly)>
  <FileControl(ctl00$PlaceHolderMain$UploadDocumentSection$ctl03$InputFile=<No files added>)>
  <CheckboxControl(ctl00$PlaceHolderMain$UploadDocumentSection$ctl03$OverwriteSingle=[*on])>
  <TextControl(ctl00$PlaceHolderMain$ctl04$ctl02$uploadLocation=/Data/)>
  <SubmitControl(ctl00$PlaceHolderMain$ctl04$ctl02$selectTargetButton=Choose Folder...) (readonly)>
  <IgnoreControl(ctl00$PlaceHolderMain$ctl03$RptControls$btnOK=<None>)>
  <IgnoreControl(ctl00$PlaceHolderMain$ctl03$BtnCancel=<None>)>
  <TextControl(__spText1=)>
  <TextControl(__spText2=)>>

A: Dear friend you may be forgot to update command after submit file into the list. Your mechanize is perfect just add update command after post and submit. after below : response = br.submit()


text:
Q: Wordpress login logout on menu I'm pretty new to WordPress and I'm trying to import a website of mine (which it's all in PHP) to WordPress. The thing is, my NavBar has this code:

bla bla bla

bla bla bla

<?php include_once('Login_Status.php') ?>

That login script (which is a fictious name of course) runs a simple code that checks if the user is logged in and if he is logged it returns:

Member Area

Logout

else, it returns:

Login

So, now that I'm trying to import the website to WordPress and I'm on the nav bar part of the process, I'm not seeing how I'm going to include this PHP file on the wp_nav_menu($args) function.
Any idea or link where I can read further on this?

A: The way I would set this up would be to just add the login, logout and members area links to your nav in the menu manager. Then you can use the Nav Menu Roles plugin to conditionally display those menu items.
Another way to do this would be to setup two nav menus and conditionally display them using the is_user_logged_in function.
$location = is_user_logged_in() ? 'logged_in_menu' : 'logged_out_menu';
wp_nav_menu(array(
    'theme_location' => $location,
    /* ... */
));

This is assuming you have the menus logged_in_menu and logged_out_menu registered using the register_nav_menu function. I would use this solution if the logged in and logged out menus are significantly different. I don't think that's the case for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Call Function In LinQ Query I want to sum price for all products that is in list.
I called a funtion in linQ query.
Total = t0.TbOfferProducts.Sum(x => Customs.CalculateCurrency(x.TbOffer.Price))

But it didnt recognize my function
I wrote another function for linQ, then I called it. But linQ dont recognize my function.

Error:
LINQ to Entities does not recognize the method 'Double Cal_Price(Int32)' method, and this method cannot be translated into a store expression.

I try other versions but none of them didnt work.Help me please.
myList =
    (from t0 in DB.TbProducts
    where t0.BoActive == true && t0.BoSoftDeleted == false
    let price = Cal_Price(t0.InProductId)
    select new ProductActivityInfo
    {

        ID = t0.InProductId,
        Name = t0.StProductName,
        Code = t0.StProductCode,
        Total = price
    })

public double Cal_Price(int productId)
{
    double  total = 0;
    using (MyEntityContext DB = new MyEntityContext())
    {
        var list = DB.TbOfferProducts.Where(x => x.InProductId == productId);

        foreach (var item in list)
        {
            total += Customs.CalculateCurrency(item.TbOffer.Price);
        }
    }

    return total;
}

A: EF Core is tryng to build SQL but fails when found custom compiled method in query. Correct Total on the client side:
// calculate sum by grouping
var offerPrices =
    from op in DB.TbOfferProducts
    group op.TbOffer.Price by x.InProductId
    select new
    {
        ProductId = g.Key,
        RawPrice = g.Sum()
    };

var result =
    (from t0 in DB.TbProducts
    join op in offerPrices on t0.InProductId equals op.ProductId
    where t0.BoActive == true && t0.BoSoftDeleted == false
    select new ProductActivityInfo
    {

        ID = t0.InProductId,
        Name = t0.StProductName,
        Code = t0.StProductCode,
        Total = op.RawPrice
    })
    .ToList();

// correct Total on the client side
result.ForEach(x => x.Total = Customs.CalculateCurrency(x.Total));


text:
Q: How can I choose the highest number in a row, and multiply it automatically with a value in the same column? I have a table in excel that can be seen below.
I want to choose the highest number in the "RPD" row and multiply it with the values that are in the same column.
So in this case the formula would take July column and multiply all the values there.
The problem is that I want to do this automatically, so when the order of values in "RPD" row changes the calculation changes automatically, still chooses the highest value in "RPD" row and multiplies it with all the values in the same column.
I also want to do this for the second highest value and so on...
So I would end up with a new row where the first column has the values for july multiplied and so on.
Thanks in advance.

A: You may need to use the =LARGE(matrix, k) function; where matrix will be the RPD numbers and K-esim largest number. And fix the range of your matrix.
Change MAIOIR to LARGE (i'm using it in pt_BR).
For the 1st one, the formula will be:
=LARGE(C5:N5; B9)*C4*C6

Then will have to lock the parameters by using $
=LARGE($C$5:$N$5; $B9)*C$4*C$6

Output:


text:
Q: Django Stripping Blanks In Between Words When Generating Blanks I am working on a Hangman game using Django and I'm having some trouble generating the blanks from the words if the answer is two words, such as a first and last name. It seems to be something with Django stripping spaces and I have tried playing around with some solutions I found elsewhere, but unsuccessfully.
Here is one 'solution' I found in another custom fields.py file I created.
class ExampleAdmin(admin.ModelAdmin):
    ordering = ['display', ]

    def formfield_for_dbfield(self, db_field, request, **kwargs):
        if db_field.name == 'display':
            kwargs['strip'] = False
        return super().formfield_for_dbfield(db_field, request, **kwargs)

And the other is a custom class within admin.py I created
class NonStrippingTextField(TextField):
    A TextField that does not strip whitespace at the beginning/end of
    it's value.  Might be important for markup/code.

    def formfield(self, **kwargs):
        kwargs['strip'] = False
        return super(NonStrippingTextField, self).formfield(**kwargs)

Here is the method of views.py where I am generating the blanks in the model to be displayed in the template.
if request.method == 'GET':
        load_animals_dict()
        word = generate_animals_word()
        game = Game(answer=word)

        for x in range(len(word)):
            if word[x] == ' ':
                game.display += ' '
            else:
                game.display += '_ '

        return render(request, 'index.html', {"game": game})

For testing purposes I have {{ game.display }} and {{ game.answer }} to see what renders and no matter what I have done - if there are two words the space in between always gets stripped.
EDIT: Splitting into two 'CharFields' I was able to resolve this.


text:
Q: ajax url call confusion EDIT:
I will try to explain what I want to do a bit better. I am displaying a table with all the fields retrieved from a database using an ajax call to a php file (eg. other.php) in my main.php. What I am trying to figure out is once the table is displayed to screen and the call is in the other.php file, can I implement an update query within other.php to update a field in the database with a user input? Does that make sense?
Thanks.

A: Yes, it's possible. Assuming that you have a form that the user fills before clicking in the menu, you can add this values in your ajax call.
For example, assuming that you have a search button
<input type='text' name='search' id='search' />

You can pass this to your php with get or post (type of request)
$.ajax({
  url: "somefile.php",
  type: "POST",
  data: "search=" + $('#search').val(),
  success: function(data){
    //do something...
  }
});

And in your somefile.php you can access the value with $_POST['search'] or $_GET['search'] (depending of the type of the request).
I think with this you can adapt to your reality. More samples you can get in the JQuery docs.


text:
Q: Jquery datepicker show on div mouseover, hide on mouseout from datepicker Im trying to achive that effect: http://www.palms.com/ (look at booking module on right side of site). When u place cursor at div for ex Arriving, it will show you datepicker, u can rollover on it, and pick a date. When u rollout from div or datepicker, its disapears. Thats a problem, whose i cant achive.
I can show datepicker on mouseover, but i cant hide it on mouseover (from datepicker), when im rollout from div, datepicker disapears...
Its my test code:

...

          PICKUP A DAY

A: If you want to hide the datePicker on mouseout, then you should have used fadeOut() like this
$('#content').mouseout(function(){
            $('#calendar').fadeOut('fast');
        });

Check this in JSFiddle1
But my opinion is to use .hover() with a callback like this for a smooth effect
$('#content').hover(function(){
      $('#calendar').fadeIn('fast');
  }, function() {
      $('#calendar').fadeOut('fast');
});

You can check this in JSFiddle2


text:
Q: How accurate is Stack Exchange's idea of time? Currently there is an incentive to post a question in a specific minute of the hour (the first, for the record).  In order to do, I posted, Any GPIO library that supports I2C multi-master mode? which was around 15 seconds past the top of the hour (which was 7pm in New York) according to my nptd synchronised PC.  After waiting patiently for a day my reaction to the gamification on SE had still not earned it's reward - and I'm as Mad as a Hatter (and not a "Hero of Time") but not so Mad I cannot wait until 7pm in Tokyo...
Question: just how accurate is the Stack Exchange time-keeping?

A: It's quite accurate, and the 'window' is one minute. The timezone of your PC doesn't matter; it needs to be 7:00:00pm - 7:00:59pm anywhere in the world.
Your problem is that the Hero of Time hat, like most Winter Bash hats, has an additional hidden requirement: your question must have a positive score. It didn't have it at the moment you posted this Meta question; it does have now, so your Hero of Time hat should be on its way.


text:
Q: Using random.choice() to generate multiple times, then assign to a variable I am trying to make a game , and one of the functions needed is random text generation(From a Dict). For this I've been using the the random.choice() function with the random library. I want the code to generate a new result everytime the function is called. Here is the code:
colours = ["red","yellow","orange","green","blue","purple","grey"]
words = ["red","yellow","orange","green","blue","purple","grey"]
worrd = random.choice(words)
def get():
 print(ent.get())

def start():
 print("started")
 lab.pack_forget()
 sta.pack_forget()
 opt.pack(padx=5,pady=4)
 ent.pack(padx=5,pady=9)
 acc.pack(padx=7,pady=9)
 opt.config(text=worrd,fg=random.choice(colours))

How would I generate a new result from the words dict, and then assign it to the worrd variable?

A: You can use random index:
import random
words = ["red","yellow","orange","green","blue","purple","grey"]
worrd=words[random.randint(0,len(words)-1)]

It's change worrd variable every time.


text:
Q: NullPointerException at android widget ArrayAdapter private void fillArrayAdapter() {
        Cursor c = db.rawQuery("SELECT * FROM quotes", null);
        int count = c.getCount();
        int column = c.getColumnCount();
        Log.d("countcl", column + "");
        totalRec = new String[count * column];
        Log.d("counttot", totalRec + "");
        int i = 0;
        c.moveToFirst();
        while (!c.isAfterLast()) {
            totalRec[i++] = c.getString(c.getColumnIndex("qoutemsg"));
            c.moveToNext();
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getBaseContext(), R.layout.activity_customview, R.id.tv,
                totalRec);
        lv1 = (ListView) findViewById(R.id.listViewQuotes);
        lv1.setAdapter(adapter);

    }

Logcat
11-25 22:43:26.982: E/AndroidRuntime(17543): FATAL EXCEPTION: main
11-25 22:43:26.982: E/AndroidRuntime(17543): java.lang.NullPointerException
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.widget.AbsListView.obtainView(AbsListView.java:2191)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.widget.ListView.makeAndAddView(ListView.java:1840)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.widget.ListView.fillDown(ListView.java:675)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.widget.ListView.fillGap(ListView.java:639)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5128)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4188)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.view.Choreographer.doCallbacks(Choreographer.java:562)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.view.Choreographer.doFrame(Choreographer.java:531)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.os.Handler.handleCallback(Handler.java:730)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.os.Handler.dispatchMessage(Handler.java:92)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.os.Looper.loop(Looper.java:137)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at android.app.ActivityThread.main(ActivityThread.java:5155)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at java.lang.reflect.Method.invokeNative(Native Method)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at java.lang.reflect.Method.invoke(Method.java:525)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:756)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:572)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
11-25 22:43:26.982: E/AndroidRuntime(17543):    at dalvik.system.NativeStart.main(Native Method)`


text:
Q: android TextView onRestoreInstanceState get wrong value My code is like this:
    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.progress = mProgress;
        return savedState;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
            SavedState savedState = (SavedState) state;
            mProgress = savedState.progress;
            super.onRestoreInstanceState(savedState.getSuperState());
    }

The mProgress value is 60 when I pass it to savedState in onSaveInstanceState and I get 0 in onRestoreInstanceState.
if I modify the code
savedState.mProgress = mProgress in onSavedInstanceState to savedState.mProgress = 10 then I got 10 in onRestoreInstanceState.
It's so weird. if I make the mProgress static then I get 60. I don't know what's the matter.

A: Use like this,
@Override
protected void onCreate(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
        mProgress = savedInstanceState.getInt("progress");
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("progress", mProgress);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState != null) {
        mProgress = savedInstanceState.getInt("progress");
    }
}


text:
Q: collection of key-value pairs where key depends on value I have a class MyClass
class MyClass
{
    public string Name { get; set; } // is unique among all instances
    public SomeClass Data { get; set; }
    ...
}

of which I want to store several instances in a collection. I will often need to check if an instance with a certain name exists, and if it does, retrieve that instance. Since iterating through the whole collection is not an option (performance!), I thought of a using a collection of key-value-pairs, e.g. an IDictionary<string, MyClass>.
My program will also allow renaming instances of MyClass (it will not allow renaming if name uniqueness would be violated). But if I rename a MyClass, I will also need to delete the old entry from the dictionary and add the new one (i.e. with the new name) to keep the data consistent.
The problem is that I will have several such dictionaries (which contain subsets of all MyClass instances) all over the place, and it will be hard to keep track of them and consistently update all dictionaries after every renaming.
Is there a way to keep the key-value pairs consistent automatically? I think I heard of a data structure that allows this, which exists at least in C++ (unfortunately, I have no idea how it's called). Basically, it should be a collection where the key is not just a plain string but more like a reference to a string (to the name property in this case), but behaves as if it were a string. Does such a thing exist in C#? Do you have other ideas how to keep the collections consistent?
My only idea is to have a collection of all dictionaries on the highest level of my program and to make the renaming method update all those dictionaries after the actual renaming process. But there must be a better way!

Why this question is not a duplicate of Best way to change dictionary key :
I already know that a dictionary does not allow changing the key. I am instead asking for another data structure that is somehow compatible to key changes (without losing the performance benefit completely), and I am asking for other approaches as well. So my question is much more open to input from any direction, as long as it helps to solve the problem of keeping the data consistent.

A: As far as I understand you, your problem is this:

*

*You have multiple dictionaries, each holds a part of your data

*All your instances should have a unique name throughout all the dictionaries

*When a name is changed:

*

*First, check this name is still unique

*Update it in whatever dictionray it lives in

I think I would tackle this problem a bit differently.
First, add an ID field to the class that would be a Guid / running number, That field should never change from the moment the instance is created.
Next, add another dictionary that would hold only the names and IDs of the instances, it should look something like this:
[{"FirstName": "Guid1"},
{"SecondName": "Guid2"},
{"ThirdName": "Guid3"}]

The rest of your dictionaries will hold the ID as their key, and not the name:
[{"Guid1": {instance1}},
{"Guid2": {instance2}}]

Now when you change the name of an instance, all the names exist in a single dictionary that'll tell you if it already exist. And you need to change it only in the single place, since the rest of the dictionaries rely on a constant value that'll never change.
So say you want to change the name of "FirstName", the names dictionary will look like this:
[{"OtherName": "Guid1"},
{"SecondName": "Guid2"},
{"ThirdName": "Guid3"}]

And the rest of the data doesn't need to change.

A: I don't think there is a native collection to do that. However you can easily create your own by just adding some kind of notification in your base class.
   public class ChangingNameObject
    {
        public delegate void ObjectNameChange(string oldName, string newName);
        public event ObjectNameChange ObjectNameChanged;
        private string name;
        public string Name
        {
            get => name;
            set
            {
                ObjectNameChanged?.Invoke(name, value);
                name = value;
            }
        }
    }

    public class WatchingDictionary
    {
        private Dictionary<string, ChangingNameObject> content = new Dictionary<string, ChangingNameObject>();

        public void Add(ChangingNameObject item)
        {
            item.ObjectNameChanged += UpdatePosition;
            content[item.Name] = item;
        }

        public void Remove(ChangingNameObject item)
        {
            item.ObjectNameChanged -= UpdatePosition;
            content.Remove(item.Name);
        }

        private void UpdatePosition(string oldname, string newname)
        {
            var o = content[oldname];
            content.Remove(oldname);
            content.Add(newname, o);
        }
    }

I only wrote the very basic stuff and you miss all the accessors and enumerators, just add the one you need.
Be very carefull with enumeration though as changing a collection during enumeration will cause a fail (and as the collection is hidden, youu might be doing it without knowing)


text:
Q: pyserial library not found I am getting an import error using pyserial on mac.
I have pip downloaded it and easy installed it but it doesn't seem to be recognised.
This is the error:
File "python.server", line 2, in <module>
    import serial
ImportError: No module named serial

It's not finding any problem with the first line 'import http' so it is definitely something specific to pyserial.


text:
Q: Aurelia Binding to slidebar I am having some trouble trying to figure out the correct way to bind a value in my slidebar that slides out.
Event.html:
<template>

  <require from="./sidebar/event-builder-sidebar"></require>
  <require from="./event-item"></require>

          <event-builder-sidebar containerless data.two-way="?"></event-builder-sidebar>

                  <button type="button" class="btn btn-sm btn-default"> Task Library</button>
                  <button type="button" class="btn btn-sm btn-default"> Add Task</button>

                        <event-item containerless data.two-way="t"></event-item>

</template>

You see where event-item is being looped. It generates multiple cards and when a user clicks on those cards they get a slidebar (event-builder-slidebar) that slides in from the left and allows the user to edit information in the card. I am currently at a loss for the correct way to do this. I am guessing I would need the event that triggers the slidebar to slide in to pass the current data object back up to the parent event.html and into the event-builder-slidebar. That is where I am at a loss to figure out how to do.
import { bindable, bindingMode } from 'aurelia-framework';
import { CssHelper } from '../../../shared/css-helper';

export class EventItem {
  @bindable({ defaultBindingMode: bindingMode.twoWay }) data;

  static inject() {
    return [CssHelper];
  }

  constructor(cssHelper) {
    this.cssHelper = cssHelper;
    this.toggleEdit = e => { this.edit(e); };
  }

  attached() {
    document.addEventListener('click', this.toggleEdit);
  }

  edit(e) {
      // this needs to pass this.data back to event builder sidebar somehow
  }
}

A: Using the containerless attribute is likely gumming things up for you. If you stop using that, you can simply use event binding to bind the custom element's click event to a function on your parent VM that sets a, e.g. selectedEvent property. You can even set it without a VM function directly in the template like this:
<template>
  <require from="./sidebar/event-builder-sidebar"></require>
  <require from="./event-item"></require>

          <event-builder-sidebar containerless data.bind="selectedEvent"></event-builder-sidebar>

                  <button type="button" class="btn btn-sm btn-default"> Task Library</button>
                  <button type="button" class="btn btn-sm btn-default"> Add Task</button>

                        <event-item data.bind="t" click.delegate="selectedEvent = t" ></event-item>

</template>

However, if you really want to use containerless custom elements, then you'll need to fire the click event as a custom event (and you'll end up having a container element anyways it'll just be a div or something). Here is a gist that shows this in action: https://gist.run/?id=eb9ea1612c97af91104a35b0b5b10430
element vm
import {inject, bindable, containerless} from 'aurelia-framework';

@containerless
@inject(Element)
export class Thing {
  @bindable value;

  constructor(element) {
    this.element = element;
  }

  fireClick() {
    let e = new CustomEvent('click', { bubbles: true });

    this.element.dispatchEvent(e);
  }
}

element template
<template>

    ${value}

</template>


text:
Q: Display divs based on browser language with show/hide function (error: nothing shows up) I want to display a paragraph on a website in different languages, depending on the browsers settings (unfortunately it has to be done using jQuery).
So far I have gotten as far as that I can display the language of the browser back to me but when I try to show/hide the div element based on the language it just shows neither.
I have already tried putting "===" instead of "==" and the language code seems to be correct (I tested it with an alert).
What have I done wrong? Heres my fiddle http://jsfiddle.net/o4um72af/4/
var userLang = navigator.language || navigator.userLanguage;
if (userLang == "en-GB") {
     $("#english").show();
}
else {
     $("#english").hide();
}

if (userLang == "de") {
     $("#deutsch").show();
}
else {
     $("#deutsch").hide();
}

A: You're already hiding #deutsch and #english in CSS, so jQuery for this isn't needed. Then your userLang for English us would be something like "en-US" and "de-DE" for German in Germany. You can console.log(userLang) at the end of your code to see this in console. This is what worked for me at least.
Also, the code was just sitting there, not being instructed to fire off, here's an update to your code that does the trick if applied to your jsfiddle, I updated the userLang values, removed the hide methods, and added a document ready function, good luck!
$(function(){
  var userLang = navigator.language || navigator.userLanguage;
  if (userLang === "en-US") {
       $("#english").show();
  }
  if (userLang === "de-DE") {
       $("#deutsch").show();
  }
});

A: Your code to detect language works correctly. To me, it's displaying the English version as I have en-GB language set.
However, what you are doing (at least based on the provided jsFiddle) is hiding both available divs - hiding the #english div if the language is not en-GB and hiding the #deutsch div if the language is not de. So if a user has a different browser language setting (eg. fr or en-US) both divs will be hidden.
Furthermore, you are already hiding the divs via CSS, so there is no need to do the hiding in else parts of the statement.
I would recommend changing code to something like this
var userLang = navigator.language || navigator.userLanguage;

if (userLang == "de") {
     $("#deutsch").show();
} else {
     $("#english").show();
}

That way, you will display the Deutsch div for people with de language setting and English div for everyone else (which is what I imagine you want?)
If the code you have somewhere else does not appear to show any div, like you suggest, then you probably have some other CSS rules or JS hiding both divs which you forgot to include in the fiddle.
Btw, the only difference between the == and === comparison is checking whether the type of both sides of the argument also matches, not just the value. So 5 == '5' would be true (notice, you are comparing an integer with value 5 to a string with value 5) whereas 5 === '5' would not be true - ie. the ===, also known as the strict equality is stricter than the == equality operator :) The strict equality sign is often used when guarding against potential mistakes such as adding a number and a string together (eg. 5 + 3 = 8 - notice both are integers and the result is an integer, but '5' + 3 = '53' - notice, one is a a string and the other is an integer, the result is a string)


text:
Q: Show emberjs computed property in view I am having trouble displaying computed properties in my view
I am learning EmberJS for less than a week. Different tutorials have different coding styles, which is very confusing, so I am following http://coding.smashingmagazine.com/2013/11/07/an-in-depth-introduction-to-ember-js/
I saw some similar posts on stackoverflow but the code is too complex for me to understand, and my question is very basic and no post I have seen just answers that bare basic.
Here is my 'users' handlebars template. It is written in index.html. I am putting only the handlebars script part.

Here is my model
App.ApplicationAdapter = DS.FixtureAdapter;

App.User = DS.Model.extend({
  name         : DS.attr(),
  email        : DS.attr(),
  bio          : DS.attr(),
  avatarUrl    : DS.attr(),
  creationDate : DS.attr()
});

Here is my Controller
App.UsersController = Ember.ArrayController.extend({
  sortProperties: ['id'],
  sortAscending: true, // false = descending

  usersCount: function(){
    return this.get('model.length');
  }.property('@each'),

  NameWithId: function() {
    return this.get('id') + ' -> ' + this.get('name');
  }.property('id', 'name')
});

After executing the script, I can see ID and name, but in the place of NameWithId I get just blank
Even my web console in Firefox shows nothing
In my template I changed
user.NameWithId

to
user.get('NameWithId')

Now I get Parse Error: Expecting 'ID', got 'INVALID'

Using:
jQuery 1.10.2
handlebars 1.0.0
Ember 1.0.0
EmberData 1.0.0-beta3

A: You can place it on the model like sevenseacat said, or you can use an itemController which will wrap up each item in the array with a controller, and that's where you would place this property.
App.UsersController = Ember.ArrayController.extend({
   itemController: 'user'
})

App.UserController = Ember.ObjectController.extend({
  NameWithId: function() {
    return this.get('id') + ' -> ' + this.get('name');
  }.property('id', 'name')
});

A: The computed property should be on the model, not the controller. It's a property of a single user instance, whereas your controller is an ArrayController, for many user instances (hence the @each in the previous computed property declaration).


text:
Q: Finding datasheets for these transistors I have 9 very odd transistors (as I think) that I got from a surprise electronic package from the electronic goldmine. The packaging is the oval metal cases with 2 wires sticking out and the case is the ground (I think). I did a datasheet search and found nothing so I am wondering if anybody has any info on these. I am also wondering if there is any cool circuit I can build with it, and if any are power MOSFETS I could use for a flyback driver (using my 555 PWM generator) Here is the list of what the labels say.
1. Motorola logo
A8W
MEX
8605
2
1587538-1
8734
3
HY-386
40PI
8939
4 Motorola
3007838-00
Mexico
8821
5
12258819
19207
8848
Some are repeats, so that's why there is only 5.

A: The last 4 digit code is the datecode in YYWW format ( year, week#)
Late 80's rock N Roll transistors.  Way past obsolete status, and once upon a time chased by "Shlockers" who sell hard to find parts at crazy prices for military spare parts. Probably broker surplus "dead inventory".

*

*A8W is a Motorola NPN TO-3, 4A 70V

*1587538-1 is a Fairchild NPN TO-3 30A 60V 200W with an Allied Signal PN

*HY386 is a Hyperion audio NPN TO-3. low gain high current  15A 60V 115W

*3007838-00 another power transistor like above.

Unfortunately these are not much use except if you have big heat sinks as an active load. The huge power ratings needed huge heatsinks.
Suggestion
This specsheet is similar to all the above parts.
You might be able to use them as LED light dimmers using DC strings of high power DC LED's or a voltage controlled power resistor. But don't waste too much time with them.

A: The transistors found in any "grab-bag" package are nearly always discarded overstock from product manufacturers. They might even be parts that failed acceptance tests, meaning that they didn't meet their original specs (whatever they were) or are in fact completely nonfunctional.
Product manufacturers often have the semiconductor manufacturer mark the parts with a proprietary "house number" instead of the standard datasheet part number, partly to assist their own inventory control, and partly to obfuscate the circuit design (to prevent copying).
The numbers you have listed look like house numbers, and it's unlikely that you will find the corresponding datasheets anywhere.
What you can do is use an ohmmeter to identify what type (NPN or PNP) they are, and this will also tell you which pin is the base connection. If you can borrow or get access to a transistor curve tracer, you can get some idea of whether they're at all functional and what their low-frequency characteristics might be. But in general, you're going to have to use them as very generic parts, without assuming any special characteristics, unless you test specifically for those characteristics first.
At some point, you're going to have to make a decision as to whether using these transistors is worth the time and effort it takes to characterize them vs. just going out and purchasing a transistor for which you can get the datasheet.


text:
Q: Android: Back to some Activity
Activity1 (not finish) can start Activity2 , Activity2 (not finish) can start Activity3.
And Activity2 and 3 can back to previous activity using
super.onBackPressed();
this.finish();

And I want to know how Activity3 back to Activity1(not refresh) directly and release the memory of Activity2?

A: Intent intent = new Intent(Activity3.this, Activity1.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

This will make the Activity1 be at the top of the backstack, killing all Activities on top of it. Hope this helps.

A: try this
@Override
 public void onBackPressed() {
     startActivity(new Intent(this, UI.class)
     .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
 return;
}

A: try super.finish(); to close 2nd activity.

A: If you want to come back to the existing activity you can use a unique ID and onActivityResult if resultData == ID --> close the second activity (for user it will be seemed like coming back from third activity to the first).
To learn more information about stack of activities, visit google site
Also maybe fragments is suitable for you - and you can simply walk through fragment stack.

A: Activity 2
Intent intent = new Intent(Activity2.this, Activity3.class);
startActivityforResult(intent,0);

When coming back from Activity3 override onBackPressed() and set result when needed
setResult(RESULT_CANCELED);

then override onActivityResult() in Activity2
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 0) {
            if(resultCode == RESULT_CANCELED)
                finish();
        }
    }

This will finish second activity, when result is set. Otherwise you can navigate back and forth like any normal activities.


text:
Q: remember variable when executing function again php Hello I have this function that gives a random value of the array

    static public function addProxy($handle, $r, $url)
    {
        if (!$proxies = TextHelper::commaListArray(ParserConfig::getInstance()->option('proxy_list')))
            return;

        $randIndex = array_rand($proxies);
        $proxy = $proxies[$randIndex];
        $proxysused[] .= $proxies[$randIndex];
        error_log( print_r( $proxysused, true ) );
        curl_setopt($handle, CURLOPT_PROXY, $proxy);
    }

This function is called with
    static public function initProxy($url)
    {
        if (self::needSendThroughProxy($url))
            \add_action('http_api_curl', array(__CLASS__, 'addProxy'), 10, 3);
    }

This function in the same file as addProxy
   try
        {
            newproxy:
            $subida++;
            CurlProxy::initProxy($url);
            $config = ParserConfig::getInstance()->getExtractorConfig();
            $product = self::$extractor->extractProduct($url, $config, null, $formats, $httpOptions, $update_mode);
        } catch (\Exception $e)
        {
            if ($subida !== 3) {
            error_log($subida);
            goto newproxy;
            }
            $error = $e->getMessage();
            $error_code = $e->getCode();
        }

This call is in another file than addProxy
As you can see I need to store the variable
$proxies[$randIndex] in the array variable $proxysused[]
To unset the echoing proxies that were used when calling the function previously.
Currently the code overwrites proxysused and its value always remains at 1 as it does not have variables saved from previous executions.
Any ideas?


text:
Q: What happens with a RISCV LOAD wider than there is memory left? What would be the behavior of the following program?
li t0, 0xFFFFFFFF
lw t1, 0(t0)

Is this implementation (MMU or execution environment) defined? I can't find any mention of this scenario in the RISC-V specification.

A: The RISC-V privileged ISA classify Physical Memory into three types: Main Memory, I/O and Empty.

Empty regions are also classified as I/O regions but with attributes
  specifying that no accesses are supported.

The document goes on saying that contrary to Main Memory (which always support R/W) an I/O region, and therefore an Empty region, can specify which access are supported.

I/O regions can specify which combinations of read, write, or execute accesses to which data widths
  are supported.

Each region has one or more Physical Memory Attribute (PMA) that stated if the region is cached, support atomic operations, it is ordered and which data size is supported.
The PMA of a region must be checked by the hardware and if any constraint is violated a trap or an interrupt is reported:

PMAs are checked for any access to physical memory, including accesses that have undergone virtual to physical memory translation. To aid in system debugging, we strongly recommend that, where possible, RISC-V
  processors precisely trap physical memory accesses that fail PMA checks. Precise PMA traps might not always be possible, for example, when probing a legacy bus architecture that uses access failures as part of the discovery mechanism. In this case, error responses from slave devices will be reported as imprecise bus-error interrupts.

The specification doesn't impose any PMA on empty regions and doesn't define any PMA value, it explicitly states that

As PMAs are tightly tied to a given physical platform's organization, many details are inherently platform-specific, as is
  the means by which software can learn the PMA values for a platform.

What happens when a non-existent RAM address is accessed is left to the specific micro-architecture defined by the implementation.
Usually the memory bus has pull-up/pull-down resistors. In such case reading from a non-existent address will result in a word made of ones or zeros and writing will be ignored.
Depending on the hardware the result can be anything, even an exception signalling a failed transaction on the bus.


text:
Q: I have to check for browser zoom level using MSHTML library in vb.net I have to check for browser zoom level using MSHTML library in vb.net. I have tried making it work in selenium by writing my desired functionality of closing the browser if it is not 100% in catch block however I can't find anything like that in mshtml.
Does anyone have any other suggestion?


text:
Q: How to convert the html5 input button to div tag? In my html5 code, I use this tag to select files to read from.
<input type="file" id="files" name="files[]" multiple />

But this has an browse button and I want to change it to a possibly a div tag so its just a click able element. I don't want to see that default browse button with the text appearing next to it.
Is there a css way to just change it so I don't see the button, yet I can still click it, or do I just have to hide it, and make something else click-able just manually click it, when clicked?

A: <input type="file" id="files" name="files[]" multiple style="display:none"/>
Click Here

works in chrome,IE11,Firefox 27.no js

A: Here is how I've been doing it by using the label to wrap the input: fiddle
HTML

    <input id="upload-file" type="file" />

SCSS
.upload-wrapper {
  display: block;
  position: relative;
  overflow: hidden;
  border-radius: 50%;
  input[type="file"] {
    position: absolute;
    top: 0;
    left: 0;
    height: 0;
    width: 0;
    opacity: .5;
    &:focus {
      outline: 0;
    }
  }
  max-width: 10em;
  img {
    display: block;
    width: 100%;
    height: auto;
  }
  &:hover, &:focus {
    border: 3px solid red;
  }
}

A: this may help
i created a fiddle too
http://jsfiddle.net/S2jht/
in this we add the same function to a div using a line of javascript (and no jquery)
document.querySelector('#fileSelect').addEventListener('click', function (e) {
// Use the native click() of the file input.
document.querySelector('.filer').click();
}, false);

and hide the default input button using css display:none


text:
Q: Show placeholder value using element ui select I'm using Element UI library in Vue.
I have a set of two radio buttons, and also a dropdown list that need to share the same data. I have everything working as expected however when the user selects one of the radio buttons the dropdown is displaying that value.
My end goal is to have the dropdown display the placeholder text unless of course a dropdown value is selected. Possibly a watcher to check if radios are selected and then update dropdown?
<template>

    <el-radio-group ref="selfLanguage" v-model="formData.selfLanguage">

          <el-radio
            id="selfLanguageEnglish"
            label="English"
            name="selfLanguage"
            class="radio--bold"
          />

          <el-radio
            id="selfLanguageSpanish"
            label="Spanish"
            name="selfLanguage"
            class="radio--bold"
          />

    </el-radio-group>

    <el-form-item
      prop="selfLanguage"
      :show-message="false"
      class="form-item--select el-form-item--dropdown"
    >

        Other

      <el-select
        ref="selfLanguageDropdown"
        v-model="formData.selfLanguage"
        name="selfLanguage"
        class="select-box"
        prop="selfLanguageOther"
        placeholder="Please select one"
        :popper-append-to-body="false"
      >
        <el-option label="French" value="french"></el-option>
        <el-option label="Russian" value="russian"></el-option>
        <el-option label="Italian" value="italian"></el-option>
      </el-select>
    </el-form-item>

</template>

A: The dropdown shows the same value because you share the same model as other select. If you want to do some computation with a logic over selfLanguage you can have two separata models (selflanguage , selfLanguageOther) and then define a computed variable to decide which language is going to be final/selected one.
You can use something like this.
const selfLanguage = computed(
  () => language.primaryLanguage ?? language.selfLanguageOther
)


text:
Q: how insert csv data to mongodb with nodejs Hi im developing an app with nodeJS, express and a mongoDB, i need to take users data from a csv file and upload it to my database this db has a schema designed with mongoose.
but i don know how to do this, what is the best approach to read the csv file check for duplicates against the db and if the user (one column in the csv) is not here insert it?
are there some module to do this? or i need to build it from scratch? im pretty new to nodeJS
i need a few advices here
Thanks
this app have an angular frontend so the user can upload the file, maybe i should read the csv in the front end and transform it into an array for node, then insert it?

A: Use one of the several node.js csv libraries like this one, and then you can probably just run an upsert on the user name.
An upsert is an update query with the upsert flag set to true: {upsert: true}.  This will insert a new record only if the search returns zero results.  So you query may look something like this:
 db.collection.update({username: userName}, newDocumentObj, {upsert: true})

Where userName is the current username you're working with and newDocumentObj is the json document that may need to be inserted.
However, if the query does return a result, it performs an update on those records.
EDIT:
I've decided that an upsert is not appropriate for this but I'm going to leave the description.
You're probably going to need to do two queries here, a find and a conditional insert.  For this find query I'd use the toArray() function (instead of a stream) since you are expecting 0 or 1 results.  Check if you got a result on the username and if not insert the data.
Read about node's mongodb library here.
EDIT in response to your comment:
It looks like you're reading data from a local csv file, so you should be able to structure you program like:
function connect(callback) {
    connStr = 'mongodb://' + host + ':' + port + '/' + schema;  //command line args, may or may not be needed, hard code if not I guess
    MongoClient.connect(connStr, function(err, db) {
        if(err) {
            callback(err, null);
        } else {
            colObj = db.collection(collection); //command line arg, hard code if not needed
            callback(null, colObj);
        }
    });
}

connect(function(err, colObj) {
    if(err) {
        console.log('Error:', err.stack);
        process.exit(0);
    } else {
        console.log('Connected');
        doWork(colObj, function(err) {
            if(err) {
                console.log(err.stack);
                process.exit(0);
            }
        });
    }
});

function doWork(colObj, callback) {
    csv().from('/path/to/file.csv').on('data', function(data) {
        //mongo query(colObj.find) for data.username or however the data is structured
        //inside callback for colObj.find, check for results, if no results insert data with colObj.insert, callback for doWork inside callback for insert or else of find query check
    });
}


text:
Q: How to read Adb Dumpsys alarm output I'm setting multiple alarms on repeat through alarm manager, they are working fine on the day they got set but not repeating at all. I have updated my code but I can't wait all day to check if the code is even working or not so I have tried adb shell dumpsys alarm command but I don't know how to read the output properly and how to extract the times of alarms being set. I have followed some links to understand the output but none is specifiying how to check the exact time of the alarm being set.
here is my output

my main code where i'm setting the alarm
 final int _id = (int) System.currentTimeMillis();

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

   //  alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,AllTime[i],AlarmManager.INTERVAL_DAY,
        //        PendingIntent.getBroadcast(this, _id, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,AllTime[i],AlarmManager.INTERVAL_DAY,
                PendingIntent.getBroadcast(this, _id, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));

and this this the broadcast receiver
public void onReceive(Context context, Intent intent) {

    String[] myStrings = intent.getStringArrayExtra("strings");
    Log.i("okk", "cathing intent values through break" + Arrays.toString(myStrings));

    createNotification(context, "Time is here baby", "this is the notification text", "Alert");
    Log.i("okk", "cathing intent values through break" + Arrays.toString(myStrings));

}

public void createNotification(Context context, String msg, String msgText, String msgAlert) {
    final int _id = (int) System.currentTimeMillis();  // unique request code

    // will open mainActivity on notification click, can change it
 //   PendingIntent notificationIntent = PendingIntent.getActivity(context, _id, new Intent(context, MainActivity.class), 0);  // changed from 0 to _id

    PendingIntent notificationIntent = PendingIntent.getActivity(context,0, new Intent(context,MainActivity.class),0);
    NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.cast_ic_notification_play)
            .setContentTitle(msg)
            .setTicker(msgAlert)
            .setContentText(msgText);

    // now intent we want to fire when noti is clicked

    mbuilder.setContentIntent(notificationIntent);

    // how person is notified

    mbuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);

    mbuilder.setAutoCancel(true); // noti dismisble when user swipe it away

    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService((Context.NOTIFICATION_SERVICE));

    //    Log.i("okk", "NOTIFIED " + intent.getExtras());

    notificationManager.notify(1, mbuilder.build());  // changes from 1 to _id
       }

A: maybe it can help you, I've created an opensource project with a GUI version of the "adb shell dumpsys alarms" command. You can find it here:
https://github.com/Dottorhouse/DumpsysAlarm
Hopefully it will help you figure out what's wrong


text:
Q: Javafx rectangles in quadtree won't dissappear/be created - using mouseevents I've made a program that creates a simple visual quadtree - basically starts with a grid of 4 rectangles which can each be divided into a smaller version of a grid containing 4 smaller rectangles. PROBLEM: Sometimes though, one of the original 4 squares refuses to divide, while the others continue working. The issue only occurs after I've tried right-clicking several times when the grid is already combined to one base square that cannot be combined any further.
I've attached a .setOnMouseClicked() handler on each square that calls my divide() method on left-click and combine() on right-click. Furthermore the handler method are set to check if the square that's been clicked belongs to a grid of squares before it tries to call the combine method, and this is where I struggle to understand what goes wrong.
My theories so far:

*

*Perhaps the issue relates to how javafx handles visual objects, but I hoped that using .getChildren().remove(Object o); was the right way to remove something from the scene. It seems to work most of the time though.

*Maybe the way I'm changing what's displayed and not isn't really thread safe, and that using an eventHandler interrupts the object removal - but the problem occurs when I'm clicking slowly as well as rapidly.

The class hierarchy consists of one abstract Cell class that can either be a Grid or a Square. Excuse me for dropping a lot of code here, but javafx debugging confuses me a lot some times, so honestly I got no idea which part of the code is responsible, thus I pasted the entire thing.
Cell.java:
public abstract class Cell {
    int x, y, w, h, id; //id is a reference the index in a grid this cell belongs to - it's used when a square replaces itself with a grid
    Pane pane;
    Cell parent;

    public Cell(Pane pane, Cell parent, int x, int y, int w, int h, int id) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.id = id;
        this.pane = pane;
        this.parent = parent;
    }

    public void divide(){}
    public abstract void remove();
}

Grid.java
public class Grid extends Cell {
    Cell[] grid = new Cell[4];

    public Grid(Pane pane, Cell parent, int x, int y, int w, int h, int id) {
        //The constructor works as it should, just some unnecessary maths to avoid confusion over rounding
        super(pane, parent, x, y, w, h, id);
        int ver = x + w/2;
        int hor = y + h/2;
        grid[0] = new Square(pane, this, x, y, w/2, h/2, 0);
        grid[1] = new Square(pane, this, ver+1, y, x+w-1-ver, h/2, 1);
        grid[2] = new Square(pane, this, x, hor+1, w/2, y+h-1-hor, 2);
        grid[3] = new Square(pane, this, ver+1, hor+1, x+w-1-ver, y+h-1-hor, 3);
    }

    public void combine(){
        remove();
        parent = new Square(pane, parent, x, y, w, h, id);
    }

    public void remove(){
        for(Cell c : grid){
            c.remove();
        }
    }
}

Square.java:
public class Square extends Cell {
    Rectangle rect;

    public Square(Pane pane, Cell parent, int x, int y, int w, int h, int id) {
        super(pane, parent, x, y, w, h, id);
        rect = new Rectangle(x, y, w, h);
        rect.setFill(Color.RED);
        pane.getChildren().add(rect);
        rect.setOnMouseClicked(e ->{
            if(e.getButton().equals(MouseButton.PRIMARY))
                divide();
            else if(e.getButton().equals(MouseButton.SECONDARY) && parent != null && parent.getClass().equals(Grid.class))
                ((Grid)parent).combine();
        });
    }

    @Override
    public void divide(){
        if(w > 3 && h > 3){
            remove();
            if(parent != null && parent.getClass().equals(Grid.class))
                ((Grid)parent).grid[id] = new Grid(pane, parent, x, y, w, h, id);
            else
                parent = new Grid(pane, parent, x, y, w, h, id);
        }
    }

    public void remove(){
        pane.getChildren().remove(rect);
    }
}

In the main file, the parent is initialized as null for the base Cell to signalize that it cannot be divided from the mouse handler:
@Override
public void start(Stage primaryStage) throws Exception {
    Pane pane = new Pane();
    pane.setBackground(new Background(new BackgroundFill(Color.BLACK, null, null)));
    cell = new Square(pane, null, 50, 50, 700, 700, 0);
    cell.divide(); //cell is a Cell type instance variable
    primaryStage.setTitle("SquareSception");
    primaryStage.setScene(new Scene(pane, 800, 800));
    primaryStage.show();
}

The outlined squares refuses to divide despite many left-clicks

The top right square refuses to divide, the others would

A: First of all you should change the type of parent to Grid.This avoids the unnecessary type checking. (Every parent is a Grid after all.)
The real issue however is, that you never properly update the parent grid in Grid.combine. You need to do this update in order for the remove method to properly find all child squares:
public void combine(){
    remove();
    Square newParent = new Square(pane, parent, x, y, w, h, id);
    if (parent != null) {
        parent.setChild(newParent);
    }
}

public void setChild(Cell newChild) {
    grid[newChild.id] = newChild;
}


text:
Q: "gam print aliases 2>$null" not Showing All Aliases I need to list all aliases in my domain (groups and users aliases) using Google GAM and I'm using the command below:
gam print aliases 2>$null

However, it's not bringing me an alias (l.suporte@domain.com) from a group that I can see through the command:
gam info group si-suporte

Output:
Group Settings:
 id: 03hvwe3312ki
 email: si-suporte@domain.com
 name: SI-SUPORTE
 directMembersCount: 8
 description: L.SUPORTE -SI
 adminCreated: True
 aliases:
  suporte@domain.com
  l.suporte@domain.com
 whoCanJoin: CAN_REQUEST_TO_JOIN
...


text:
Q: Ruby idiom for do_two_simple_things if something_is_true For instance, this takes 4 lines which is too much space for such a simple operation:
if something_is_true
  puts 'error'
  return
end

this one is a one-liner but looks awkward.
if something_is_true; puts 'error'; return; end

Can we do something like
# it would be great if this would work because it is short and readable
puts 'error' and return if something_is_true

A: I'm not sure why you think space is at such a premium that your original code is "too much."  Give your code room to breathe, and let it take the space it needs.  Getting too tricky in order to "save space" is a false economy.  The most important thing is that your code be readable and understandable.  Your original code looks great to me.

A: I agree with @NedBatchelder that your original code is probably best. Others have pointed out that in your particular example, you can use return puts 'error'.
Still, for the sake of learning, you can group multiple statements with parentheses, and therefore use a small number of statements in places where you could otherwise use only one.  You said:
# it would be great if this would work because it is short and readable
puts 'error' and return if something_is_true

You can do this with:
(puts 'error'; return) if something_is_true

A: This is kind of awful but I think it will work because puts returns nil:
puts 'error' || return if something_else

A: In this specific case, return without a value will return nil; as this happens to also be the return value of puts, you can get the same effect with just:
return puts "error" if something_else

A: Someday you will probably care less about how many cycles you can spend in a single line of code.  I would use the if-end block because it is simple, clear, and... you know, that's what it's there for.

A: I'd recommend never to use ; to join statements, it tends to be unreadable. But still there are other approaches, two ideas: first one, join error(msg, return_value = nil) and return:
return(error("Message")) if something_is_true

return(error("Message", value_to_be_returned)) if something_is_true

Second one, in Ruby it's idiomatic to signal problems using exceptions, so you can write this perfectly idiomatic one-liner:
raise MyException.new("human explanation of the error") if condition

The same idea used in an assignment:
link = doc.at_css(".content a.link") or raise MyException.new("msg")


text:
Q: Trying to find a sci-fi short story - different perspective on devil and god I am trying to find a sci-fi story I read in early 1980s sci-fi anthology. It was told from the perspective of snake/devil hiding from a megolomaniac God. Any leads much appreciated. It was written in the first person, from the view point of Satan. I remember him as a snake, hiding from a mad God who has convinced the world that light and sound are necessarily good and darkness and quiet are bad. It's kind of a rumination - I don't recall any actual action.

A: This has been confirmed as Harlan Ellison's story "The Deathbird". Published March, 1973
Hugo Award for Best Novelette, Locus Award for Best Short Story
The wise and gentle snake-like creators of the Earth lost a galactic arbitration, and possession of the planet passed from their race to the Mad One. The sole caretaker left behind was Dira, the Snake, powerless to defend himself from the slurs and myths of the other. Yet he had the final remedy, to be used only at the end, the Deathbird.
This is an emotionally powerful story that examines, among other things, terminal illness and assisted suicide. The decision to call the Deathbird lies with the man Stark, who has been reincarnated through the ages, and not with the Snake or the mad one. Nathan Stark remembers his last life, and his mother, dying in great pain, demanding that he "Use the needle." And now the Earth is in pain...

A: This answer was written before the querant added that they remember the devil as being a snake. They have indicated that the following story is not what they were looking for.

Could this be the short story "Displaced Person" by Eric Frank Russell?
The narrator meets a strange person while sitting on a bench at the setting of the sun.

He glided out of the gathering dusk and seated himself at the other end of my bench and gazed absently across the lakes towards the Sherry Netherland.
(...)
My mind speculated about him the way minds do when momentarily they've nothing else to bother them. A European refugee, it decided. A great surgeon or sculptor or something like that. Perhaps a writer, or painter. More likely the latter.

The stranger confides that he is a refugee.

"You're not a native of this New York?" I prompted.
"No." Resting long, slender hands upon his stick, he gazed meditatively forward. "I have no country. I am a displaced person."
(...)
"In these days it is an all too familiar story," he said. "A leader became so blinded by his own glory that no longer could he perceive his own blunders. He
developed delusions of grandeur, posed as the final arbiter on everything from birth to death, and thereby brought into being a movement for his overthrow. He created the seeds of his own destruction. It was inevitable in the circumstances."
(...)
"I organized that opposition. I still think it was justified. But I dare not go back."

Then he gets up to leave.

 "My name," he murmured softly, "is Lucifer."

According to the ISFDb, it was published first in the September 1948 issue of Weird Tales and has been collected in a number of anthologies which can be found through its entry in the ISFDb.


text:
Q: List index out of bounds with a TListView I'm confused when I try to insert a String into a TListView using insert(int,String).
Here is my code:
void __fastcall TFrmNewPeta::showDefaultRute()
{
    std::string line;
    std::ifstream ifs;
    wisata.savedefaultT4Awal("DefaultDataAwal");
    wisata.savedefaultT4Jarak("DefaultDataJarak");
    wisata.savedefaultT4Tujuan("DefaultDataTujuan");
    ifs.open("DefaultDataAwal");
    try{
         if(ifs.is_open())
         {
             for(int indexfile=0;std::getline(ifs,line);++indexfile)
             {
                ListItemnew = ListView1->Items->Add();
                ListItemnew->Caption = String(IntToStr(indexfile+1));
                ListItemnew->SubItems->Insert(indexfile,line.c_str());
                //cbxtest->Items->Insert(indexfile,line.c_str()); //successfull

             }
         }
    }__finally{
        ifs.close();
    }
}

With this the compiler says "List Index out of bounds (1)"
I've been tried for many times to find the way out but I got the same result.
But this one made me wonder, because when I try to test with ComboBox its works well.
cbxtest->Items->Insert(indexfile,line.c_str());

If there something wrong with my code?

A: try this
void __fastcall TFrmNewPeta::showDefaultRute()
{
    std::string line;
    std::ifstream ifs;
    wisata.savedefaultT4Awal("DefaultDataAwal");
    wisata.savedefaultT4Jarak("DefaultDataJarak");
    wisata.savedefaultT4Tujuan("DefaultDataTujuan");
    ifs.open("DefaultDataAwal");
    try{
         if(ifs.is_open())
         {
             for(int indexfile=0;std::getline(ifs,line);++indexfile)
             {
                ListItemnew = ListView1->Items->Add();
                ListItemnew->Caption = String(IntToStr(indexfile+1));
                ListItemnew->SubItems->Add(line.c_str());
                //cbxtest->Items->Insert(indexfile,line.c_str()); //successfull

             }
         }
    }__finally{
        ifs.close();
    }
}

I hope this help your problems


text:
Q: Creating symlinks with modified path in batch script? The idea behind this question is simple but I'm new to batch scripts so the nuances are making it impossible for me. I need to create a set of symlinks to replicate the contents of several source directories, which share a common parent directory, into a target directory. Example:
SrcDirParent
    SrcDirA
       FileA
    SrcDirB
       FileB
       SubDir
          FileC

Which using symlinks should create:
DstDir
    FileA ~
    FileB ~
    SubDir
        FileC ~

Using ~ to show a symbolic link. SrcDirParent and DstDir are read as absolute paths from an external file. I don't know what files/folders will be in SrcDirParent, and some of the relevant directories might already exist in DstDir while others do not. If they do exist, I need to merge the symlinks with the existing content.
The barrier that I'm currently hitting is with th filepaths. I planned to use two for loops like this:
for /d %%M in (%SRC%\*) do (
    for /r %%F in (%SRC%\%%M\*) do (
        mklink %DST%\%%F %SRC%\%%M\%%F
    )
)

But this requires relative filepaths for %%M and %%F and these variables are being filled with absolute paths. I'm not sure how to fix that.
Another issue that I'm anticipating is when the SRC and DST have conflicting filepaths - I don't want to overwrite existing paths with symlinks.
Hope this was the right place to post this. Thanks in advance.

A: After much trial and error, I found a solution:
setlocal ENABLEDELAYEDEXPANSION

for /d %%M in (%SRC%\*) do (
    pushd %%M
    for /r %%F in (*) do (

        set temp1=%%F
        set temp2=!temp1:%%M=!
        set temp3=!temp2:%%~nxF=!

        if not exist "%DST%!temp3!" (
            mkdir "%DST%!temp3!"
        )

        mklink "%DST%!temp2!" %%F
    )
    popd %%M
)

It uses "pushd" and "popd" to change the directory for the inner loop, "!string:find=replace!" for modifying the directory names, "exist" to check for existing folders before creating a new one, and "EnableDelayedExpansion" to make all the string operations work correctly. Assumes you have SRC and DST variables set already.


text:
Q: Caluclate needed heap size needed for serialization In my current Java EE project I've got a quite common task: Load objects from database using Hibernate, transfer them in another object structure (based on a XSD) and serialize it using JAXB. To simplify the scenario imagine the XML I want so serialize is a file with information records to requests we get. In theory there can be infinite information records to the requests, but I estimate a pessimistic but still realistic number of records I have to serialize.
I first made a rough estimate of the resulting XML file size and got to 292MB (about 9KB per single record). I already expected that the file size will outrange the maximium heap size of 50MB a java request is allowed to gather by our operators / server admins. So I need to find a limit where to split the records into several processes and files. I know that I can't just cut down the number of records to serialize in one file by the resulting file size, meaning I can't calculate "okay x records are 200 MB then x/4 records are 50MB and that's fits with the maximum heap". For sure I have to keep the loaded objects and the object structure I serialize in mind.
But how can I roughly estimate the needed heap size by the final size a single record so I can serialize a maximum number of records without running into memory issues? As said a rough calculation is enough, like "if your final size per record is 6KB then you need 12KB (ratio 1:2) to process it in your process.


text:
Q: given we have $p$ votes for $A$ and $q$ votes for $B$, what is the probability that after $k$ of the votes counted ,$A$ will be ahead? I was inspired by Bertrand's ballot problem I discovered today thanks to a comment in this site.
My question is basically this: given we have $p$ votes for $A$ and $q$ votes for $B$, what is the probability that after $k$ of the votes counted, $A$ will be ahead ?
Example: $p=100$ $q=80$. Q: what is the chance $A$ will have more votes than $B$ after 36 (20%) counted votes ?
When I think of it, I have even some problem calculating the probability of an exact result: for example, what is the chance for 20-16 after 36 votes ?

A: It is like taking out $k$ votes out of an urn that contains $p$ votes for $A$ and $q$ votes for $B$ and we are dealing with hypergeometric distribution.
An expression for the probability that $A$ will be ahead is:$$\binom{p+q}{k}^{-1}\sum_{i>\frac12k}\binom{p}{i}\binom{q}{k-i}$$
I have no closed expression for this summation.
If $p=100$ and $q=80$ then the chance for $20-16$ after counting $36$ votes is:$$\frac{\binom{100}{20}\binom{80}{16}}{\binom{180}{36}}$$


text:
Q: Adding a short audio bit to the end of a movie For Valentines day I get to pick the movie we watch for the night and I want to add a little something cute to the end of the movie. Just a brief bit of audio saying like a sentence. Is there an easy way to splice in a brief but of audio? I will need to add it before the credits hit, or just cut out the credits (credits don't matter to us).
I know I can simply load the movie up in a video editor, add the audio in the spot I want and then render out the movie, but seeing as it is a full sized 1080p movie that could be a lengthy render time.

A: With ffmpeg you can easily copy the audio stream out.
ffmpeg -i movie.mp4 audio.wav

Then, load up the audio file in Audacity or your favorite audio editor, and save it. Now merge it back in:
ffmpeg -i movie.mp4 -i audio.wav -c:v copy -c:a aac -strict experimental -map 0:v -map 1:a output.mp4

This will copy the video bitstream over (-c:v copy) and encode the audio again using ffmpeg's internal AAC encoder. The original audio will be replaced since it only takes the video stream of the first input (-map 0:v) and the audio stream of the second input (-map 1:a).
It will probably take a few seconds only, since the video stream isn't touched.

A: The most simple way I can think of would be to de-mux the audio (snag the audio seperate off the video). edit the audio in an audio editing program, then re-mux it.  While audio editing replace an existing audio or mix in the desired audio, leaving the length of the audio and video the same.
Using Direct stream re-muxing the video would go untouched, as the audio (which also could be direct streamed) would be added back to the set.
Another method would be to "append" create a video using (or converted to) the exact same bitrate, the exact same codec and the exact same everything.  If you managed to get all the the technical details of the AV exact an append could be done (again) without touching the original (direct stream).  Most programs would not respond to this added chunk being audio only, that is why you create a video, even if the picture is blank.
The above things can be done with Ffmpeg and virtualdub, the ease of accomplishing the task would be highly dependant on the original codecs used and complexity of the original AV stream. Example: VBR audio streams are not the same bitrate, giving you only error on append. Multitrack and 6.1 audio and all that fun stuff can make editing the audio much more than a valentine gimick.
(That means if you have not already started , you wont have it done for this years valentines day:-)
Many of the programs and methods that would make this process more simple, would re-code the video, By re-coding the video your in control of all the Technical details of the video, and appends will go as planned, muxing and mixing in new items go as planned because everything is re-coded the same. Re-coding high bitrate videos, using proper codecs and settings would not degrade the video/audio as much as it does when they are already chrunched severly for webplay or webtransport.
Another method to keep from destroying the original quality of the video, would be to compress the final output way less, that way additional losses and artifacts are not added (as much) to the video because your not attemptting to squeese it back in the same can it came out of.  Just check the ability of the playback device to handle the datarate , and it would still be fine.
A playlist and a skip button would not be the same at all.  But if you personally made a short video (instead of simple audio) tested a slight of hand skipping before presenting,, and delievered it well, it might be appretiated the same, and be a lot less work/fails.


text:
Q: middleware function error in expressjs I unable to run node main file in terminal
and I am using handlebar as template engine
getting this weird error
 I did npm install all dependencies which is required. but still getting this error.
/home/mohsin/Desktop/mohsin/react/react-web-app/node_modules/express/lib/application.js:210
throw new TypeError('app.use() requires a middleware function')
^

TypeError: app.use() requires a middleware function

this is error screenshot please have look https://i.imgur.com/c6zoaA6.png
My app.js file
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-sessions');
const passport = require('passport');
const mongoose = require('mongoose');

// Port env
const port = 3000;

// Route files
 const index = require('./routes/index');
const user = require('./routes/user');

  // Init App
  const app = express();

  // View Engine
    app.engine('handlebars', exphbs({defaultLayout: 'main'}));
   app.set('view engine', 'handlebars');

   // Static Folder
   app.use(express.static(path.join(__dirname, 'public')));

   // Body parser middleware
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false}));

     // Express Session
      app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
 }));

 // Start server
 app.use('/', index);
 app.use('/user', user);

  // Start Server
 app.listen(port, () => {
 console.log('Server started on port '+port);
 });

A: There is no package named 'express-sessions'
instead use express-session
so its not returning any method. which app.use can call as method.
Here is package


text:
Q: change logo while scrolling based on section class i need some help with my jquery script ,
i need to change logo img while scrolling  in my wordpress site (im using elementor) so if section with class =" dark logo " the dark logo appear else the white logo , i tried it a script it work for some sections and i can"t figure out the reason of the problem
im stuck here , can anyone help me plz , im newbie in js world

var whitelogo = "https://svgshare.com/i/UZP.svg";
var blacklogo = "https://svgshare.com/i/U_S.svg";
var initial = "https://svgshare.com/i/UYs.svg";
$.fn.isInViewport = function () {
  let elementTop = $(this).offset().top;
  let elementBottom = elementTop + $(this).outerHeight();

  let viewportTop = $(window).scrollTop();
  let viewportBottom = viewportTop + $(window).height();

  return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).scroll(function () {
  $('section').each(function ()
    {

  if ($(".dark").isInViewport()) {
    console.log("dark");

    $(".logo ").attr("src", blacklogo);
  }
    else  {
    console.log("light");

    $(".logo ").attr("src", whitelogo);
  }
})
  });
body {
  margin: 0;
}

.logo {
  position: fixed;
  width: 100px;
  margin : 35px;

}

#section1 {
  background: #0b46eb;
  width: 100vw;
  height: 100vh;
}

#section2 {
  background: #ffc703;
   width: 100vw;
  height: 100vh;
}
#section3 {
  background: #1f262b;
   width: 100vw;
  height: 100vh;
}


text:
Q: Implement infinite scrolling in Androidviewclient I am trying to implement Androidviewclient 5.1.1 for app which has implement scrolling of listitems. I want to scroll upto the point all the entries of the list have been finished.
That is scrollable becomes FALSE.
How should I proceed to do this ?
Which property or ANDROIDVIEWCLIENT should I check for?

A: I used culebra GUI (from AndroidViewClient 9.2.1) to generate this script scrollable.py while running the Contacts app on the device.
culebra -pVCLGo scrollable.py

To scroll the list I used the drag dialog as described in culebra: the magical drag.
Once I exited the GUI and the script was generated, I remove all the other Views but the ListView and added the while loop. So besides the while loop, pretty much everything was automatically generated.
The final script is now:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013-2014  Diego Torres Milano
Created on 2015-01-21 by Culebra v9.2.1
                      __    __    __    __
                     /  \  /  \  /  \  /  \
____________________/  __\/  __\/  __\/  __\_____________________________
___________________/  /__/  /__/  /__/  /________________________________
                   | / \   / \   / \   / \   \___
                   |/   \_/   \_/   \_/   \    o \
                                           \_____/--<
@author: Diego Torres Milano
@author: Jennifer E. Swofford (ascii art snake)
'''

import re
import sys
import os

try:
    sys.path.insert(0, os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
    pass

from com.dtmilano.android.viewclient import ViewClient

TAG = 'CULEBRA'

_s = 5
_v = '--verbose' in sys.argv

kwargs1 = {'ignoreversioncheck': False, 'verbose': True, 'ignoresecuredevice': False}
device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1)
kwargs2 = {'startviewserver': True, 'forceviewserveruse': False, 'autodump': False, 'ignoreuiautomatorkilled': True}
vc = ViewClient(device, serialno, **kwargs2)

device.Log.d(TAG, "dumping content of window=-1",  _v)
vc.dump(window=-1)

def doSomething(view):
    if view.getClass() == 'android.widget.TextView':
        print view.getText()

while True:
    device.Log.d(TAG, "finding view with id=android:id/list",  _v)
    android___id_list = vc.findViewByIdOrRaise("android:id/list")
    # check if scrollable
    if not android___id_list.isScrollable():
        break
    vc.traverse(root=android___id_list, transform=doSomething)
    device.Log.d(TAG, "Scrolling",  _v)
    device.dragDip((185.0, 499.0), (191.0, 175.5), 200, 20, 0)
    vc.sleep(1)
    device.Log.d(TAG, "dumping content of window=-1",  _v)
    vc.dump(window=-1)

NOTE: in this case, the script never exits because the ListView in Contacts never changes its scrollable property, which I hope your app
  does as you mentioned in your question.

EDIT 1
Added tree traversal for ListView children as requested in one of the comments
EDIT 2
Added doSomething() transform method
EDIT 3
Now check the class


text:
Q: Plugin 'maven-failsafe-plugin:2.22.1' not found I am getting 'maven-failsafe-plugin2.22.7' not found while importing https://github.com/serenity-bdd/screenplay-pattern-todomvc.git and setting it up as Maven project in Intellij idea. Any idea what could be the issue?
Edit: the solution was to run the code using mvn clean verify command in the terminal. Using this i receive no error whatsoever.

A: Try to Invalidate Caches. File -> Invalidate Caches / Restart...


text:
Q: How do I make my div overlap on top of everything, rather than pushing everything beneath it down? Within this HTML, I set up a code so that if you click an image link, a div comes up. Whenever the div comes up, some items get pushed down, and some rest on top of the div.
How can I make it so that this div that comes up on click just overlaps everything and doesn't push it down, etc. ?
Any help would be great!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

        Fill this space with really interesting content.

A: The css style z-index is what you are looking for.

A: You should use top: 200px; instead of margin-top when you use position:absolute;


text:
Q: __metaclass__ not worked when create class with type("Test", (Base,), {'__metaclass__':Meta, ...}) cls = type("Test", (Base,), {"__metaclass__": Meta, "a": 1, ...})

I want to make some check for the attrs in the 3rd argument with Meta class, but this seem not worked, is there any other method?

A: Meta-class is a subclass of type. So creating a type of a metaclass is calling the meta class:
cls = Meta("Test", (Base,), {"a": 1, ...})

A: You should create your Test class by calling the Meta (a.k.a. type.__class__.__new__(Meta, "Test", (Base,), {"__metaclass__": Meta, "a": 1}).
If you have a dictionary with possible __metaclass__, you can use the following code:
members = {"__metaclass__": Meta, "a": 1, ...}
metaclass = members.pop('__metaclass__', type)
cls = metaclass("Test", (Base,), members)