What algorithms do DNS servers use for faster lookups?

Question: DNS servers have to be fast in order to avoid latency. What algorithms do DNS Servers use to reduce latency? Are they any caching mechanisms that could be effectively used to improve speed?
Answer: Latency is a huge problem with DNS. The slowest part of DNS is reaching out across the 'Net and querying other servers. Any caching a client or server does will speed up the process. In fact, that's exactly what happens.
When a DNS server responds to a query, the answer comes back with a TTL (time-to-live). The TTL value tells the querying server how long to cache the response. The TTL value is set by the authoritative server for the zone. Typically it's about a day, but can vary depending on how often the administrator thinks the DNS entry might change.
The DNS client (which might be another server acting on behalf of an end user) caches the response and will flush it out of its cache when the TTL has been exceeded. Until that time, subsequent queries for that particular hostname will come out of the cache.
I used to run my own DNS server at home so all my computers on my LAN could take advantage of the local cache. But I discovered that it was better to use my ISP's DNS servers. They benefitted from the queries of thousands of customers and were much more likely to have more cached answers than my servers ever could.
Comment: Hello Sir, I have seen your youtube videos and learned well during my college days. I wanted to know some more information regarding it. As you have mentioned, ISP's DNS server will cache the domain name. But what algorithm they will perform to cache and to lookup? I think hash will be the best choice.
Comment: What algorithm do DNS server use for caching domain name and for searching the same domain name from it's cache?
Answer: I know this question already has an accepted answer, but there's much more you can do than just caching.  For example:

Use BGP to establish a network of geographically distributed servers, reachable via Anycast.  This can reduce the average number of hops that a DNS query packet has to traverse.
Eliminate latency-containing infrastructure.  For example, host your DNS servers with your ISP or at a large Internet peering point instead of at the slow end of a WAN.
Avoid CNAME records; prefer A records instead.  CNAMEs often require multiple queries to resolve.
Use a robust, high-performance commercial service, such as UltraDNS.


Grub Installation failed into target

Question: I tried to install Ubuntu 14.04 on Windows 10 having created partitions for swap area and root. But when I am installing ubuntu it keeps saying "failed to install grub-efi-amd64-signed" into target. I have tried several times but it keeps saying the same thing and installation fails.
Please help me as how to proceed further.
Answer: I've come across this problem when Installing Mint 17.3, Lubuntu 16.04 and Ubuntu LTS 16.04 on a 16GB Flashdisk from a live USB.
You see when I created the Live USB, I used rufus making bootable USB, I also tried using Mint's Create Bootable USB tool. Same results, failure to install grub...
The problem was that all these tools were creating the Live USB to be compatible with UEFI boards. Thus when you boot your live USB in UEFI mode, your installer will create GPT disk rather than MBR, and for that you need a dedicated partition where you put /boot/efi.
However I wanted MBR, so I started the computer with my Live USB, opened gparted and erased then formatted my installation target, which like I said earlier was a 16GB Flash disk (I like having a portable OS), when you create the new partitions, select MBR theme. After you're done with partitioning your target, install Linux as you would normally do and that dreaded error message won't appear at the end of the installation.
Good Luck

Grub Installation failed into target


Probability of losing the bet

Question: Consisting of five matches.
Each game, the probability of winning is 1/2
The probability of a draw is 1/6
The probability of losing is 1/3
After five matches, if you lose three times (or more) consecutively, you lose the bet
What is the probability you lose the bet
What i have tried is 1-binomcdf(5,1/3,2). I got 17/81 but that seems wrong to me.
Answer: Write L for lose (an individual match), and N for don't lose. The probability of L is $1/3$, and the probability of N is $2/3$.
You lose the bet with the following patterns: LLL, NLLL, NNLLL, and LNLLL.
The probability of LLL is $(1/3)^3$, the probability of NLLL is $(2/3)(1/3)^3$, and so on. Add.
Comment: Shouldn't the winning cases also be included?
Comment: @MohamadMisto they are included. Winning is a form of not losing (D).
Comment: Ah sorry didnt notice that
Comment: The question is about losing the bet. But maybe your question is about for example my LLL. I could have broken that up into $4$ cases, LLLLL, LLLLN, LLLNL, and LLLNN. The sum of the probabilities will turn out to be $(1/3)^3$, but it is much more efficient to stop at LLL, for whatever happens next we will lose the bet.
Comment: @MohamadMisto: Thanks for the comment. I unwisely chose D for don't lose, forgetting that D is also the first letter of the word draw. Fixed.

Probability of losing the bet


12.04 - Steam is running in the system monitor, but will not open

Question: I am on Ubuntu 12.04, and have installed Steam and had it running previously but for the past 2-3 days, whenever I try to run Steam it opens a dialog box that says Verifying installation and then it closes and nothing happens. When I try to run Steam through terminal it gives me this:

Running Steam on ubuntu 12.04 32-bit
  STEAM_RUNTIME is enabled automatically
  Installing breakpad exception handler for appid(steam)/version(1378500910_client)
  Installing breakpad exception handler for appid(steam)/version(1378500910_client)
  Installing breakpad exception handler for appid(steam)/version(1378500910_client)
  unlinked 0 orphaned pipes
  removing stale semaphore last operated on by process 3130 with name 0eBlobRegistryMutex_F8AC220EF1CF9E5DA3A138E83771D64C
  removing stale semaphore last operated on by process 3130 with name 0eBlobRegistrySignal_F8AC220EF1CF9E5DA3A138E83771D64C
  removing stale semaphore last operated on by process 3130 with name 0emSteamEngineInstance
  removing stale semaphore last operated on by process 3130 with name 0eSteamEngineLock
  Installing breakpad exception handler for appid(steam)/version(1378500910_client)
  [0914/114403:WARNING:proxy_service.cc(958)] PAC support disabled because there is no system implementation

Any suggestions would be helpful.
Thanks!
Comment: Actually I have found that if you remove the appcache with "rm -Rf ~/.steam/steam/appcache", it fixes the issue, must have been a Steam update that broke it.
Answer: Just run rm -Rf ~/.steam/steam/appcache
Comment: While this may be the correct answer, in future, when you post an answer, could you explain how running code samples will help. This may help other in the future determine whether this is the route they should take.


app is asking for AppleID when being run

Question: I am updating my iOS app with the Apple suggested transaction VerificationController code to verify in-app purchases due to the recent "hack" published that allowed people to purchase in-ap purchases without paying due to spoofed receipts from spoofed Apple servers.
I have everything integrated, and am now testing.  I have run the app several times and the verification stuff has run several times.
I want to test everything about purchasing including starting with a fresh brand new app and AppleID.  So I deleted the app completely off my testing device.  I created a brand new "test user" AppleID in iTunes Connect.  I went to the Settings app on my test device, went to Store, and changed the default AppleID for the device to this newly created AppleID.
I re-run the app from Xcode with the debugger, which re-installs the App onto the testing device and runs it fresh.
The problem is that almost immediately on launch, the testing device puts up the AppleID password Alert-type view and asks for the password for the old AppleID that I originally used to test everything including the original in-app purchase and the verification for it.  It does not ask for the password for the new device AppleID as set in the Settings app under store.
When I run it as a new app, the verification code does not run and no code from any of my routines that do anything with the Apple StoreKit stuff is run except for a solitary
[[SKPaymentQueue defaultQueue] addTransactionObserver:observer];

(observer is my delegate object for the StoreKit stuff and is created but no routines in it run except init and init does nothing except set a static variable for itself to create a singleton type class)
For checking purposes, I also added in
NSLog(@"in App Delegate, payment queue transactions are %@", [[SKPaymentQueue defaultQueue] transactions]);

which shows no old transactions hanging around.
I have no clue on why it has started to ask for my AppleID of the original test user when the App is newly installed, the AppleID for the store for the device is different, and I can identify no code being run that accesses the StoreKit (except as mentioned above).
ANy insight into this would be appreciated.
ETA:  Touching CANCEL in the password dialog does not cause any extra code to run in the app and does not prevent the app from running.
If I then go into the in-app purchase screen (where the app queries the store for available in-app purchases), it asks for the password again in the same way, on the OLD AppleID.  I can cancel and nothing seems to happen.  If I actually touch "restore purchases" button in my app, it then asks for the password on the new AppleID as set up in the Store settings.  I have not gone past this point as I want to understand what is going on and don't want to mess things up by completing/attempting the restore or purchase under the new AppleID.
Thanks
Comment: Have you solved it somehow ?
Comment: @bluesm  I never did solve the problem and no longer really use that device I was having the issues with.  Sorry.  I may eventually try and come back to it as I still have that device in a drawer...
Answer: I had exactly the same problem and struggled for hours to solve it.
As previously mentioned, StoreKit works system-wide and the system keeps asking for login for any transaction for which
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];

has not been called. I was using RMStore, looked at the source code I found this suspect lines:
if (error.code != RMStoreErrorCodeUnableToCompleteVerification) {
    // If we were unable to complete the verification we want StoreKit to keep reminding us of the transaction
    [queue finishTransaction:transaction];
}

This is probably what happened:

I first purchased the product with my test Apple ID
I deleted the product for test purposes
I tried to purchase it again. At this point I entered wrong credential and RMStore did not call [[SKPaymentQueue defaultQueue] finishTransaction:.
The app started asking for login at every startup.

I tried to login with a different test account but still the same alert asking to login with the old Apple ID. I also deleted the Apple ID on iTunes Connect but this did not help.
Finally I managed to solve by Restoring (not Purchasing) the product with the same account.
I don't know if there is another way to solve this issue (i.e. to reset the StoreKit queue). Anyway always remember to call finishTransaction in your code.
Comment: Thank you!  I just logged in as my test user, hit my "restore" button.  Then quit and restarted and the login didn't happen.   The timing of the login window was so weird.   Even debugging line-by-line it consistently happened at something completely unrelated to StoreKit.
Answer: StoreKit.framework works system-wide, so the Apple ID that gets displayed doesn't have anything to do with your app, and reinstalling the app will not have any influence.
However, you can log out from the iTunes Store / App Store:

Tap Settings → iTunes & App Stores
Tap the Apple ID signed in (button at the top)
Tap "Sign Out"

When you then use your app again, StoreKit should prompt for both email and password.
Comment: I don't know if you saw the comments that the AppleID is not related to the one stored in settings ("the AppleID for the store for the device is different")
Comment: It's almost as if iOS has stored information somewhere saying "this app is requesting previous purchase information" and can't help but asking for it on subsequent loads. Only deleting the app got rid of it for me.
Comment: @chadbag Ah, sorry, didn't understand you correctly there. Not sure what's going on then. :(
Comment: @AndreasLey  no harm no foul ;).  The device I had this issue with is no longer my main device, though I have not worked on this app since due to other paying gigs, so I am not sure where I stand on this issue at the moment.  I'll be back on it shortly unless people come out of the woodwork with paying work...
Answer: Steps to Fix:

Starting at the App Store, pull up the multi-task bar and tap the Settings app.
Scroll down and tap 'General'.
Scroll down and tap 'Date & Time'.
If the 'Set Automatically' switch is ON, turn it OFF.
Tap 'Set Date & Time'.
Tap the field that says "[day of the week], [month][day], 2013".
Adjust the year wheel to say "2012" and back out of the Date & Time section.
Multi-task back to the App Store and attempt to download the app again.
Tap 'Cancel' on the "Cannot connect…" modal.
Return to the native Settings > General > Date & Time > Set Date & Time.
Go back to the month, date, year wheels and change the year to "2030".
Back out to the home screen and launch the App Store.
A "Cannot connect to the Store" modal should appear right away.
Tap 'OK' and then multi-task back to Settings.
Return all the way back to the month, date, year wheels again and change the year back to "2013.
Multi-task back to the App Store and attempt to download the app again.


Lock the Computer over Night and on Weekends

Question: Given my computer runs on Ubuntu, and I can install on it whatever I like: If I would want to prevent myself from using the computer in the night and on the weekend, what software solution comes closest to putting the computer into a box locked with a timer-lock?
Answer: pam_time is the built-in way to restrict access based on time.  It can prevent logins, but existing sessions would continue.  Otherwise, people seem to script their own solutions.
Links

How do I restrict my kids' computing time?
Log on hours for users
How can I allow access to SSH only at a specific time?
How to lock yourself out of the primary account temporarily?
how to restrict time used for using computer in Ubuntu
http://manpages.ubuntu.com/manpages/focal/en/man8/pam_time.8.html


Disable grails 2.0 resources processing, after deploy

Question: I've packaged my app into a war (by grails war), and as I see, it have built all required resources. For example I have coffeescript code, that have translated to into js dir. Same for scss, etc. I mean I have all static resources, that can be served directly (and I want to server it from Nginx, not Tomcat)
But after deploying this war into Tomcat, I'm getting errors like:
ERROR plugins.DefaultGrailsPluginManager  - Error configuring dynamic methods for plugin [resources:1.1.6]: java.lang.NoSuchMethodError: org.mozilla.javascript.Parser.parse(Ljava/io/Reader;Ljava/lang/String;I)Lorg/mozilla/javascript/ScriptOrFnNode;
org.codehaus.groovy.runtime.InvokerInvocationException: java.lang.NoSuchMethodError: org.mozilla.javascript.Parser.parse(Ljava/io/Reader;Ljava/lang/String;I)Lorg/mozilla/javascript/ScriptOrFnNode;
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:680)
Caused by: java.lang.NoSuchMethodError: org.mozilla.javascript.Parser.parse(Ljava/io/Reader;Ljava/lang/String;I)Lorg/mozilla/javascript/ScriptOrFnNode;
    at com.yahoo.platform.yui.compressor.JavaScriptCompressor.parse(JavaScriptCompressor.java:312)

This one is from yui-minify-resources plugin. Similar thing happening for coffeescript-resources plugin. Maybe it's because there is something wrong with this plugins, but it's crazy, because I already have all resources, prepared/processed/compiled to static files. I don't need this plugins on production mode.
How I can disable all this resource plugins on production mode? Is it possible?
PS same thing for grails run-war
Comment: any luck ? Whats is the resolution ? I am facing the same issue.
Comment: @UmairSaleem don't remember how exactly, but was fixed by 'hacking around classloader' and upgrading all things to newer versions
Answer: This is likely due to coffeescript-resources and yui-minify-resources both having a dependency to Rhino javascript engine, but the YUI team has made some modifications to their version of Rhino, which causes it to be incompatible with vanilla Rhino. You have two options:

Try hacking around with classloaders
Don't use YUI compressor
Comment: Related to option 2: we're shortly releasing a minifying plugin that uses google's closure compiler to get around this limitation: https://github.com/conmio/google-closure-compiler-resources


Requester/InvalidNameIDPolicy Error with SimpleSAMLPHP SP and ADFS IDP

Question: After looking all over the Internet, particularly

ADFS 2.0 InvalidNameIDPolcy
Using SimpleSAMLphp to Authenticate against ADFS 2.0 IdP
Requester/InvalidNameIDPolicy

I tried all the suggested modifications to authsource.php and metadata php. Nothing worked.
Here is my authsource.php
'default-sp' => array(
    'saml:SP',
    'privatekey' => 'saml.pem',
    'certificate' => 'saml.crt',
    'idp' => 'http://domain.com/adfs/services/trust',

I used the XML to simpleSAMLphp metadata converter to generate the saml20-idp-remote.php
So when I access the page, SimpleSAMLPHP correctly redirects me to the IDP login page. I decoded the SAML Request:
<samlp:AuthnRequest
    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    ID="_4e03333c7aa76314d965e05f8fcdd3e1f4c5be96c8"
    Version="2.0"
    IssueInstant="2014-12-11T19:41:50Z"
    Destination="https://domain.com/adfs/ls/"
    AssertionConsumerServiceURL="https://sub.domain.com/simplesaml/module.php/saml/sp/saml2-acs.php/default-sp"
    ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST">

    <saml:Issuer>
        https://su.bdomain.com/simplesaml/module.php/saml/sp/metadata.php/default-sp
    </saml:Issuer>
    <samlp:NameIDPolicy Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient" AllowCreate="true"/>

</samlp:AuthnRequest>

After logging in with a valid test account, I'm redirected back to my site with the error.
SimpleSAML_Error_Error: UNHANDLEDEXCEPTION
Backtrace:
0 /var/www/html/igt_s3k/web/simplesamlphp/www/module.php:179 (N/A)
Caused by: sspmod_saml_Error: Requester/InvalidNameIDPolicy
Backtrace:
3 /var/www/html/igt_s3k/web/simplesamlphp/modules/saml/lib/Message.php:385 (sspmod_saml_Message::getResponseError)
2 /var/www/html/igt_s3k/web/simplesamlphp/modules/saml/lib/Message.php:495 (sspmod_saml_Message::processResponse)
1 /var/www/html/igt_s3k/web/simplesamlphp/modules/saml/www/sp/saml2-acs.php:96 (require)
0 /var/www/html/igt_s3k/web/simplesamlphp/www/module.php:134 (N/A)

I tried setting different NameIDPolicy but none of them worked.
    //'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress',
    //'NameIDPolicy' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient',
    //'NameIDPolicy' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',
    //'NameIDPolicy' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified',

Thanks!
Comment: I was getting a similar error for having 'store.type' => 'memcache', instead of phpsession
Answer: Yeah. In a fit of anger and frustration. I set NameIDPolicy to null and everything works. FML
'default-sp' => array(
    'saml:SP',
    'privatekey' => 'saml.pem',
    'certificate' => 'saml.crt',
    'idp' => 'http://comain.com/adfs/services/trust',
    'NameIDPolicy' => null,

Comment: Great thanks. This bug still exists in the latest simplesamlphp on github June 2016
Comment: I am another one of those people you just saved a bunch of time - Thank you !
Comment: @YarGnawh You just saved me so much time and energy! Thank you so much! Works with Moodle/saml2 Auth plugin, if anyone is hitting the same spot I did.
Comment: First thing I Googled. I'm wondering how long I would have burnt on this
Comment: According to https://github.com/simplesamlphp/simplesamlphp/issues/771#issuecomment-433412601 you should set it to `false` with modern SimpleSAML version.
Answer: As of SimpleSAML v1.15.0, setting the NameIDPolicy to NULL is not supported, and will result in an error.
If you do not set the NameIDPolicy, the SAML Request will default to:  urn:oasis:names:tc:SAML:2.0:nameid-format:transient, which can cause integration problems.
In order to not explictly send the NameIDPolicy in the auth request, apply the patch found here, and set the NameIDPolicy to false in the authsources.php config file.
'NameIDPolicy' => false

Comment: this is the valid answer now
Comment: Just as a note: This option has to be set in the `config/authsources.php` within the configuration of your SP (see below https://stackoverflow.com/a/27451231/336311).
Comment: After applying the patch in Message.php and setting the NameIDPolicy to FALSE worked for me, also we need to make sure we have a proper privatekey and certificate file for the signing
Comment: Thanks @BurninLeo - I have edited the answer to add that information too.
Answer: According to http://social.technet.microsoft.com/wiki/contents/articles/4038.ad-fs-2-0-how-to-request-a-specific-name-id-format-from-a-claims-provider-cp-during-saml-2-0-single-sign-on-sso.aspx
you should use the default value of unspecified
'NameIDPolicy' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified',
Comment: After adding 'unspecified' as suggested here, once I got the attributes response i could see it said the NameId had `Format urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress`

So I just added this as the new NameIdPolicy (i.e. .....:emailAddress) and it is working now


How can I help the homeless children?

Question: Spontaneously, a bunch of children in my village in "Banished" (PC, via Steam) have become homeless. Two were students, one is a small child (2 years old).

What I think happened, is that their parent died by misadventure. (In this village, people in all sorts of professions have been killed by falling rocks. I'm not sure how vendors, traders, fishermen, and farmers all seem to be wandering in the way of rock falls, but that's beside the point here.)
Anyway, in an attempt to mitigate it, I built some more houses. People moved in, and the two students stopped being homeless -- but this child remains. I've also got a boarding house that's sitting empty. He's not hungry (he stops by random houses and gets fed), but winter is coming and I'd rather he not freeze to death.
Here's his info:

Other than the fact that he's homeless, he seems to be a perfectly happy, normal child ... and I'd kind of like for him to stay that way.
How can I give this child a home?
Comment: You have empty houses, right?
Comment: Yes. After the children first became homeless I unpaused a bunch of houses and built them out. I also have a completely empty boarding house (though I don't think that's useful outside of with nomads)
Comment: Didn't mention this in my answer, but boarding houses are for families, basically the same as a house/stone house. (That's according  to the wiki.) I would assume that the same rules apply -- that a child wouldn't live there alone. I really only use the boarding house for nomads, so it's empty most of the time, unless too many kids come of age at once before I can build them all houses.
Answer: It's not enough to have a house for them - a child can not/will not live by themselves. I've had this scenario before, a couple times (it's dangerous working in the quarry!) and I know one time it happened relatively soon before the child was scheduled to age-up into an adult, so they survived long enough to do that, then moved into a house as an adult. The other time, I believe it was one of the few times I let nomads settle into my village, and the child ended up moving in with one of them. I don't know if another child coming-of-age into adult phase would adopt them, but that wouldn't surprise me given the other two solutions I've seen. Granted this was a while ago -- I assume that the mechanics wouldn't have changed since then, but no way to know. Maybe I'll start a fresh game up and try it... this has got me missing the game again!

How can I help the homeless children?


Deployment using TFS 2012 of SQL Project Not including Post deploy script

Question: Deploying SQL (SSDT) projects to SQL 2012 from TFS 2012 Visual Studio 2012 using the TFS build controller.   All projects have successfully deployed and pushed Post Deploy scripts to the server.  (this is a test server where we are testing the deployment of a migration from 2008 to 2012).  I needed to recreate the job (which is in the post deployment script) so I asked the deployment manager to drop the job and re-run the deploy.  The post deployment script did not run and was not included in the generated deployment sql on the TFS server.
Comment: Not sure what you're talking about when you talk about jobs and deployment managers.  I deploy SSDT projects using SqlPackage.exe and DACPAC's
Comment: I have my environment set up so dev sql projects are on continuous deployment to the dev server and when I am ready to deploy to QA or DEV I deploy using the build manager on the TFS server.
Comment: Can you look inside the dacpac file generated to verify that it has a postdeploy sql file and that it's correctly populated? I don't recall seeing the post-deploy scripts not running nor an option to prevent that.
Comment: The dacpac file for that project has a Model.sql but not a PostDeply.sql  -- however the source for that project has a script that is marked as Post Deployment.  Other project's dacpac files contain both sql files.
Comment: I did see the related question that you helped with (http://stackoverflow.com/q/16981612/236348) and as a precaution did remove all comments from that script, but it still does not include the script in my deployment, or the DACPAC that is generated.
Comment: Can you generate a dacpac manually through building the project and verify that there's a postdeploy script in that file?  Is it possible that your build process isn't picking up the correct version of the project?
Comment: Never mind... when I removed comments, the build action got changed to "None"  switched it back to "Post-Deploy" and all is right with the deployment now.
Comment: @PeterSchott if you want to submit an answer for this, I will mark yours as the correct answer.  Thanks!
Comment: I appreciate the offer, but mostly glad you got it solved. :) You actually found the issue, though seems odd that the build action was changed.
Answer: database Project not running Post Deployment scripts
See the linked question for the answer.  I removed comments.  When I did this the Build Action reverted to "None" I checked later and fixed this by setting to "Post-Deploy" and without the comments, it worked.


django-elasticsearch-dsl suggest not working

Question: I have created the following document using django-elasticsearch-dsl.
@registry.register_document
class QuestionDocument(Document):
    class Index:
        name = 'questions'

    class Django:
        model = QuestionModel
        fields = ['title', 'text']

Now when i try to do a suggest with below command
QuestionDocument.search().suggest("questions", "text", completion={'field': 'title'}).to_queryset().all()

I get the following error:
 elasticsearch.exceptions.RequestError: RequestError(400, 'search_phase_execution_exception', 'Field [title] is not a completion suggest field')

What am i doing wrong here? and how can i fix it? I tried to find a tutorial in the package documentation but couldn't find anything.
Comment: `Field [title] is not a completion suggest field` implies that your `title` field is not of type `completion` which is required in order to use it in a suggest query. Can you show your mapping ?
Comment: For Django model fields, django-elasticsearch-dsl automatically creates mappings to elasticsearch, but i don't know how to create a new mapping on elasticsearch using django-elasticsearch-dsl.
Answer: Field [title] is not a completion suggest field implies that your title field is not of type completion which is required in order to use it in a suggest query.
You need to define your QuestionDocument class like this instead:
@registry.register_document
class QuestionDocument(Document):

    title = fields.CompletionField()             <--- add this

    class Index:
        name = 'questions'

    class Django:
        model = QuestionModel
        fields = ['text']                        <--- remove title here

Comment: I deleted the indexes too, still not working but i assume this should work. Think i just wont use django_elasticsearch_dsl, sucks anyway. Thanks for the help!
Comment: This returns error saying that the field cannot be redeclared. The exact error message: `django_elasticsearch_dsl.exceptions.RedeclaredFieldError: You cannot redeclare the field named 'title' on QuestionDocument`
Comment: Fixed, of course, you also need to remove it from the fields declaration in the `Django` class
Comment: This still gives error, saying that title is not a Completion suggest field. `elasticsearch.exceptions.RequestError: RequestError(400, 'search_phase_execution_exception', 'Field [title] is not a completion suggest field')
`
Comment: Yes, you probably need to delete your index and let Django recreate it with the new field definition
Comment: 2 days passed and is still haven't found a proper solution to this problem. This is getting very frustating
Comment: There is no time guarantee over here, people are helping in best effort mode ;-)


Change to Application Setting is not showing up at runtime

Question: I have an application that's dealing with a required list of files it has to manipulate when run.  I wanted to add a couple of files to this list.  The list of files is stored in a setting.  The scope of the setting is "Application".  I added my two files to the list (via project properties -> settings), and saved everything.  My files now appear there.  My files are showing up in the app.config for this project under ApplicationSettings.
But when I run the application this line of code:
StringCollection requiredFiles = mySettings.UpdatePackageRequiredFiles;

Does not include my files.
mySettings is the right type; it's the project where the settings exist.  Further, there is nowhere in the project UpdatePackageRequiredFiles is being written to and you can't write to an Application scope setting at run-time anyway (or so I understand).
To spice up the mystery a little bit, there are 3 files appearing in the list whose existences are a complete mystery.  They do not appear when viewing the settings in the designer, or in the source file.  So what am I missing?
Answer: It turns out there is a configuration file with an identically named setting that the application was getting the list of files from.


Allow hold block to unblock more than one agent type

Question: So, I'm currently sending two different agents (each from their own source blocks) to a common queue. In that queue I use agent comparison in order to prioritize one agent over another.
View descriptive Image here:

However, in an upcoming hold-block, I cannot seem to unblock the next unit in the queue which is a different agent-type from the first (even though I have set it to "isBlocked = False" when the previous unit exited seize-delay-release). After that, the agent type that first entered service is the only one that can operate throughout the simulation. The other agent-type is stuck in the queue.
Any ideas on how I can get the other agent-type through the Hold-block?
Answer: The hold block will work independently of the agent types in the queue ahead of it.
You should not be using isBlocked = false to 'open ' or 'close' the hold.  This code simply returns if the hold block is blocked or not.

You should use block for blocking and unblock for unlbocking

Here is a small working example where

the hold block is set to initially blocked = false
blocking the hold on the On Enter code of the hold block using self.block()
unblocking the hold at the last delay using the On Exit code with hold.unblock()

and most importantly it uses two different agent types to proof that it can handle multiple agents types.
Comment: Great solution. Thanks for your effort!

So if I understood correctly, using the "isBlocked" variable did only return a boolean, but didn't actually perform a "block" or "unblock" method?


Trig Substitution quadrant diagram Confusion

Question: Evaluate $\, \displaystyle \int _{-1}^{-1/2} \frac{dx}{\sqrt {4x^2-1}}$.
$My\ work:-$
substituting $\, \displaystyle 2x=\sec (\theta),\, \,$
$\Rightarrow \displaystyle  \displaystyle \int \frac{dx}{\sqrt{(2x)^2-1}} \displaystyle = \displaystyle  \frac{1}{2}\int \frac{ \sec (\theta )\, \tan (\theta )\, d\theta }{\sqrt{\sec ^2(\theta )-1}} $
$\Rightarrow \displaystyle \int \frac{ \sec (\theta )\, \tan (\theta )\, }{2\, |\tan (\theta )|} \,  d\theta$
now since$\displaystyle \, -1\leq 2x = \sec (\theta )  \leq -\frac{1}{2}\ $ we have quadrant II and III where $\sec (\theta )\leq 0.\,$
$Question:-$  1. In solution they given a diagram for IIIrd quadrant and Yes i know when we calculate sec we get same 2x, but i am confused how'd they come up with this diagram ?

and here's my Diagram, it will really  helpful if someone please point out mistakes in my diagram

sorry for such Naive question
Comment: $\sec \theta = 2x \implies \cos\theta = \frac{1}{2x}$ and then use $\sin^2\theta + \cos^2\theta = 1$ to find $\sin\theta$. That explains their diagram.
Comment: @MathLover stupid question, but my diagram is also representing $\sec \theta = 2x$
Answer: You have made mistake in your second step . You denoted $ 2x = \sec { \theta}$ .
As $x \ge {-1} $, $2x \ge {-2}$ , therefore , $\sec { \theta} \ge {-2}$ . Therefore , $\cos { \theta} \le {{-1} \over 2}$. Now proceed.
Comment: $x = \frac{\sec (\theta )}{2}\ $ now its alright ??


How do I add a value from a callback into a new element with setAttribute?

Question: I need to add the value of a callback into my setAttribute. How do I do that?
This value is necessary to get data out of a table at a later moment.
This is the code:
row.forEach(function(row) {
         var subchapname = document.createElement("div");
         subchapname.setAttribute("id", "subchaptertitle");
         subchapname.setAttribute("subid", '"+row+"');
         subchapname.setAttribute("onclick","{ alert('You are not going to believe this!') } ");
         subchapname.textContent = row.subname;
         rows.appendChild(subchapname);

Basically, this means:
callback = row
This callback needs to be added to subchapname.setAttribute("subid", '"+row+"');
Is this possible?
This is the actual result:

bos in brand
```
</code>
Comment: What value do you want the "subid" attribute to contain eventually? The row callback doesn't actually return a value, it just sets a bunch of attributes and then appends a div with some text.
Comment: Thx for your response :) I actually need the id (which I called subid) from that row. And that row comes from a sqlite-database this way: ```db.all("SELECT subname FROM chaptree WHERE (chapname='" + chapname + "') ORDER BY suborder", function(err,row)```
Comment: You should just be able to do `subchapname.setAttribute("subid", row)` or `subchapname.setAttribute("subid", row.someProperty)` What kind of data structure does `row` have? Can you console log it and update the question?
Answer: subid is not attribute to store data in it, so you can not add a attribute like this to a html-tag and fill it with a value (Of course writing a string into it, would work, but is this what you need?). But you can add datasets if you use html5. So use this solution to store your rows-value in the dataset-property of subid.
If row is a object and you want to see the the stringified value of the Object use JSON.stringify before storing it in the dataset
row.forEach(function(row) {
  var subchapname = document.createElement("div");
  subchapname.setAttribute("id", "subchaptertitle");
  subchapname.dataset.subid = row;
  // subchapname.dataset.subid = JSON.stringify(row);
  subchapname.setAttribute("onclick","{ alert('You are not going to believe this!') } ");
  subchapname.textContent = row.subname;
  rows.appendChild(subchapname);
});

Your Element should now look like this:

Or if you used JSON.stringify:

To log the value to the console, (after you added the tag to the DOM) do something like this:
console.log(document.getElementById('subchaptertitle').dataset.subid);

In case you used JSON.stringify, now use something like this:
console.log(JSON.parse(document.getElementById('subchaptertitle').dataset.subid));

Comment: Thanks for your absolutely brilliant help! I am still learning to program in JavaScript and i didn't know about the dataset property. Your solution and explanation helped me very much! I can now use the values in the dataset to make other calls. Again, thank you very much for your help!!


Declare a component with generic type

Question: Is it possible to declare a component with a generic type in Angular 4?
The following code causes build errors:
export class MyGenericComponent<T> implements OnInit {
    @Input()  data: BehaviorSubject<T[]>;

    //...
}

The error when executing ng serve is:
ERROR in C:/.../my-generic.module.ts (5,10): Module '"C:/.../my-generic.component"' has no exported member 'MyGenericComponent'.

Example:
The following example is an attempt to implement a generic data table where @Input() data changes from one component 'calling this component' to another.
The question is could BehaviorSubject<any[]> be changed to BehaviorSubject<T[]> where T would be the generic type passed to the component?
@Component({
  selector: 'my-data-list',
  templateUrl: './data-list.component.html',
  styleUrls: ['./data-list.component.css']
})
export class DataListComponent implements OnInit {
  @Input()  data: BehaviorSubject<any[]>;
  @Output() onLoaded = new EventEmitter<boolean>();

  private tableDataBase : TableDataBase = new TableDataBase();
  private dataSource : TableDataSource | null;

  constructor() { }

  ngOnInit() {
    this.tableDataBase.dataChange = this.data;
    this.dataSource = new TableDataSource(this.tableDataBase);
    this.onLoaded.emit(true);
  }
}

class TableDataBase {
  dataChange: BehaviorSubject<any[]> = new BehaviorSubject<any[]>([]);

  get data(): any[] {
    return this.dataChange.value;
  }
}

class TableDataSource extends DataSource<any> {

  constructor(private tableDataBase: TableDataBase) {
    super();
  }

  connect(): Observable<any[]> {
    return Observable.of(this.tableDataBase.data);
  }

  disconnect() {}
}

Comment: @jonrsharpe I am trying to implement a generic component that lists data. The type of the data model may change depending on the page using this component. I edited my question to give an example to where I am using the generic type in the class
Comment: What's the problem you're trying to solve with this?
Comment: How would the framework know what the generic argument should be for the component?
Comment: @jonrsharpe You mean that it's a bad concept to work with generic components? Technically, I could work with the type _any_ instead of a _generic_ type, but would it be a good practice?
Comment: It's not really clear what you're trying to achieve, hence the comment above. Without the context, like an example of two concrete `T`s you'd like to abstract out, this is likely an XY problem (see e.g. http://xyproblem.info).
Comment: @jonrsharpe I've just added an example in my post, I hope it could help
Comment: I understand the idea of a generic *class*, but how can a *component* do this? Surely the bindings will be different for each T? Sure you can extract common methods to a superclass, but beyond that it's unclear what you expect.
Answer: You can also access the Type parameter through the ViewChild like this:
export class Bazz {
  name: string;

  constructor(name: string) {
    this.name = name;
  }
}

@Component({
  selector: 'app-foo',
  template: `<div>{{bazz?.name}}</div>`,
  exportAs: 'appFoo'
})
export class FooComponent<T> {
  constructor() {}
  private _bazz: T;

  set bazz(b: T) {
    this._bazz = b;
  }

  get bazz(): T {
   return this._bazz;
  }
}

@Component({
  selector: 'app-bar',
  template: `<app-foo #appFoo></app-foo>`,
  styleUrls: ['./foo.component.scss'],
})
export class BarComponent<T> implements OnInit {
  @ViewChild('appFoo') appFoo: FooComponent<Bazz>;

  constructor() {}

  ngOnInit() {
    this.appFoo.bazz = new Bazz('bizzle');
    console.log(this.appFoo.bazz);
  }
}

Comment: Actually angular is smart enough to figure out the `T` from inputs as well. Lets say you have `Input() data: T` in your generic component. When you use that component and assign `[data]="someTypedDataVariable"` the angular compiler will use the type of `someTypedDataVariable` to instanciate the generic component. This is how angular material table (based on cdk table) works. This paired with the angular language service will ALSO provide you with type safety + typeahead iniside mat-table column definitions. For reference: https://github.com/angular/components/blob/master/src/cdk/table/table.ts
Comment: So how to you use `T` type argument of the `BarComponent`? It's still unclear what do you expect to receive as an argument, when `BarComponent` is instantiated? It's make sense to use generic concrete class when you are controlling its instantiation (so you can control what argument to pass). But in case of component - it's the angular framework itself which instantiates it - and the framework is not aware of your parameter and will not be able to pass something making sense
Answer: You can declare it, but cannot use it directly. You can do something like this:
export abstract class Form<T> implements OnInit, OnChanges {
  someMethod() { throw 'Dont use directly' }
  otherMethod() { return 'Works!'; }
  // Note that below will cause compilation error
  //   TypeError: Object prototype may only be an Object or null: undefined
  // You cannot use protected in this usecase
  protected anotherMethod() { }
}

@Component({})
export class ModelOneForm extends Form<ModelOne> {
  someMethod() { return this.otherMethod(); }
}

Comment: Hmm `@Componet?` ?
Comment: This method works, but I am still looking for more generic form of a component: Instead of using `...extends Form`, I am looking for something like `export class ModelOneForm extends Form`, and this code throws a compilation error with the message `Cannot find name 'T'`
Comment: @KarolDepka, should be a type; i fixed it. :)
Answer: You can consider this way. Create an interface for the data such as following:
interface ListItem {
  info: string;
  ...
}

Transform the data that you want to list to comply with the interface and thus can be interpreted by the ListDataComponent. Your ListDataComponent can then list the data according to the properties in the interface.
import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'data-list',
  templateUrl: './data-list.component.html',
  styleUrls: ['./data-list.component.scss']
})
export class DataListComponent implements OnInit {
    @Input() public items: ListItem[];

    constructor() {
    }

    ngOnInit() {
    }
}

Answer: I would recommend creating a parent list component with multiple child components for each type of data displayed, then use [ngSwitch] and *ngSwitchCase to determine what to display.
@Component({
  selector: 'app-list',
  template: `
    <ng-container *ngFor="let item in list$ | async" [ngSwitch]="item.type">
      <app-list-item-one [item]="item" *ngSwitchCase="listItemType.One"></app-list-item-one>
      <app-list-item-two [item]="item" *ngSwitchCase="listItemType.Two"></app-list-item-two>
    </ng-container>
  `
})
export class ListComponent extends OnInit {
  list$: Observable<ListItem[]>

  constructor(
    private listApi: ListApiService
  ) { }

  ngOnInit() {
    this.list$ = this.listApi.getList(...)
  }
}

@Component({
  selector: 'app-list-item-one',
  template: `
    {{ item.aProperty }}
  `
})
export class ListItemOneComponent {
  @Input() item: ListItemOne
}

@Component({
  selector: 'app-list-item-two',
  template: `
    {{ item.bProperty }}
  `
})
export class ListItemTwoComponent {
  @Input() item: ListItemTwo
}

export class ListItem {
  id: string
}

export class ListItemOne {
  aProperty: string
}

export class ListItemTwo {
  bProperty: string
}

Comment: This looks like a cleaver approach to me, rather than forcing the consumer to pick the correct component for the job. I don't know why it was downvoted.
Answer: I did something similar to Jun711.  I created an interface, and then my component uses that interface.  Then I just extend the interface for the other classes.  I just pass in an array of a type that extends the interface.
export interface INameable {
    name: string;
}

export interface IPerson extends INameable { title: string; }
export interface IManager extends INameable { Employees: IPerson[]; }

@Component({
    selector: 'nameable',
    templateUrl: './nameable.component.html',
    styleUrls: ['./nameable.component.scss'],
})
export class NameableComponent implements OnInit {

    @Input() names: INameable[] = [];
    @Output() selectedNameChanged = new EventEmitter<INameable>();

    constructor() {}
    ngOnInit() {}
}

then usage is pretty simple:
<nameable [names]="PersonList" (selectedNameChanged)="personChangedHandler($event)"></nameable>
<nameable [names]="ManagerList" (selectedNameChanged)="mangagerChangedHandler($event)"></nameable>

The downside is that the containing component has to determine the full type, but the upside is my components become more reusable as I follow Liskov & ISP.

Declare a component with generic type


Prove that meas$(A)\leq 1$

Question: Let $f:\mathbb R\to [0,1]$ be a nondecreasing continuous function and let $$A:=\{x\in\mathbb R : \exists\quad y>x\:\text{ such that }\:f(y)-f(x)>y-x\}.$$
I've already proved that:
a) if $(a,b)$ is a bounded open interval contained in $A$, and $a,b\not\in A$, then $f(b)-f(a)=b-a.$
b)$A$ contains no half line.
What remains is to prove that the Lebesgue measure of $A$ is less or equal than $1$. I've tried to get estimates on the integral of $\chi_A$ but i went nowhere further than just writing down the integral. I'm not sure whether points a) and b) are useful, but i've reported them down for the sake of completeness so you can use them if you want.
Thanks everybody.
Comment: Observe that in your result a) you also have $f(b) - f(a) \leq 1$ due to the range of $f$.
Comment: But this doesn't help me unfortunately.. Of course i thought that fact was useful but i don't know how to link it to a proof of the problem. Any idea?
Answer: hint
(c) show that $A$ is open
(d) Any open subset of $\mathbb{R}$ is the union of countably many disjoint open intervals $\amalg (a_i,b_i)$. The Lebesgue measure is equal to $\sum (b_i - a_i)$. Now apply item (a) and the fact that $f$ is non-decreasing.

Prove that meas$(A)\leq 1$


Can a vampire's human child and another human make vampire babies?

Question: A vampire and human can have both vampire and human offspring. Can their human child have vampire babies?
Answer: Simply put; No.
For occult status, only the parents are checked.
Of course, if the human child were to later become a vampire, their children would be able to inherit it. ;)


How do I get the Kubuntu upgrade notification icon back?

Question: When Kubuntu needs to be upgraded between versions (e.g. 9.10 to 10.04), there's a notifier icon that shows up in the system tray,

(Source)
But if I click on it to start the upgrade and it fails for some reason (in my case, not enough space on the /boot partition), the icon disappears. How can I either get it back, or run the upgrade manually, without having to log out and log back in?
Answer: Open up KPackageKit in Kickoff (under the Computer tab), and it should offer to install updates.
If KPK can't do it:
sudo do-release-upgrade

Comment: Hm, I thought I did that and it only gave me 4 updates, the regular security/bugfix complement... but I'll go back and try it again to check.
Answer: The program that places the icon in the tray is a python script, update-notifier-kde, and it can be run from the terminal as
python /usr/bin/update-notifier-kde

(sudo not required, it will prompt for the password graphically)


Opening a Modal from a Menu in GlueStack

Question: I'm working on a project using GlueStack, and I'm trying to implement a functionality where clicking on a menu item should open a modal. I've looked into the documentation, but I couldn't find a clear example or guidance on how to achieve this.
I tried this but is not working.
  onClick: () => void;
}

const MenuConten: React.FC<ButtonProps> = ({ onClick }) => {
  return (
    <DesMenu>
      <MenuItem onPress={onClick}>
        <Icon as={Pencil} size="sm" mr="$2" />
        <MenuItemLabel size="sm" onPress={onClick}>
          Editar
        </MenuItemLabel>
      </MenuItem>
      <MenuItem>
        <Icon as={Trash2} size="sm" mr="$2" color="red" />
        <MenuItemLabel size="sm" color="red">
          Eliminar
        </MenuItemLabel>
      </MenuItem>
    </DesMenu>
  );
};

export default MenuConten;````

I need each option of the menu to open a different modal.

Could someone please provide a step-by-step guide or code snippet on how to open a modal from a menu in GlueStack? Any insights or examples would be greatly appreciated. Thank you!

Answer: You can use the prop selectionMode="single" and onSelectionChange callback to open modal. Below is an example of the same.
https://snack.expo.dev/@sacontrack/multiple-modal.


Gurobi: how to add a constraint x1*x2*x3

Question: I wish to add a constraint n1 = x1 * x2 *x3 in Gurobi, where x1, x2 and x3 are variables with 0 or 1. Unfortunately, can not find the solution.
Can someone help me?
Comment: x1 are binary value? Eg : 10101. You want to multiply them?
Comment: @CycDemo actually x1 x2, x3 all are just 0 or 1. And yes, multiply them
Comment: Can you verbalize your constraint in terms of IF, THEN, ELSE, AND, OR, XOR, NOT. The example you gave is IF x1 AND x2 AND x3, THEN n1, ELSE NOT n1. Less strictly, you gave, if x1, x2, and x3 all equal 1 then n1 equal 1 else n1 equals 0.
Answer: You are trying to create a seemingly non-linear constraint on binary variables.  You can model this as a series of linear constraints by noting the n will have the value 1 if and only if x1, x2, and x3 are all 1.
// only if part
model.addConstr(n, GRB.LESS_EQUAL, x1);
model.addConstr(n, GRB.LESS_EQUAL, x2);
model.addConstr(n, GRB.LESS_EQUAL, x3);

// if part
GRBLinExpr all_three;
all_three.addTerm(1.0, x1);
all_three.addTerm(1.0, x2);
all_three.addTerm(1.0, x3);
all_three.addConstrant(-2);
model.addConstr(n, GRB.GREATER_EQUAL, all_three);

This adds the constraints
n >= x1 + x2 + x3 - 2 and n <= min(x1, x2, x3).
Comment: Thanks, but I have a more complicated one. for example : n3=x2* (n1+n2- n1*n2) +x1* (n1-n2) *(n1-n2), then how to deal with it? here all variables are all 0 or 1.
Answer: n1<=x1
n1<=x2
n1<=x3
2+n1>=x1+x2+x3

If any of the of the x are 0, then n will be force to zero. If all are 1, n is forced to 1.
Edit
Since Gurobi recognizes binary variables, you could just use
3*n1<=x1+x2+x3
2+n1>=x1+x2+x3

The first only allow 0 and 1 while this would allow fractional values if not for the binary requirement.
EDIT
The constraint
n3 = x2 * (n1 + n2 - n1 * n2) + x1 * (n1 - n2) *(n1 - n2)

appears to be trying to enforce the logic
IF n1 AND n2:
    n3 = x2

IF n1 XOR n2:
    n3 = x1

IF (NOT n1) AND (NOT n2):
    n3 = 0

Since it the standard rule for expressing boolean logic operations in zero-one integer linear programming (ILP) take the form of x1 AND x2 IMPLIES y1, I reconstructed the above to read
n1 AND n2 IMPLIES i1
n1 XOR n2 IMPLIES i2
(NOT n1) AND (NOT n2) IMPLIES i3

Constructing the constraints for i1, i2, i3 is given below
IF n1 AND n2, THEN i1
    i1 ≥ n1 + n2 − 1
    i1 ≤ n1
    i1 ≤ n2
    0 ≤ i1 ≤ 1

IF n1 XOR n2, THEN i2
    i2 ≤ n1 + n2
    i2 ≥ n1 − n2
    i2 ≥ n2 − n1
    i2 ≤ 2 − n1 − n2
    0 ≤ i2 ≤ 1

IF NOT n1 AND NOT n2, THEN i3
    i3 ≥ 1 - n1 - n2
    i3 ≤ (1 - n1)
    i3 ≤ (1 - n2)
    0 ≤ i3 ≤ 1

This gives use three mutually exclusive indicators and the original problem can be rewritten as
-(1 - i1) ≤ n3 - x2 ≤ (1 - i1)
-(1 - i2) ≤ n3 - x1 ≤ (1 - i2)
-(1 - i3) ≤ n3 ≤ (1 - i3)

Comment: Thanks, but I have a more complicated one. for example : n3=x2* (n1+n2- n1*n2) +x1* (n1-n2) *(n1-n2), then how to deal with it? here all variables are all 0 or 1.
Comment: The easiest way to do it is to write it out like a logic statement, like n3 is True if x2 is true AND ... Then there is a set of rule you can use to construct the linear constraints. If you can star what you want in that way I can help, but the expression you've written is too confusing to understand at the moment.
Answer: Simplify way to convert binary string to integer. And, multiply it. Is it not OK?
int x1 = Integer.parseInt("101011", 2);
int x2 = Integer.parseInt("00010", 2);
int x3 = Integer.parseInt("000101", 2);
int n1 = x1 * x2 * x3;
System.out.println(n1);

Update
I don't know Gurobi, but
  GRBVar x1 = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "x1");
  GRBVar x2 = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "x2");
  GRBVar x3 = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "x3");

Example
Comment: What I mean is used in Gurobi as a constraint


What snapshot software do you recommend?

Question:
Possible Duplicate:
What screenshot tools are available?

Hi,
is there a snapshot software for Ubuntu? Something like SnagIt?
The idea is many times I have to take the snapshot and edit the image to crop to my region of interest, SnagIt does that automatically and very nicely.
Another feature is to take a snapshot of text (that can't be otherwise copied - like text in a photo) and then parse it into actual text document using an OCR technology.
Thanks
Answer: Shutter (Click to Install)

Shutter is a feature-rich screenshot program. You can take a screenshot of a specific area, window, your whole screen, or even of a website – apply different effects to it, draw on it to highlight points, and then upload to an image hosting site, all within one window.
Comment: shutter looks pretty much what I was looking for, thanks
Answer: Shutter is def. the closest to snagit.
Answer: For those one-off screenshots, Shutter might be a overkill. You can use xfce-screenshot for those purposes. Its very simple, but works.
Answer: I am not familiar with snagit, but have you tried Shuttler? as far I know it's the most complete screen shot tool available for Linux.
Comment: Shutter or Shuttler?
Answer: Yes, shutter is a very powerful utiity. It let you edits, run predefined plugins on it for 3d reflection and like effects and 2click upload to image hosting site for easy sharing. You won't need anything else, I am sure. :)
Comment: It can also take screenshots of full web pages by URL & a recent update also let you resize the window, take a screenshot and then resize it back to the original size, good for bloggers.


The similar function of "tf.Session().partial_run()" in Pytorch

Question: I am trying to use Pytorch to reimplement a project, but I have some troubles to find a similar function of "partial_run" of Tensorflow. Can you show me what it is?
Thanks.
Answer: You don't need the partial run function, as Pytorch objects hold actual values (and are not just abstracted computation/input nodes in a graph that only hold values once the computation graph is triggered - with Session.(partial)run).
So when you code something in pytorch, you can (mostly) just think of it as writing numpy code. There, too, the objects you create when writing your code will hold actual values that you can manipulate.
Besides being more "traditional" this has the great consequence that Pytorch thus allows you to debug code using a traditional python debugger.
Comment: Thanks! Your explanation helps me a lot.


How to bind Ctrl+arrows to Home and End keys? xmodmap does not work

Question: On Windows, I used to bind Ctrl+Left to Home and Ctrl + Right to End via ahk.
Now I'm struggling to achieve this behavior in Ubuntu.
I've tried editing /etc/inputrc:
"\e[1;5C": end-of-line
"\e[1;5D": beginning-of-line

It works but only in the terminal window.
I've also tried xmodmap:
xmodmap -e "keycode 113=Left NoSymbol Home"

but it does not work.
The strange thing here is that if I bind to Shift + Left in xmodmap it works:
xmodmap -e "keycode 113=Left Home"

My guess here is that the default behavior of Ctrl + Left(skip words) somehow gets priority over xmodmap bindings.
Where can I find where the default bindings are located and how to remove it?
Or,  maybe I could just bind needed behavior there ?
I'm on Ubuntu 12.04
Comment: Do you get `xev` output for the keys you want to change?
Comment: I do. I got keycode 113 = Left from xev output.
Comment: Can you add the whole `xev` output please?
Comment: state 0x0, keycode 113 (keysym 0xff51, Left)
Comment: and state 0x4, keycode 113 (keysym 0xff51, Left) if pressed with Ctrl - the state is changed to 0x4 as expected
Answer: AutoKey can do bindings like this, but it requires running a service in the background (like ahk, but unlike xmodmap).
Configure a "phrase" where the text is <home>, the paste method is Keyboard, and the hotkey is <ctrl>-<left>:
Comment: An expanded, more generic version: http://askubuntu.com/a/304834/194  Does that make this question a duplicate?
Comment: @JeffDror it's  and  ( http://code.google.com/p/autokey/wiki/SpecialKeys )
Comment: Nice. This might also be a good fit as an answer here as well http://askubuntu.com/questions/254424/how-can-i-change-what-keys-on-my-keyboard-do-how-can-i-create-custom-keyboard/257497#257497
Comment: It probably does, but you should still get the bounty. ;-)
Comment: this method does not work.
Comment: Still works for me using Ubuntu 13.10 and AutoKey 0.90.1.
Comment: For me this works well for  and  but not for  and .
Comment: Nice, but doesn't work when combining with SHIFT to e.g. move from beginning of line to its end while wanting to select the line content
Comment: It says the script contains an error for me. The script contains nothing but . (Ubuntu 20.04)
Comment: @Tom, can't that be solved by adding scripts for Shift+Ctrl+Left/Right that first holds Shift and then  and then releases shift?
Answer: I'm using Apple aluminum keyboard on Ubuntu workstation and the following xmodmap commands did it for me:
# remap Ctrl_L to ModeSwitch, then use it to map arrow keys so that
# they act like on the MacBook keyboard with Fn key pressed
xmodmap -e "keycode 37=Mode_switch"
xmodmap -e "keycode 113 = Left NoSymbol Home"
xmodmap -e "keycode 114 = Right NoSymbol End"
xmodmap -e "keycode 111 = Up NoSymbol Prior"
xmodmap -e "keycode 116 = Down NoSymbol Next"

This works perfectly because my Caps Lock key is remapped to Control function using Ubuntu keyboard preferences, so the left Control key is not needed. Since it is located where the Fn key is found on MacBook keyboard, switching between desktop and MacBook keyboards does not impact muscle memory.
Answer: Autokey worked for me. The default Autokey behavior would be: map both right ctrl+arrow and left ctrl+arrow. And I wanted only right ctrl, because I used left ctrl to navigate words.
Here is the script I used in Autokey:
output = system.exec_command('xinput query-state "AT Translated Set 2 keyboard" | grep down', getOutput=True)
# 105 is right ctrl
if 'key[105]=down' in output:
    keyboard.send_keys('<end>')
else:
    keyboard.send_keys('<ctrl>+<right>')

Note: you might have a different keyboard name. Try all of them. I had 3 devices, but only one worked
xinput list --name-only | grep -i keyb
Virtual core keyboard
Virtual core XTEST keyboard
AT Translated Set 2 keyboard

P.S. I installed Autokey from GitHub, because the package in Ubuntu Software is broken.


How to iterate and group through dictionary in python

Question: I am fighting with the query as I have to count What are the total CO2 emissions by each Airline?
I have managed to get all the data to a dictionary which looks like
Flight Number is 2HX and the airline is IT and the aircraft is E195 going from EDDF to LIMF
Flight distance is 542.93 km
Flight CO2 emissions is 16.87 kg

Flight Number is 8031 and the airline is ES and the aircraft is B752 going from LEBL to EDDP
Flight distance is 1365.97 km
Flight CO2 emissions is 31.07 kg

Flight Number is 39DV and the airline is ES and the aircraft is A320 going from LEPA to LEMD
Flight distance is 546.33 km
Flight CO2 emissions is 16.92 kg

All calculations are done by all of the flights but I would like to group them based on the AIRLINE, thus increasing the total results for them and printing them accordingly.
Any ideas how I could start it?
JSON file loaded looks like this
[{"hex": "150694", "reg_number": "RA-67220", "flag": "RU", "lat": 51.633911, "lng": 50.050518, "alt": 11582, "dir": 290, "speed": 761, "v_speed": 0.3, "squawk": "0507", "flight_number": "9004", "flight_icao": "TUL9004", "dep_icao": "VIDP", "dep_iata": "DEL", "airline_icao": "PLG", "aircraft_icao": "CRJ2", "updated": 1675528289, "status": "en-route"}, {"hex": "152038", "reg_number": "RA-73784", "flag": "RU", "lat": 43.352108, "lng": 35.634342, "alt": 11277, "dir": 4, "speed": 881, "v_speed": 0, "squawk": "7313", "flight_number": "427", "flight_icao": "AFL427", "flight_iata": "SU427", "dep_icao": "HESH", "dep_iata": "SSH", "arr_icao": "UUEE", "arr_iata": "SVO", "airline_icao": "AFL", "airline_iata": "SU", "aircraft_icao": "A333", "updated": 1675528054, "status": "en-route"}, {"hex": "152052", "reg_number": "RA-73810", "flag": "RU", "lat": 59.739784, "lng": 85.652138, "alt": 9745, "dir": 89, "speed": 801, "v_speed": 0, "squawk": "5521", "flight_number": "173", "flight_icao": "SVR173", "flight_iata": "U6173", "dep_icao": "USSS", "dep_iata": "SVX", "arr_icao": "UHHH", "arr_iata": "KHV", "airline_icao": "SVR", "airline_iata": "U6", "aircraft_icao": "A319", "updated": 1675528294, "status": "en-route"}

Basically function for listing flights look like this, but I would like to group them by airlines and add value of co2 emissions to each of individual results
def list_all_flights(self):
    #List all flights
    total_result = 0
    for i in self.flights_list.read_data_file(): # json.file
        if(i.get('dep_icao') and i.get('arr_icao')):
                print(f"Flight Number is {i['flight_number']} and the airline is {i['flag']} and the aircraft is {i['aircraft_icao']} going from {i['dep_icao']} to {i['arr_icao']}");

I have managed to count all encounters of different airline  inside new dictionary and it works
if 'flag' in i:
                temp[i['flag']] = temp.get(i['flag'], 0) + 1'

Now I would like to add the result for co2 emissions as a total for an airline.
Comment: _I have managed to get all the data to a dictionary which looks like_ - This is not a dictionary
Comment: Please, post [mre] of your code, incl. sample JSON and expected output
Comment: you are right they are coming from json file that I could get attributes like dictionary i.get('flag') for the airline I was hoping if there is a way to group the values in total for each one of the airline.
Comment: I am sorry I am new in this, I have added some entries how json looks like.
Comment: I have managed to count all encounters of different airline  inside new dictionary and it works
'''
               if 'flag' in i:
                    temp[i['flag']] = temp.get(i['flag'], 0) + 1'
'''
Answer: By making use of Pandas module (you can install via pip install pandas) I made this.
import pandas as pd
df = pd.read_json("data.json")
result = {a_iata:[] for a_iata in df.airline_iata.unique()}
for a_iata in result:
    result[a_iata] = df.loc[df.airline_iata == a_iata]

Where data.json is the data that you have provided. The code essentially filtrates every entry by its airline_iata value and stores them into individual DataFrames. You can see the data by using result['AIRLINE_CODE'] and it will return the DataFrame.
When you are constructing your message, you can use something like this:
temp_df = result['AIRLINE_CODE']
message = f"Flight reg number is {temp_df.reg_number}..."

You can fill the message out however you like.


packhard bell dot s netbook ubuntu 12.10

Question: sorry im absolutly linux beginner....
i bought a packhard bell netbook dots with Limpus.did not get along with limpus so wanted to install ubuntu.
netbook:
2 GB RAM intel Atom N2600, intel graphics Media Accelerator 3600
I over installled ubuntu 12.10 (desktop version) like in the instruction (isofile over USB). Installation went fine. No problems. when starting after installation alot of text is coming.....starting xyz....with alot of okays at the end of line
but nothing happends: ends with #Starting CPU interrups balancing daemon, stopping anachronics cron and blinking cursor...
was reading in this forum, tried to do some things like #recoverymode# and nomodeset...
but did not work or where do i get this graphic drivers from. Packard bell just offers windows drivers.and how do i install them?
maybe its a completely diffrent cause for this?
Thanks alot
Answer: Same netbook here. Cannot start into X windows. Blank screen and computer freezes.
I have tried Ubuntu, slackware 14, puppy 5.4.2 , crunchbang
It works only with kernel 2.6.
The problem I think it is intel 3600 graphics.
Answer: I just installed it using a different ubuntu image and then successfully upgraded to 12.10.
Downloads: http://releases.ubuntu.com/precise/
Yeah unity 3D might be a bit slow but one can cope with it.


Infinite scrolling within a tabbed listview on Android

Question: Is it a good experience to give an infinite scrolling view across tabs in Android if there are tabbed list views in the app?
Basically if a user scrolls through a list in a tabbed view, the tab auto scrolls to the next tab once the user reaches the end of the list in one tab. Also if the users scrolls back on the list, he's taken to the previous tab (so like an infinite scrolling list across tabs).
I see an implementation on iOS of a similar kind in this app.
https://itunes.apple.com/in/app/grofers-local-shopping/id960335206?mt=8
Will this make sense on Android?
Answer: Not sure the use case for this. what are the tabs? what does the app do?
I think perhaps there is a way to prompt your users to move to the next tab without auto-moving to the it.
The issue is it's an action that the user can not undo, if i'm scrolled at the bottom of a long list, then auto moved to another list...i just lost my place. Also it's not a common pattern users are familiar with. Plus having the a tab bar means that the next tab is only a tap away and always visible.
Comment: Think of the app as basically as a list of news articles split by tabs which are categories. So tabs might be "Featured", "Sports","Current affairs" and so on, each having a list of articles. Once I reach the end of Featured tab, it auto scrolls into Current affairs etc.,
Answer: Infinite scrolling + swipe between tabs is a great idea.
What you have to be aware of is respecting the patterns of each OS. As an example, remember iOS has the tab bar on the lower of the screen while Android uses it on top of the navigation bar. Also, the back button for android should take the user to the last tab visited but in iOS you won't have a behaviour such as this one. Keep your patterns clear and solid while using interactions which are new for you users. And of course test them to proove users understand them and find it useful.
Swarm is a good example of many differences iOS and Android have.
Comment: Infinite scrolling amongst tabs also? i.e. If I reach the end of the list in one tab, the tabs change ?


Material Autocomplete - auto selecting an option when options change. React

Question: I am trying to get Material Autocomplete to auto select my initially loaded option, but am having some issues. I'm very new to React and so may be doing something fundamentally wrong, but my code is basically doing this.
<code>export default function AsyncPicker({name, formik, initialOptions = []}) {
    const [options, setOptions] = useState(initialOptions);

    useEffect(() => {
        setOptions(initialOptions);
    },[initialOptions])

   return (
       <Autocomplete
           ....otherProps
           options={options}
           value={{id:formik.values[name]}}
           getOptionSelected={(option, value) =>  option.id === value.id}
       />
   )
}
</code>
The options are loaded asynchronously when typing, but for the initial option I want to load a single option based on the value of the record.
From a parent component I am rendering the Autocomplete that initially gets a default empty array for its initialOptions. When data is loaded asynchronously for the given record the initialOptions is updated to reflect the value of the record loaded. The options update in the child control and the option renders, but it does not auto select.
getOptionSelected does fire upon the initialOptions being updated and the id of both the option and the value match, so why is it not being selected?
As I said, happy to be told Im doing it completely wrong as had never written a line of react 2 weeks ago.
Answer: <code> return (
       <Autocomplete
           ....otherProps
           options={options}
           value={{id:formik.values[name]}}
           getOptionSelected={(option, value) => formik.setFieldValue(option.id === value.id)}
       />
   )
</code>
tie the onChange function to formik's setFieldValue function as in this answer?
Using Material-UI's Autocomplete component with Formik
Comment: No. I am calling setOptions when the initialOptions are first provided (which is the only point it should be selected) and then on subsequent api calls after user input.
Comment: That results in the error: Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
Comment: Im guessing its because setFieldValue causes the component to re-render which results in infinite loop. Also, I dont understand the intent behind that fix, doesnt setFieldValue just set a value to the underlying formik object? Wheras in this case the formik object has its values, the picker has loaded the option, its just that I need to select it


403 Request Failure Despite working Service Account google.oauth2

Question: I am consistently running into problems querying in python using the following libraries. I am given a 403 error, that the "user does not have 'bigquery.readsessions.create' permissions for the project I am accessing.
#BQ libs
from google.cloud import bigquery
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file('path.json')

#BigQuery Connection and query execution
bqProjectId = 'poject_id'
project_id = bqProjectId
client = bigquery.Client(credentials= credentials,project=project_id)

query = client.query("SELECT * FROM `table`")
Output = Query.to_dataframe()

I am using the same service account json file, and same query in Java, R, and even on a BI tool. All three successfully retreived the data. So this seems to be python specific.
I have tried starting with a clean environment. I even reinstalled anaconda. Nothing seems to work. What are some possible culprits here?
*Obviously my path, query, and creds are different for that actual script.
Answer: You can try the below code by including access scope https://www.googleapis.com/auth/cloud-platform for your requirement.
from google.cloud import bigquery
from google.oauth2 import service_account

key_path = "path/to/service_account.json"

credentials = service_account.Credentials.from_service_account_file(
    key_path,
    scopes=["https://www.googleapis.com/auth/cloud-platform"],
)

project_id = "project-id"
client = bigquery.Client(
    credentials=credentials,
    project=credentials.project_id,
)
sql_query ="SELECT * FROM table"
query_job = client.query(sql_query)
results = query_job.result()
df = results.to_dataframe()
print (df)

As per the error message you are getting, service account is missing the BigQuery Admin Role which includes the permission bigquery.readsessions.create.
For more information regarding BigQuery IAM roles you can refer to this document.


With Puppeteer how can I click the parent element of my selector?

Question: The markup i have to work with looks like this:

    <input type="radio" name="myfield" value="Yes" size>

I want to call page.click(selector) with the radio as the selector, but I can't. I don't think it is visible because of the size attribute.
My javascript looks like this:
const page = await browser.newPage();
const selector = 'input[name="myfield"]';
await page.click(selector);

So I would like to target and click the parent label element.
How do I change the value of my selector constant to target the label?
Comment: Please be more specific. How about adding some picture to visualize your current situation? And also add your codes please.
Comment: By "but I can't" you probably mean "but it won't work", so please show what you're doing.
Comment: Sorry, I didn't explain very well. By can't, i mean that the element is not visible and therefore i don't believe it can technically be clicked. Therefore I think i need to target the label which is visible, but i don't know how I target it.
Comment: Does `const selector = 'label';` not work or what is the question here?
Answer:
Sorry, I didn't explain very well. By can't, i mean that the element is not visible and therefore i don't believe it can technically be clicked. Therefore I think i need to target the label which is visible, but i don't know how I target it

not visible or not visible at the moment?
Have you tried to use waitForSelector(selector) ?
const page = await browser.newPage();
const selector = 'input[name="myfield"]';

await page.waitForSelector(selector); // waiting here before click
await page.click(selector);

Or something like:
const page = await browser.newPage();
const selector = 'label';

await page.waitForSelector(selector);

await page.evaluate((_) => {
    document.querySelector('label > input[name="myfield"]').parentElement.click()
});


Rebinding Knockout Click Event

Question: I have a list of items that have bindings to a click event using Knockout.js.

This function works perfectly. The problem arises when I add a new record to the knockout list I call a sort function that sorts the knockout list alphabetically.
The sort function orders the list, empties it and then appends the reordered list.
When this is done the knockout items lose their click binding parent.preEditContact
How can I rebind the click event?
Answer: Instead of using my makeshift sort code there is actually sort functions available with Knockout.js that retains the click bindings.
The code used to sort a list while retaining the click bindings is as follows:
self.Contacts.sort(function(a,b){
 var a1 = a.ContactName().toLowerCase();
 var b1 = b.ContactName().toLowerCase();
 return a1.localeCompare(b1);

});
Comment: You could accept your answer, so that people don't think it's still unresolved in the preview page...
Comment: It says I cant mark my answer as the correct answer for at least another day

Rebinding Knockout Click Event


shift by left an array withh given value

Question: #include <iostream>
#include <string>
#include <fstream>

using namespace std;

void shiftLeft (char myarray[], int size, int shiftBy)
{
    if(shiftBy > size){
        shiftBy = shiftBy - size;
    }

    if(size == 1){
        //do nothing
    }
    else{
        char temp;
        //for loop to print the array with indexes moved up (to the left) <-- by 2
        for (int i=0; i < size-shiftBy; i++)
        {//EXAMPLE shift by 3  for a c-string of 5
            temp = myarray[i];//temp = myarray[0]
            myarray[i] = myarray[i + shiftBy];//myarray[0] == myarray[2]
            myarray[i + shiftBy] = temp;//myarray[2] = temp(value previously at index i)
        }

    }
}

int main ()
{
    char text[] = "OPAKMIGWPKBTWAQSZQABTAVWASZGETAATGCEWQEAVFZMHATXSOQLPAMOTZMIATXFWFKMQEMELWBHQZYPQJMFGEMLKTZQEOWAVARATXMXIABTKVAOUKDQFLTQZWDKMYMAFLPUFSULYGWMDLWELWBOQFZWGLIRSZYZWGKMZWIDTMFOMQFBTWEAGLESVPXZARMZDIWWBTWLMJSQKBQNMZAVSGNFZMKWIDZMSADQKPUKPMJVQKANWTXKIEZIWWBASAWANFZMDWQEKWYWUUKBMCMFZMAFTKGBTWZEGCZVAFZMEOMQHWRWIEQEUFLMFLPGEZQNXSSQLPQOWAVAMJMXGDQDGPSZWSVPVMQHJGLQTSDQHZAEQEWAFGSQWXMFLYATQKBAYWNWNAJMUKTQWXMFLYATQKBAYWNWNAJMUKTQWX" ;
    char textTwo[] = "OPAKMIGWPKBTWAQSZQABTAVWASZGETAATGCEWQEAVFZMHATXSOQLPAMOTZMIATXFWFKMQEMELWBHQZYPQJMFGEMLKTZQEOWAVARATXMXIABTKVAOUKDQFLTQZWDKMYMAFLPUFSULYGWMDLWELWBOQFZWGLIRSZYZWGKMZWIDTMFOMQFBTWEAGLESVPXZARMZDIWWBTWLMJSQKBQNMZAVSGNFZMKWIDZMSADQKPUKPMJVQKANWTXKIEZIWWBASAWANFZMDWQEKWYWUUKBMCMFZMAFTKGBTWZEGCZVAFZMEOMQHWRWIEQEUFLMFLPGEZQNXSSQLPQOWAVAMJMXGDQDGPSZWSVPVMQHJGLQTSDQHZAEQEWAFGSQWXMFLYATQKBAYWNWNAJMUKTQWXMFLYATQKBAYWNWNAJMUKTQWX";
    string OG="OPAKMIGWPKBTWAQSZQABTAVWASZGETAATGCEWQEAVFZMHATXSOQLPAMOTZMIATXFWFKMQEMELWBHQZYPQJMFGEMLKTZQEOWAVARATXMXIABTKVAOUKDQFLTQZWDKMYMAFLPUFSULYGWMDLWELWBOQFZWGLIRSZYZWGKMZWIDTMFOMQFBTWEAGLESVPXZARMZDIWWBTWLMJSQKBQNMZAVSGNFZMKWIDZMSADQKPUKPMJVQKANWTXKIEZIWWBASAWANFZMDWQEKWYWUUKBMCMFZMAFTKGBTWZEGCZVAFZMEOMQHWRWIEQEUFLMFLPGEZQNXSSQLPQOWAVAMJMXGDQDGPSZWSVPVMQHJGLQTSDQHZAEQEWAFGSQWXMFLYATQKBAYWNWNAJMUKTQWXMFLYATQKBAYWNWNAJMUKTQWX";
    int size =OG.length();
    int count = 0;
    ofstream outputFile("info.txt");
    for (int i =1; i<size+1;i++){
        shiftLeft(text,size,i);
        string name="OPAKMIGWPKBTWAQSZQABTAVWASZGETAATGCEWQEAVFZMHATXSOQLPAMOTZMIATXFWFKMQEMELWBHQZYPQJMFGEMLKTZQEOWAVARATXMXIABTKVAOUKDQFLTQZWDKMYMAFLPUFSULYGWMDLWELWBOQFZWGLIRSZYZWGKMZWIDTMFOMQFBTWEAGLESVPXZARMZDIWWBTWLMJSQKBQNMZAVSGNFZMKWIDZMSADQKPUKPMJVQKANWTXKIEZIWWBASAWANFZMDWQEKWYWUUKBMCMFZMAFTKGBTWZEGCZVAFZMEOMQHWRWIEQEUFLMFLPGEZQNXSSQLPQOWAVAMJMXGDQDGPSZWSVPVMQHJGLQTSDQHZAEQEWAFGSQWXMFLYATQKBAYWNWNAJMUKTQWXMFLYATQKBAYWNWNAJMUKTQWX";
        for(int j=0;j<size;j++){
            if(text[j]==textTwo[j])
            count++;
        }
        outputFile  <<"Shift right by: " << 422-i << " Coincidences: " << count <<"text:" <<text <<endl;
        strcpy_s(text, name.c_str());
        count = 0;
    }
outputFile.close();
    return 0;
}

My goal is here to crack The Vigen`ere Cipher but i need to do the following operrationg shift the bits starting from 0 to size of text and check if the shifted and original text match up, the maximum value that they match up gives me the key space but my code doesnt work proper, shifting left seems to not work but i have tested on small inputs it works fine on small inputs..
Comment: _"i dont know where my mistake is...."_ What is the problem actually? Compiler errors? Runtime errors? Unexpected output?
Comment: check the desc again, i added more details
Comment: Not enough details. Provide an [MCVE], show your observations when stepping through your code with the debugger.
Comment: I'm not at all sure I understand what you're trying to do, but if it doesn't work for large "shiftBy" inputs, is it because you're only checking shiftBy > size once? I mean, I would think you would want something more like "while (shiftBy >= size) { shiftBy -= size; }" at the top of your function.
Comment: Move your `temp =` statement to before the `for` loop.  Otherwise it looks like a *swap* pattern.
Answer: Arrays can be shifted either by moving elements or changing the index.
Shifting by moving elements
Repeat for every slot:
array[i] = array[i+1];
// or
array[i+1] = array[i];

Rotating by moving elements
i = 0;
carry_value = array[i];
// Loop:
array[i] = array[i+1];
// end loop
array[last_slot] = carry_value;

A Caesar Cipher works by changing the index value:
new_value = array[(index + offset) % array_capacity];


History of squaring the circle

Question: I'd like to know the main attempts in history to prove the squaring the circle. Do you know a good book or link where I can find a schematical and methodical description of the history of this problem? Thank you
Comment: See [Wiki's entry](https://en.wikipedia.org/wiki/Squaring_the_circle) with references and  Ernest William Hobson,  (1913) [Squaring the Circle: A History of the Problem](https://archive.org/details/squaringcirclehi00hobsuoft) Cambridge University Press.
Comment: Really good advice!
Answer: Perhaps, this is the best link I can provide : A video by Numberphile
 - Squaring the Circle
Comment: @xyzt I too am big fan of this channel. You must subscribe to it. Their videos are worth watching.
Comment: Really interesting YouTube channel!
Comment: Well .. sometimes numberphile is mind blowing and sometimes it is just :-( . I would say that for  a short description of Any maths topic numberphile is good. +1
Comment: @Thelonewolfisbackbaby... I read your bio.. did you appear for JEE, or what are your plans? IISC?IISER? I am from Indore,M.P. and in 11th standard.I am also planning to do something in mathematics.
Comment: Well... I will appear for JEE next year ... I m in class 12 right now. Most of my time is consumed in doing maths so iisc will be my first choice.
Comment: How about you ?? Are you preparing for JEE?
Comment: @Thelonewolfisbackbaby... Yes I am. Did you appear for KVPY (I appeared) , it is the best for joining research institute in India.
Comment: Yes.. I did.. but I don't have any intrest in bio and chemistry so I failed... :-P they habe a cutoff of 50+ which I can't get even if I do all the physics and maths questions...
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/56946/discussion-between-jaideep-khare-and-the-lone-wolf-is-back-baby).
Comment: @VidyanshuMishra Yaaden BC, apan idhar pehli baar mile the.
Comment: :-)  Haa BC...  MSE kaa faayda!!!!
Comment: @Vidyanshu Bhai 10k Hit ho gaye! Nacho BC :)
Comment: Abe saala m abhi yehi dekh ra that dopher m Ki iske 10k hue yaa nhi.... Tb 9973 the... Mjhe LGA bs ek answrr krde..  10 k ho jaegi.... Congo....  Talented h tu. :-P
Comment: @VidyanshuMishra wholesome xD
Answer: A classical resource is E. W. Hobson's book Squaring the circle. A history of the problem. It was published in 1913, so it is a bit outdated from the viewpoint of historical methodology, but it has the advantage of covering the topic broadly from antiquity to the end of the 19th century. I find it mathematically accurate, and the choice of the episodes analyzed is not trivial (for example, you can find there a fine discussion of the not-so-well known solution given by Descartes). Moreover, Hobson wrote the book only a few decades after the first rigorous proofs of the transcendence of $\pi$, which perhaps explains his interest for the history of the quadrature of the circle. A more recent and very fine study is P. Eymard and J. P. Laffont's book Autour du nombre $\pi$. This beautiful book is mathematically more engaging than Hobson's, but well worth reading. I have just realized that there is an English edition too.
These books do not deal with the flawed attempts to square the circle, which were countless in history. For this topic, you can consult Marie Jacob's book, which is available, I am afraid, only in French.

History of squaring the circle


How can I route a system-wide ALSA EQ (alsaequal) through my volume control and connect PulseAudio to it?

Question: I have a rather specific issue and can't solve it on my own.
As explained in this Question, I have set up a system-wide volume control for my single USB audio card (M-Audio Fast Track). Now, I would also like to add a system-wide equalizer (libasound2-plugin-equal) to it, while keeping the volume control intact.
So far, I was able to get everything working correctly only in ALSA-programs.
With the following /etc/asound.conf, both the volume-control via softvol and the equalizer settings work at the same time:
pcm.!default {
        type plug
        slave.pcm "softvol"
}

ctl.!default {
        type hw
        card Track
}

pcm.softvol {
        type softvol
        slave {
            pcm "hw:Track"
        }
        control {
            name "Master"
            card Track
        }
}

ctl.equal {
        type equal;
}

pcm.plugequal {
        type equal;
        slave.pcm "plug:softvol";
}

pcm.!default {
        type plug;
        slave.pcm plugequal;
}

Source: https://docs.slackware.com/howtos:hardware:sound_problems_on_slackware
There seems to be some redundancy, but this is the setup that works currently.
The issue that remains now is that PulseAudio apparently skips all of this setup and directly outputs to my sound card, so the equalizer works in programs that support ALSA-output (not Firefox, etc.) and JACK, since the output device can be specified.
Does someone know how to isolate PulseAudio in such a way that it will only output to the plugequal ALSA-device and not be connected to my sound card directly?
Unfortunately, PulseAudio doesn't list plugequal as an output device, just my hardware sound card.
I have uninstalled PulseAudio at the moment, since it disables the EQ and volume control when it is connected to the sound card.
Answer: As someone used to "plug and play" audio devices (eg never have to configure anything for sound) your problem "sounds" very complicated to me. However, there are generic problems with equalizers and the accepted answer there might help:
To start the pulseaudio equalizer run:
qpaeq

If this gives you the error
There was an error connecting to pulseaudio,
please make sure you have the pulseaudio dbus module loaded, exiting...

then load these two modules using pactl:
pactl load-module module-equalizer-sink
pactl load-module module-dbus-protocol

and, to make these changes permanent, edit ~/.config/pulse/default.pa (create it if necessary) and add these lines:
load-module module-equalizer-sink
load-module module-dbus-protocol

Comment: Hi, thank you for your answer! Just to make sure: By the context of the commands, I'm assuming this will only affect PulseAudio sound, right? I've had a PulseAudio EQ working a while ago, but I also need to apply it to JACK outputs, that's why I'm trying to EQ all signals at the last stage (ALSA). Currently, I'm routing my PulseAudio sound through a JACK EQ-plugin (Calf), but having an EQ at the ALSA stage would allow me to not have the JACK daemon running constantly when I'm not working in my DAW.
Answer: I used to use jack and MIDI and I remember looking at this video on YouTube. I will try to go through the steps.
If you haven't done so already you should first install qjackctl
sudo apt install qjackctl

Follow the prompts and change the answer to yes. Then, go back to the command line after the install.
aptitude search pulseaudio

You need to install some modules.
pulseaudio-module-jack

to install it, use this command:
sudo aptitude install pulseaudio-module-jack

Next go into into a text file:
sudo vi /etc/pulse/default.pa

Look for the heading ###Load audio drivers statically. Then, add these two lines:
load-module module-jack-sink
load-module module-jack-source

Then put this into the command line:
sudo service pulseaudio restart

The video goes into even more detail but that gives a good explanation. I did this at one point in time and it worked, good luck.
Comment: Hi, thank you for your suggestion! Unfortunately, this doesn't really help me with the PulseAudio/ALSA problem. I'm aware that it's possible to route PA through a Jack-EQ plugin, but that would require me to constantly have both Jack and the Plugin Host running, which creates a bit of extra load AND it requires me to fix my CPU governor, because I get audible x-runs on Ondemand. I hoped to dodge this situation by having a central EQ at the ALSA stage or possibly two separate EQs for PA and Jack, but at this point it seems unlikely that this is possible...


How to delete attachment from list item in sharepoint using client object model?

Question: The AttachmentCollection object does not have any delete method. How can i do it?
Answer: AttachmentCollection class does not expose any methods for deleting attachments, but you could utilize Attachment.DeleteObject method to delete an Attachment from a collection.
The following example demonstrates how to delete all attachments in list item:
<code>public static void DeleteAttachmentFiles(ClientContext context, string listTitle,int listItemId)
{
    var list = context.Web.Lists.GetByTitle(listTitle);
    var listItem = list.GetItemById(listItemId);
    context.Load(listItem, li => li.AttachmentFiles);
    context.ExecuteQuery();
    listItem.AttachmentFiles.ToList().ForEach(a => a.DeleteObject());
    context.ExecuteQuery();
}
</code>


Getting feedback from ViewModel

Question: I have a simple webform which has two fields that accepts number values. What I would like to do is compare the values in each field and, if they aren't valid, display a message to the user.
I'm currently using the ValidationAttribute in my viewmodel for this and the method 'isValid', where true is returned if the values are valid and false if they're not but I'm unsure how to capture the true/false return and make use of it. Here's what I have so far:
public class AlertValuesCheck : ValidationAttribute
{
    private static double minAlert;
    private static double maxAlert;

    public override bool IsValid(object value)
    {
        if (maxAlert == 0)
            maxAlert = (double)value;
        else
            minAlert = (double)value;

        if (maxAlert < minAlert)
            return false;

        return true;
    }
}

Elsewhere...
[Display(Name = "Max Alert Boundary")]
[AlertValuesCheck]
[Required(ErrorMessage = "{0} is required!")]
public Nullable<double> MaxAlertBoundary { get; set; }

[Display(Name = "Min Alert Boundary")]
[AlertValuesCheck]
[Required(ErrorMessage = "{0} is required!")]
public Nullable<double> MinAlertBoundary { get; set; }

Ideally I would like to have a message displayed like [Required(ErrorMessage)] does. Is this possible? If so, how would I do this?
Comment: Have you looked at the Fluent Validation library?
Comment: Just taken a look at it - looks very promising
Comment: I like it because it takes the validation logic out of the view models and makes it more easily testable. It's no longer a concern of the view model.
Answer: You already have ErrorMessage property on your AlertValuesCheck as it extends ValidationAttribute.
So you can just go with :
[AlertValuesCheck(ErrorMessage = "Your error message !!")]

Comment: This is exactly along the lines of what I was after however my program ignores this even after changing both returns to false (my error message wasn't shown). Do you think I could be missing something else in this?

Getting feedback from ViewModel


Control chromium kiosk mode url from python

Question: Using Python to start a browser (Chromium) and change the url
The linked question is asking exactly what I want but I don't know how to implement the answer that is just to uses Selenium.
I just need to load chromium in kiosk mode and load a local html page I have does this with os.system('chromium-browser --kiosk file://.....') but this loads a new window/tab every time so it's not efficient or fast
Comment: Do you mean this line browser = Popen(["chromium", "http://www.google.com"]) because didn't work for him. I don't what to start a new window every time I need to display a page I just what t reload the view. :)
Comment: The question you linked to uses `Popen` from [the `subprocess` module](https://docs.python.org/3/library/subprocess.html). That allows you to communicate with the process and kill it.
Answer: You can add options to selenium's chromedriver, similar to how you would using os.system
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--kiosk")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("http://example.com")

To refresh or reload the page repeatedly, you could do driver.get(url) or driver.refresh() in a while True loop.
Comment: I'm having trouble getting the chromedrive to work on a raspberry pi.
Answer: this code work for me..
 from selenium import webdriver
 from selenium.webdriver.support import ui
 from selenium.webdriver.chrome.options import Options

 option = Options()
 option.add_argument("--start-maximized")
 option.add_argument("--no-sandbox")
 option.add_argument("--disable-web-security")
 option.add_argument("--ignore-certificate-errors")
 option.add_argument("--kiosk")
 option.add_argument("--disable-password-manager-reauthentication")

driver = webdriver.Chrome("C:/chromedriver.exe",0,option)


Shiny server systemctl fails at boot

Question: I installed Shiny Server on my Ubuntu Mate 15.10 64bit.
I can start the server without problem after boot by running manually the command sudo systemctl start shiny-server.
I enabled the service to start at boot with
sudo systemctl enable shiny-server, but when I boot the server is not started.
I did sudo systemctl status shiny-server and the log says that starting the server failed with error:
pid file /var/run/shiny-server.pid not readable (yet?)

How can I fix such an issue?
Answer: I'm facing the same problem on a RHEL 7.x box...
We are waiting on an official response from the shiny-server gurus.
However, for the time being, if you edit the /etc/systemd/system/shiny-server.service file...and comment out thePIDFile=/var/run/shiny-server.pid line, it seems to 'fix' the problem.
(you may need to translate paths since I'm on en EL 7 box, and you are on an Ubuntu Server)
Comment: +1 I had the same issue when I downgraded from a Pro evaluation version to the free one. Commenting that line out, running `sudo systemctl daemon-reload` and restarting the server seemed to do the trick.

But I don't know why....
Comment: Did you ever hear of an official solution to this issue? I just hit the exact same one on Ubuntu 16.04, and your fixed worked for me for the moment.

Shiny server systemctl fails at boot


Restore Default Ubuntu 22.04 DNS Settings

Question: Situation
Prior, to properly backing up my freshly installed Ubuntu 22.04 with Timeshift... I attempted to instead install dsnmasq for local web development.  Of course, I broke my DNS and now my fresh install has no internet access :-(
Error
These are the exact step from my personal notes that caused the error:
1. Disable & stop systemd resolved

    $ sudo systemctl disable systemd-resolved
    $ sudo systemctl stop systemd-resolved

2. Remove symlink on `/etc/resolv.conf` & remove the file

    $ ls -lh /etc/resolv.conf
    $ sudo rm /etc/resolv.conf

3. create new /etc/resolv.conf

   sudo bash -c 'echo "nameserver 127.0.0.1" > /etc/resolv.conf'

After item 3.) above, I completely lost internet access.
Troubleshooting
1.) I easily re-enabled  systemd-resolved
Update:
@keff suggested solution below, seems to be correct, but it does not work.
1.) I created a virtualbox installation of ubuntu 22.04 and made a copy of /etc/resolv.conf  that I put in my shared folder and took a screenshot of the ls -l /etc/resolv.conf output.
2.) I followed @keff's instructions and compared the results to my virtualbox output... they match.  I rebooted the machine to ensure all possible services get a restart.
DNS just isn't working, although it is correctly configured.  I have two laptops connected to the same wifi connection, so I know the wifi is working correctly.
I am stumped.
(yes, port 53 is open in ufw)
Question
The part of my foolery that eludes me is, "How do I re-establish the  /etc/resolv.conf  symlink, so that box once again has outside internet access?"
Comment: does a systemctl restart resolved
help until the next boot ?
Answer: To recreate the symlink for /etc/resolv.conf, run the following command:
sudo ln -s /run/systemd/resolve/stub-resolv.conf /etc/resov.conf

This will create a symlink from /etc/resov.conf to /run/systemd/resolve/stub-resolv.conf, which lists 127.0.0.53 as the local caching stub resolver.