text:
Q: Calling -retainCount Considered Harmful Or, Why I Didn't Use retainCount On My Summer Vacation
This post is intended to solicit detailed write-ups about the whys and wherefores of that infamous method, retainCount, in order to consolidate the relevant information floating around SO.*

*

*The basics: What are the official reasons to not use retainCount? Is there ever any situation at all when it might be useful? What should be done instead?** Feel free to editorialize.

*Historical/explanatory: Why does Apple provide this method in the NSObject protocol if it's not intended to be used? Does Apple's code rely on retainCount for some purpose? If so, why isn't it hidden away somewhere?

*For deeper understanding: What are the reasons that an object may have a different retain count than would be assumed from user code? Can you give any examples*** of standard procedures that framework code might use which cause such a difference? Are there any known cases where the retain count is always different than what a new user might expect?

*Anything else you think is worth metioning about retainCount?

*
Coders who are new to Objective-C and Cocoa often grapple with, or at least misunderstand, the reference-counting scheme. Tutorial explanations may mention retain counts, which (according to these explanations) go up by one when you call retain, alloc, copy, etc., and down by one when you call release (and at some point in the future when you call autorelease).
A budding Cocoa hacker, Kris, could thus quite easily get the idea that checking an object's retain count would be useful in resolving some memory issues, and, lo and behold, there's a method available on every object called retainCount! Kris calls retainCount on a couple of objects, and this one is too high, and that one's too low, and what the heck is going on?! So Kris makes a post on SO, "What's wrong with my memory management?" and then a swarm of <bold>, <large> letters descend saying "Don't do that! You can't rely on the results.", which is well and good, but our intrepid coder may want a deeper explanation.
I'm hoping that this will turn into an FAQ, a page of good informational essays/lectures from any of our experts who are inclined to write one, that new Cocoa-heads can be pointed to when they wonder about retainCount.

** I don't want to make this too broad, but specific tips from experience or the docs on verifying/debugging retain and release pairings may be appropriate here.
 ***In dummy code; obviously the general public don't have access to Apple's actual code.

A:
The basics: What are the official reasons to not use retainCount?

Autorelease management is the most obvious -- you have no way to be sure how many of the references represented by the retainCount are in a local or external (on a secondary thread, or in another thread's local pool) autorelease pool.
Also, some people have trouble with leaks, and at a higher level reference counting and how autorelease pools work at fundamental levels. They will write a program without (much) regard to proper reference counting, or without learning ref counting properly. This makes their program very difficult to debug, test, and improve -- it's also a very time consuming rectification.
The reason for discouraging its use (at the client level) is twofold:

*

*The value may vary for so many reasons. Threading alone is reason enough to never trust it.

*You still have to implement correct reference counting. retainCount will never save you from imbalanced reference counting.

Is there ever any situation at all when it might be useful?

You could in fact use it in a meaningful way if you wrote your own allocators or reference counting scheme, or if your object lived on one thread and you had access to any and all autorelease pools it could exist in. This also implies you would not share it with any external APIs. The easy way to simulate this is to create a program with one thread, zero autorelease pools, and do your reference counting the 'normal' way. It's unlikely that you'll ever need to solve this problem/write this program for anything other than "academic" reasons.
As a debugging aid: you could use it to verify that the retain count is not unusually high. If you take this approach, be mindful of the implementation variances (some are cited in this post), and don't rely on it. Don't even commit the tests to your SCM repository.
This may be a useful diagnostic in extremely rare circumstances. It can be used to detect:

*

*Over-retaining: An allocation with a positive imbalance in retain count would not show up as a leak if the allocation is reachable by your program.

*An object which is referenced by many other objects: One illustration of this problem is a (mutable) shared resource or collection which operates in a multithreaded context - frequent access or changes to this resource/collection can introduce a significant bottleneck in your program's execution.

*Autorelease levels: Autoreleasing, autorelease pools, and retain/autorelease cycles all come with a cost. If you need to minimize or reduce memory use and/or growth, you could use this approach to detect excessive cases.
From commentary with Bavarious (below): a high value may also indicate an invalidated allocation (dealloc'd instance). This is completely an implementation detail, and again, not usable in production code. Messaging this allocation would result in a error when zombies are enabled.

What should be done instead?

If you're not responsible for returning the memory at self (that is, you did not write an allocator), leave it alone - it is useless.
You have to learn proper reference counting.
For a better understanding of release and autorelease usage, set up some breakpoints and understand how they are used, in what cases, etc. You'll still have to learn to use reference counting correctly, but this can aid your understanding of why it's useless.
Even simpler: use Instruments to track allocs and ref counts, then analyze the ref counting and callstacks of several objects in an active program.

Historical/explanatory: Why does Apple provide this method in the NSObject protocol if it's not intended to be used? Does Apple's code rely on retainCount for some purpose? If so, why isn't it hidden away somewhere?

We can assume that it is public for two primary reasons:

*

*Reference counting proper in managed environments. It's fine for the allocators to use retainCount -- really. It's a very simple concept. When -[NSObject release] is called, the ref counter (unless overridden) may be called, and the object can be deallocated if retainCount is 0 (after calling dealloc). This is all fine at the allocator level. Allocators and zones are (largely) abstracted so... this makes the result meaningless for ordinary clients. See commentary with bbum (below) for details on why retainCount cannot be equal to 0 at the client level, object deallocation, deallocation sequences, and more.

*To make it available to subclassers who want a custom behavior, and because the other reference counting methods are public. It may be handy in a few cases, but it's typically used for the wrong reasons (e.g. immortal singletons). If you need your own reference counting scheme, then this family may be worth overriding.

For deeper understanding: What are the reasons that an object may have a different retain count than would be assumed from user code? Can you give any examples*** of standard procedures that framework code might use which cause such a difference? Are there any known cases where the retain count is always different than what a new user might expect?

Again, a custom reference counting schemes and immortal objects. NSCFString literals fall into the latter category:
NSLog(@"%qu", [@"MyString" retainCount]);
// Logs: 1152921504606846975

Anything else you think is worth mentioning about retainCount?

It's useless as a debugging aid. Learn to use leak and zombie analyses, and use them often -- even after you have a handle on reference counting.

Update: bbum has posted an article entitled retainCount is useless. The article contains a thorough discussion of why -retainCount isn't useful in the vast majority of cases.

A: The general rule of thumb is if you're using this method, you better be damn sure you know what you're doing. If you are using it for debugging a memory leak you're doing it wrong, if you're doing it to see what is going on with an object, you're doing it wrong.
There is one case where I have used it, and found it useful. That is in doing a shared object cache where I wanted to flush the object when nothing had a reference to it anymore. In this situation I waited until the retainCount is equal to 1, and then I can release it knowing that nothing else is holding onto it, this will obviously not work properly in garbage collected environments and there are better ways to do it. But this is still the only 'valid' use case I've seen for it, and isn't something a lot of people will be doing.


text:
Q: iCloud fails with core data - partial updates - undocumented error message I am trying to sync the data of a core data app between two devices via iCloud. It basically seems to work, but it mostly fails. Data does not show up, or shows up randomly / partially. Sync takes forever (sometimes: hours).
Of course I tried all obvious remedies such as deleting the apps and data from the devices etc.
I get the following messages (relevant excerpt):
[_PFUbiquityRecordsImporter operation:failedWithError:](839):
CoreData: Ubiquity:  Import operation encountered an error:
Error Domain=NSCocoaErrorDomain
Code=134060 "The operation couldn't be completed.
(Cocoa error 134060.)" UserInfo=0x1106a6a0
{exception=Attempted to perform an operation without an open database}
while trying to import the log file at the URL:
<PFUbiquityTransactionLog: 0x11062710>

right after
CoreData: Ubiquity: Error importing transaction log:
<PFUbiquityTransactionLog: 0x110eb820>

and later
-[_PFUbiquityRecordsImporter operation:failedWithError:](824):
CoreData: Ubiquity:  Import operation encountered a corrupt log file,
Error Domain=NSCocoaErrorDomain Code=134302
"The operation couldn't be completed. (Cocoa error 134302.)"
UserInfo=0x12e0b0 {underlyingError=Error Domain=NSCocoaErrorDomain Code=19
"The operation couldn't be completed. (Cocoa error 19.)" UserInfo=0x1af070
{NSUnderlyingException=error during SQL execution : constraint failed,
NSFilePath=/var/mobile/Applications/
59087988-334C-40DC-9F6A-C7DA22F7B790/Documents/database.sqlite,
NSSQLiteErrorDomain=19}, reason=Error encountered while importing
transaction log at URL: <PFUbiquityTransactionLog: 0xe87b3f0>

Any clues about this "without an open database" error?
What to do about the "corrupt log file"?

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL Adding external space for storage tables I would like to add more freespace to storage mysql tables.
I have tried use symbolic links with curlftpfs/sshfs (first create table, then move to ftp and add ln -s) but mysql gives me error  "Operating system error number 95 in a file operation." on start.
I have VPS and FTP server (with SSH access), I would like connect remotely FTP space to my VPS which will be used to store ibd data.
Data tables must be store only on external server, not on VPS.
I am using InnoDB engine, 5.5.50 Mariadb, centos 7.
Do you have any ideas how to do it?
Thanks

A: Choice 1:  Bigger disk drive.  Some OSs allow dynamic addition of drives to add space.
Choice 2:  If the OS can see another drive, you may be able to ask MySQL to put certain files on that drive.
No, you cannot use FTP or other "remote" mechanisms.


text:
Q: Fit child div with `aspect-ratio` to parent in Firefox It's 2021 and aspect-ratio is supported in all modern browsers. Several years ago someone asked a question about how to fill a parent while maintaining an aspect ratio, however the sole answer that mentioned aspect-ratio produces an incorrect result in Firefox.
What is the correct way to expand an element to fit its parent while contrained to its aspect-ratio property? The result I desire is exactly what was shown in that other question:

Here is a non-working starter snippet, see how it breaks when the parent is made wider:

#parent {
  display: grid;
  place-content: center;

  width: 100px;
  height: 150px;
  resize: both;
  overflow: auto;
  border: 2px solid black;
}

#child {
  aspect-ratio: 1 / 1;

  background: yellow;
  border: 2px solid orange;
}

I should be an expanding square!


text:
Q: Click through menu with sub-menu children So I'm not sure if this design has a proper name, so It's hard to know what to look for.
With touch screen interfaces sometimes you get a grid of tiles that are options and you can click one and it will show some new tile options like you're searching for a product and narrowing down the category.
You might start with a tile grid of countries, for the sack of my sanity ill just use letters.
| A | B | C | D |
| E | F | G | H |
|  I  | J | K | L |
..(Scroll for more )..
Then you click a tile and it will load that tiles children like in a map struct, so you could show a tile grid of cities within the chosen country. They choose a country and you show its children such as street names etc ...
Hopefully you get the picture, I'm trying to achieve this on an app I'm building in flutter, I'm not sure if a library or element out there already exists to do this alternatively if anyone has a suggestion on the most efficient way to build this id appreciate it.
My intent was to loop through a variable holding my map at the root and display tiles using Gridview, then when a tile is clicked set that as the variable root and re-render now showing its children. Continuing like this but I'm not sure its the most efficient.
Grid of tiles generated from a map, updating the map to its child when its clicked.

A: try out this package https://pub.dev/packages/multilevel_drawer
here is an example from it
 child: Scaffold(
        drawer: MultiLevelDrawer(
          backgroundColor: Colors.white,
          rippleColor: Colors.white,
          subMenuBackgroundColor: Colors.grey.shade100,
          header: Container(                  // Header for Drawer
            height: size.height * 0.25,
            child: Center(child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset("assets/dp_default.png",width: 100,height: 100,),
                SizedBox(height: 10,),
                Text("RetroPortal Studio")
              ],
            )),
          ),

          children: [           // Child Elements for Each Drawer Item
            MLMenuItem(
                leading: Icon(Icons.person),
                trailing: Icon(Icons.arrow_right),
                content: Text(
                  "My Profile",
                ),
                subMenuItems: [
                  MLSubmenu(onClick: () {}, submenuContent: Text("Option 1")),
                  MLSubmenu(onClick: () {}, submenuContent: Text("Option 2")),
                  MLSubmenu(onClick: () {}, submenuContent: Text("Option 3")),
                ],
                onClick: () {}),
            MLMenuItem(
                leading: Icon(Icons.settings),
                trailing: Icon(Icons.arrow_right),
                content: Text("Settings"),
                onClick: () {},
                subMenuItems: [
                  MLSubmenu(onClick: () {}, submenuContent: Text("Option 1")),
                  MLSubmenu(onClick: () {}, submenuContent: Text("Option 2"))
                ]),
            MLMenuItem(
              leading: Icon(Icons.notifications),
              content: Text("Notifications"),
              onClick: () {},
            ),
            MLMenuItem(
                leading: Icon(Icons.payment),
                trailing: Icon(Icons.arrow_right),
                content: Text(
                  "Payments",
                ),
                subMenuItems: [
                  MLSubmenu(onClick: () {}, submenuContent: Text("Option 1")),
                  MLSubmenu(onClick: () {}, submenuContent: Text("Option 2")),
                  MLSubmenu(onClick: () {}, submenuContent: Text("Option 3")),
                  MLSubmenu(onClick: () {}, submenuContent: Text("Option 4")),
                ],
                onClick: () {}),
          ],
        ),
        appBar: AppBar(
          backgroundColor: Colors.white,
          iconTheme: IconThemeData(color: Colors.black),
          title: Text(
            "Multi Level Menu",
            style: TextStyle(color: Colors.black),
          ),
        ),
        body: Container(
            decoration: BoxDecoration(
              gradient:
              LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
                Color.fromRGBO(255, 65, 108, 1.0),
                Color.fromRGBO(255, 75, 43, 1.0),
              ]),
            ),
            child: Center()),
      ),


text:
Q: Angular login Authentication Error I am NEW to Angular. I am using this Angular method to user to log into the system.
loginuser(){
    const user = {
      username: this.username,
      password: this.password
    };
    this.Auth.loginUser(user).subscribe((res)=>{
      if(res){
        this.Auth.storeData(res.token, res.user);
        this.flashMessage.show('You are Successfully logged In.', { cssClass: 'alert-success', timeout: 5000 });
        this.router.navigate(['/userProfile']);
      }else{
        this.flashMessage.show('You are Password or Username not Correct.', { cssClass: 'alert-success', timeout: 5000 });
        this.router.navigate(['/login']);
      }

    });
  }

But I got a error in my VScode editor showing like this.

And my angular-cli also showing these errors.

But in my node function I clearly define those parameters. And this is my node function.
router.post('/login', (req, res)=>{
    const name = req.body.username;
    const password = req.body.password;
    //console.log(password);
    User.findByName(name,(err, user)=>{
        if(err) throw err;
        if(!user){
            res.json({state: false, msg:"No User Found"});
            //return false;
        }
        User.passwordCheck(password,user.password, (err, match)=>{
            if(err) throw err;

            if(match){
                const token = jwt.sign({User} , config.secret, {expiresIn:86400*3});
                res.json({
                    state: true,
                    token: "JWT" + token,
                    user:{
                        id:user._id,
                        name:user.name,
                        ID:user.ID,
                        IDexpDate: user.IDexpDate
                    }
                });
            }else {
                res.json({state:false,msg:"password does not match"});
            }
        });

    });
    console.log(password);
});

I am using Angular version 6 to develop this application. I search for this in many areas unfortunately I cannot find any problem like this. I think my service functions also will need to give an answer so this are my service files.
readonly baseURL ='http://localhost:3000/users/login';
storeData(token,userdata){
    localStorage.setItem("tokenid",token);
    localStorage.setItem("user",JSON.stringify(userdata));
    this.authtoken = token;
    this.user= userdata
  }
  loginUser(user){
    let header = new HttpHeaders();
    header.append('Content-Type','application/json');

    return this.http.post(this.baseURL,user,{headers:header});
  }

But when I console.log those res.token and res.user that gives me values in my console log. My problem is why that vscode editor show me error like that. Thank you very much for you to give your valuable time to help me.

A: What you define in Node for response types doesn't carry over to your typescript.. you have to define it manually.
By referencing resp.user and resp.token Angular expects you to define your response to declare these objects. By setting resp: any you are telling Angular not to actually care to look for matching types.
If you always expect your response here to contain a user and token, it would be better to declare the response:
resp: {
user: string,
token: string
}


text:
Q: NFS protocol vs iSCSI protocol I was reading some articles on VMware ESXi about storage. One thing mentioned was the advantages of being able to use vMotion, DRS and etc. to achieve High Availability. The one thing that I kept seeing was the word "Shared Storage".
What does this mean?
Right now I am running my ESXi server with an iSCSI backend (single linux server).
Is that considered shared storage, even though only one server can connect to a single target.
Considering NFS allows many connections to the same data does it have advantages over iSCSI?
Can someone gives me an idea?
I am thinking about converting my iSCSI server to NFS.
Also does ESXi (4.0+) support NFSv4?

A: More than a single initiator can connect to a single iSCSI target, if the target is configured to allow it.
All of the benefits of having shared storage in ESXi are available with both iSCSI and NFS.  Beyond that, which is "better" to use is subjective, which doesn't belong here.

A: Another aspect is that you cannot reduce the size of your iSCSI/VMFS partition on your SAN, however you may be able to reduce the NFS partition depending which SAN you own. A Netapp can reduce an NFS partition (if there's space free of course).
A small side effect on your VM's, when you use NFS, you will not be able to see the disk performance of your VM's.

A: What's not mentioned here is that the VMFS filesystem and NOT iSCSI per se is what makes storage share-capable. Not all filesystems allow access from more than one system at a time. Clearly NFS does. Something critically important to note is that iSCSI is block-level over IP, while NFS is a file-level protocol/filesystem. There is a ton of advantages to NFS, that are simply not an option with iSCSI. I work for Nexenta, and every day we spend hours in debates of what is better. Ultimately, it does come down to what your environment needs, and the level of knowledge of iSCSI and NFS by the staff expected to support it.
Multiple iSCSI initiators can connect to the same target, and assuming that configuration allows multiple clients can access the same LUN. VMFS allows for this, and that's how DRS clusters work. Without this ability you could not do a lot of what clustering offers, such as Vmotion, etc.
NFS is by default a shared filesystem. When you build a datastore on NFS, assuming you export NFS to all notes in your DRS cluster, all files stored on the NFS datastore are accessible from all hosts in the cluster.
Again, difference is NFS is a filesystem. iSCSI is a SCSI-3 protocol delievered via IP. Not all filesystems delievered via iSCSI are natively capable of being shared. NFS is natively a shared filesystem.

A: I prefer iSCSI over NFS for running data-stores because,
iSCSI is far more secure by allowing mutual chap authentication.
iSCSI bandwidth I/O is less than NFS. iSCSI uses MPIO ( Multi Pathing ) plus you get block based storage & LUN Masking.
NFS data-stores have been in my case at least susceptible to corruption with SRM. NFS speed used to be a bit better in terms of latency but it is nominal now with all the improvements that have came down the pipe. NFS in my opinion is cheaper as almost any thing can be mounted that is a share.
I obviously prefer iSCSI but, iSCSI solutions or even FC are a bit more expensive. I would mount a NFS and iSCSI DS and run VMwark and see what your IOPs are, that would probably be the best way. As far as NIC bonding, where would you bond at ? The appliance level ( your NAS ) or at the VKernel level ?
And to answer your question ESXi 4 / 4.1 only support NFSv3.

A: I work in a NetApp troubleshooting environment on a daily basis and here are some notes I'd like to add which may influence one's final decision on which method of connecting to back-end storage may be most appropriate for them.
iSCSI can have significantly less overhead as it is a block-based protocol (host-side management of filesystem) and MPIO can be used with it as previously indicated here, which is a big draw to its side.
But one must also note that if you are planning on using thin-provisioning (no space guarantees on storage) in your environment, you may also need to implement some strategy to free up blocks again on the storage-side after they are released from the host lun (using the VAAI, UNMAP API - http://blogs.vmware.com/vsphere/2012/04/vaai-thin-provisioning-block-reclaimunmap-in-action.html ). Also, I do believe that VMware may have disabled VAAI UNMAP in certain releases for awhile due to some performance implications ( http://blogs.vmware.com/vsphere/2011/09/vaai-thin-provisioning-block-reclaimunmap-issue.html ).
If one uses NFS, then the blocks are managed by the storage appliance natively, and thus hole-punching to clean up once blocks are released is not necessary.
Just another consideration in the big picture...


text:
Q: likelihood of major earthquake each year when only 30 year probability is known Everyone, in the Bay Area we hear that the likelihood of a 7.1 magnitutude earthquake on our local Hayward Fault that would cause liquefaction is 31% sometime in the next 30 years.
What I'd like to understand is how you calculate the probability of that magnitude earthquake EVERY year of that 30 year time span. And does it increase every year that the event does not occur?

A: Assuming the likelihood of such a quake happening in the span of a year is $x$, and assuming independence between the year, then the likelihood of it never happening in the next 30 years is $(1-x)^{30}$, and hence the probability of it happening at least once is $1-(1-x)^{30}$  So, solve for:
$$1-(1-x)^{30} = 0.31$$

A: Another reasonable sounding assumption is that large earthquakes are anticorrelated in time because the fact that one happens will relieve the stress and prevent another one from happening soon.  If 30 years qualifies as soon you can't have more than one earthquake in the span and you can just say it is $\frac {31}{30}\%\approx 1.03\%$ per year for that span.  I don't claim this is a better model than independence, which gives about $1.23\%$ per year.  This gives an idea of how the assumptions can change the result.


text:
Q: Why does floating of my example not work I have a simple question and I do not understand why this is not working:
HTML PART:

  KSDfao oasdkfo posfk  ojsf a osjdf klksj f lkjsdf lkjas j lsajf lkjf  jasfd
  lksf dfj ksfpwo ksdas dflkj jf kasjf ajsfl kasjdfkjasf 9j4k lsidjf  ijsf
  öskjdf jsd falksdjf öaslkjfinkasdn ig sadf sadf sadf sadf asd fas dfsd as
  fasd fasd fasd fasd fasd fs fsdf asdfsadf sd fsad fsad fasd fasd fasd fasdf
  sdf as f

Right

CSS PART
.main{
    position:relative;
    width: 300px;
}

.right{
    poition: absolute;
    top: 0px;
    float: right;
    border: 1px solid #00f;
    padding: 20px;
    width: 50px;
}

Text should float around the div. What is the problem here?

A: Is this the layout you were going for? If so, remove the position: absolute, and put your right div before your text in your markup.

.main {
  width: 300px;
}
.right {
  float: right;
  border: 1px solid #00f;
  padding: 20px;
  width: 50px;
}

Right

    KSDfao oasdkfo posfk ojsf a osjdf klksj f lkjsdf lkjas j lsajf lkjf jasfd lksf dfj ksfpwo ksdas dflkj jf kasjf ajsfl kasjdfkjasf 9j4k lsidjf ijsf öskjdf jsd falksdjf öaslkjfinkasdn ig sadf sadf sadf sadf asd fas dfsd as fasd fasd fasd fasd fasd fs fsdf
    asdfsadf sd fsad fsad fasd fasd fasd fasdf sdf as f


text:
Q: NavigateTo same page again does not refresh? I have 2 pages in my Windows Phone 8 XAML app, "MainPage" and "Play".
I NavigateTo Play from MainPage, then hit the back button to return to MainPage.
Once I NavigateTo Play again, 2 things happen that I find confusing:

*

*My constructor for Play is called again, yet the controls on the page still contain data from the last page visit.

*Even though I see data in page members the data does not render on the screen.
There's something basic here I'm missing? How do I either get a completely new page; or re-render the previous instance?
Thanks
-John

A: You can use different class to hold your data, I think that is the problem. You can see this for more info.


text:
Q: pandas date_range giving wrong result shouldn't the below example include '2022-01-01'?
>>> import pandas as pd
>>> pd.date_range("2022-01-03", "2023-12-31", freq='MS')
DatetimeIndex(['2022-02-01', '2022-03-01', '2022-04-01', '2022-05-01',
               '2022-06-01', '2022-07-01', '2022-08-01', '2022-09-01',
               '2022-10-01', '2022-11-01', '2022-12-01', '2023-01-01',
               '2023-02-01', '2023-03-01', '2023-04-01', '2023-05-01',
               '2023-06-01', '2023-07-01', '2023-08-01', '2023-09-01',
               '2023-10-01', '2023-11-01', '2023-12-01'],
              dtype='datetime64[ns]', freq='MS')

A:
How do we get start of the month in that case? inclusive of 2022-01-01

In this case, use pd.offsets.MonthBegin:
>>> pd.date_range("2022-01-03", "2023-12-31", freq='M') + pd.offsets.MonthBegin(-1)
DatetimeIndex(['2022-01-01', '2022-02-01', '2022-03-01', '2022-04-01',
               '2022-05-01', '2022-06-01', '2022-07-01', '2022-08-01',
               '2022-09-01', '2022-10-01', '2022-11-01', '2022-12-01',
               '2023-01-01', '2023-02-01', '2023-03-01', '2023-04-01',
               '2023-05-01', '2023-06-01', '2023-07-01', '2023-08-01',
               '2023-09-01', '2023-10-01', '2023-11-01', '2023-12-01'],
              dtype='datetime64[ns]', freq=None)


text:
Q: How to make simple GUI graph with Linear Equation I am a beginner programmer. I have a task to make a GUI with a linear equation y=mx+b and a set of parameters where I can change the m and b values. I have both matplotlib and numpy. I also have tkinter for the GUI. This is what i have so far i edited my friends code on a coordinate GUI.
 def onButtonValChange():
    if X1.get() != '':
        x[0] = float(X1.get())

    if Y1.get() != '':
        y[0] = float(Y1.get()

def createGraph(x,y):
    graphRoot = Tk.Tk()
    graphRoot.wm_title("Your Graph")
    graphRoot.resizable(0,0)
    f = Figure(figsize=(5, 4), dpi=100)
    a = f.add_subplot(111)
    a.plot(x, y)
    canvas = FigureCanvasTkAgg(f, master=graphRoot)
    canvas.show()
    canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

x = [1]
y = [1]
ButtonChangeValues = Tk.Button(root, text="Submit Change", command=onButtonValChange)
ButtonChangeValues.grid(row=11, columnspan=3)

ButtonCreateGraph = Tk.Button(root, text="Create This Graph", command=lambda: createGraph(x, y))
ButtonCreateGraph.grid(row="15", columnspan=3)

Tk.mainloop()

A: So here is some code that i use its a moving line graph but you could adapt the code to move only when you change the equation. all you would have to do is populate the lists of x0Coords y0Coords and xy0Coords with the right mx+b formula
# Run from IDLE or LXTerminal not IDLE 3
# for import spidev to work, must run as python (v2) not python3

from Tkinter import * #to run on python 2, use Tkinter, for python3 use tkinter
import math
from datetime import datetime, timedelta
import numpy as np
import spidev

#--------------------- variables -------------------------
#---user defined settings
screenWidth = 450
resolution = 5 #number of pixels between data points, for visual purposes only
samplePeriod = 100 #milliseconds, time between data points written to txt file
timeRange = .5 #minutes
#---end user settings

baseTime = int(timeRange*60*1000/screenWidth)
startTime = datetime.now()

nl = "\n"
root = Tk()
root.title("Simple GUI")
root.geometry("500x300") #widthxheight

C = Canvas(root, bg = "gray", height = 250, width = screenWidth)

x0Coords = []
y0Coords = []
xy0Coords = []

coordLength = int(screenWidth/resolution)

#---initiation of lists
for i in range(0,coordLength):
    x0Coords.append(i*resolution)
    y0Coords.append(125)
    xy0Coords.append(0)
    xy0Coords.append(0)

#putting X and Y corrdinites in a list
def coordinate():
    global x0Coords, y0Coords, xy0Coords
    for i in range(0,coordLength*2,2):
        xy0Coords[i] = x0Coords[i/2]
        xy0Coords[i+1] = y0Coords[i/2]
    #print(xy0Coords)
#---End initiation of lists

c0 = C.create_rectangle(0,0,20,50)
cl0 = C.create_line(xy0Coords)
pressure = Label(root, text="test")
pressure.pack()

spi_0 = spidev.SpiDev()
spi_0.open(0, 0)

#--------------------------- End of Variables -------------------------

#--------------------------- Definitions ------------------------------

#shifts y values down in index in array to represent time moved forward
def shiftCoords(nextValue):
    global y0Coords, xy0Coords
    y0Coords.pop(0)
    y0Coords.append(nextValue)
    coordinate()

#updates the GUI based on the new time
def move_time():
    global c0,cl0,xy0Coords, resolution, baseTime
    C.delete(c0)
    C.delete(cl0)
    c0 = C.create_rectangle(0,0,20,int(float(readadc_0(0))/1023*250))
    shiftCoords(125-int(float(readadc_0(0))/1023*125))
    cl0 = C.create_line(xy0Coords)
    #print(float(readadc_0(0))/1023*250)
    root.title("V= " + str(round(3.3*float(readadc_0(0))/1023,2)))
    root.after(baseTime*resolution,move_time)

C.pack()
root.after(baseTime,move_time)
root.after(samplePeriod,writeData)
root.mainloop()


text:
Q: CSS - Change drop down list/menu so they are same in all browsers I have some drop down lists on my website, Currently they change their display depending on what browser/os they are being displayed on.
I would like to know how I could change their display so it looks the same on all browsers (preferably how it is displayed using a mac)
Any help would be much appreciated!!
this is my current code
<select name="university" id="university" >
          <option value="Aston">Aston University</option>
        </select>

A: Allright, you can use a bit of javascript and css for this.
Aston University<select><option value="Aston">Aston University</option></select>

Set position relative on the .select and have the actual <select> fill up the entire space within by setting it to position absolute and using top:0;left:0;bottom:0;right:0;. Set opacity 0 on the <select>, de options will still be visible after a click. Use javascript to get the current value from the <select> and update the inner span with that value (also listen to change event).
Voila, you can now style your .select whichever way you like.


text:
Q: SiFR Only replacing content 'above the fold' I'm trying to use siFR to replace H1 and H2 content on my page but it appears to be only replacing the first two.
There are about 8 in all so some of them aren't on the page until you scroll down, and it appears that siFR is only replacing the items "above the fold"
I know next to nothing about javascript so can anyone tell me how to solve this so it replaces all of the H1's and H2's

A: Try to use servlets. This may help you solving your issue. You may find some good tutorials online.


text:
Q: Entity Framework null object I have simple DBcontext class called OdeToFoodDb:
public class OdeToFoodDb: DbContext
{
    public DbSet<Restaurant> Restaurants { get; set; }
    public DbSet<Review> Reviews { get; set; }

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Restaurant>()
            .HasMany(resturant => resturant.Reviews)
            .WithRequired(review => review.Resturant);
        base.OnModelCreating(modelBuilder);
    }
}

and the class definition:
public class Restaurant
{
    //public virtual int ID { get; set; }
    public virtual int RestaurantId { get; set; }
    public virtual string Name { get; set; }
    public virtual Address Address { get; set; }
    public virtual IList<Review> Reviews { get; set; }
}

public class Review : IValidatableObject
{
    public int ReviewId { get; set; }

    [DisplayName("Digning Date")]
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    [DataType(DataType.Date)]
    public DateTime Created { get; set; }

    [Range(1, 10)]
    public int Rating { get; set; }

    [Required]
    [DataType(DataType.MultilineText)]
    public string Body { get; set; }
    public int RestaurantId { get; set; }
    public Restaurant Resturant { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var fields = new[]{ "Created"};

        if(Created > DateTime.Now)
        {
            yield return new ValidationResult("Created date cannot be in the future.", fields);
        }

        if (Created < DateTime.Now.AddYears(-1))
        {
            yield return new ValidationResult("Created date cannot be to far in the past.", fields);
        }
    }
}

my problem is when i select a review from dbcontext like this:
    OdeToFoodDb _db = new OdeToFoodDb();
    public PartialViewResult LatestReview()
    {
        var review = _db.Reviews.FindTheLatest(1).Single();
        //************************************
        return PartialView("_Review", review);
    }

I checked that the review.Restaurant is null! while the other property have a value. What is wrong with my code?

A: Either load navigation property Restaurant explicitly via Include method:
var review = _db.Reviews.Include(r => r.Restaurant).FindTheLatest(1).Single();

or you can enable lazy loading for that property, by making it virtual:
public virtual Restaurant Restaurant { get; set; }

You can read more about loading related entities here.


text:
Q: How can I do subplots in matplotlib with differents xlimit and size of axis-x? How can I solve this? I want to do 4 subplots with matplotlib, I have used the subplot option but the result is just a big plot. I don't have idea what is the problem.  I want to see four subplots, each one with title, and a suptitle for them.
I don't have idea how can I solve it?
Can you help me please to fix it?
Thanks a lot
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals
from matplotlib.collections import LineCollection
import matplotlib.patches as mpatches
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.ticker as tkr
from pylab import text

with open("file1.txt") as f:
         m1 = map(float,f)

with open ("file2.txt") as f:
         m2 = map(float, f)

fig, ax = plt.subplots(sharey='row')
fig.set_figwidth(18)  #Width figure
fig.set_figheight(12) #Height figure

plt.rcParams['figure.dpi'] = 300
plt.subplots_adjust(wspace=0.18, hspace=0.2)

fig.suptitle('PLOTS', y=0.93, fontsize=15)

# Plot
plt.subplot(421)
y = np.array(m1)
x = np.arange(len(y))
threshold = 0.5
segments_x = np.r_[x[0], x[1:-1].repeat(2), x[-1]].reshape(-1, 2)
segments_y = np.r_[y[0], y[1:-1].repeat(2), y[-1]].reshape(-1, 2)
linecolors = ['red' if y_[0] > threshold and y_[1] > threshold else 'blue'
              for y_ in segments_y]
segments = [zip(x_, y_) for x_, y_ in zip(segments_x, segments_y)]
ax = plt.axes()
ax.add_collection(LineCollection(segments, colors=linecolors))
ax.set_ylim(-0.06, 1.07)
ax.set_xlim(0,268)
blue_patch = mpatches.Patch(color='blue', label='ordenada')
red_patch = mpatches.Patch(color='red', label='desordenada')
plt.legend(handles=[blue_patch, red_patch], loc='lower left', fontsize=12)
plt.axhline(y=0.5, color='black', linestyle='--')
plt.title(r'Protein', fontsize=18)
plt.xlabel(r'# Residue', fontsize=16)
plt.ylabel(r'(%)', fontsize=16)
plt.xticks(size=12)
plt.yticks(size=12)
plt.xticks(np.arange(min(x), max(x)+1, 10))
plt.grid()
plt.tight_layout()

# Plot
plt.subplot(423)
p = np.array(m2)
o = np.arange(len(p))
threshold = 0.5
segments_o = np.r_[o[0], o[1:-1].repeat(2), o[-1]].reshape(-1, 2)
segments_p = np.r_[p[0], p[1:-1].repeat(2), p[-1]].reshape(-1, 2)
linecolors = ['red' if p_[0] > threshold and p_[1] > threshold else 'blue'
              for p_ in segments_p]
segments = [zip(o_, p_) for o_, p_ in zip(segments_o, segments_p)]
ax = plt.axes()
ax.add_collection(LineCollection(segments, colors=linecolors))
ax.set_ylim(-0.06, 1.07)
ax.set_xlim(0,383)
blue_patch = mpatches.Patch(color='blue', label='ordenada')
red_patch = mpatches.Patch(color='red', label='desordenada')
plt.legend(handles=[blue_patch, red_patch], loc='lower left', fontsize=12)
plt.axhline(y=0.5, color='black', linestyle='--')
plt.title(r'Protein', fontsize=18)
plt.xlabel(r'# Residue', fontsize=16)
plt.ylabel(r'(%)', fontsize=16)
plt.xticks(size=12)
plt.yticks(size=12)
plt.xticks(np.arange(min(o), max(o)+1, 10))
plt.grid()
plt.tight_layout()
plt.show()

#plt.savefig('figure.png', format='png', bbox_inches="tight", dpi=300)

How can I solve this?
where is the problem?

A: You need to specify the number of plots you want to be created by matplotlib.pyplot.subplots,
nrows = 2
ncols = 2
fig, ax = plt.subplots(nrows, ncols, sharey='row')

which will create an array of axes instances with shape (nrows, ncols). You can then plot to individual axes via
ax[0,0].plot(...)

Although in order to set tick properties, labels, etc for the axes you need to use the axes versions of the functions instead of the pyplot versions. I.e.
ax[0, 0].set_xticks(...)
# instead of
plt.xticks(...)

ax[0, 0].set_title(...)
# instead of
plt.title(...)

ax[0, 0].set_xlabel(...)
# instead of
plt.set_xlabel(...)


text:
Q: Docker - Exposed ports accessible from outside - iptables rules ignored I have a docker container running like:
 docker run --name some_container_1 -p 8080:80 -d some_image

Which works fine. The container exposes it's port 80 to 8080 and is accessible from localhost.
For some reason however it's ignoring the INPUT iptables rules completely and is also accesible from outside.
How can I restrict access to my Docker container to only allow i.e. IP 123.456.789.0 to access it from external?
Thanks.

sudo iptables -L -n -v --line-numbers
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination
1        0     0 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
2      365 23380 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
3        0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:22
4        7   788 LOG        all  --  *      *       0.0.0.0/0            0.0.0.0/0            limit: avg 5/min burst 5 LOG flags 0 level 7 prefix "iptables denied: "
5        7   788 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination
1       24  1524 DOCKER     all  --  *      docker0  0.0.0.0/0            0.0.0.0/0
2        0     0 ACCEPT     all  --  *      docker0  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
3       15 13320 ACCEPT     all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0
4        0     0 ACCEPT     all  --  docker0 docker0  0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT 204 packets, 21792 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain DOCKER (1 references)
num   pkts bytes target     prot opt in     out     source               destination
1       24  1524 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:80

sudo iptables-save
# Generated by iptables-save v1.4.21 on Wed Apr  8 23:37:43 2015
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [100:16642]
:DOCKER - [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
-A INPUT -j DROP
-A FORWARD -o docker0 -j DOCKER
-A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -i docker0 ! -o docker0 -j ACCEPT
-A FORWARD -i docker0 -o docker0 -j ACCEPT
-A DOCKER -d 172.17.0.2/32 ! -i docker0 -o docker0 -p tcp -m tcp --dport 80 -j ACCEPT
COMMIT
# Completed on Wed Apr  8 23:37:43 2015
# Generated by iptables-save v1.4.21 on Wed Apr  8 23:37:43 2015
*nat
:PREROUTING ACCEPT [13:2206]
:INPUT ACCEPT [1:64]
:OUTPUT ACCEPT [4:268]
:POSTROUTING ACCEPT [4:268]
:DOCKER - [0:0]
-A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER
-A OUTPUT ! -d 127.0.0.0/8 -m addrtype --dst-type LOCAL -j DOCKER
-A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
-A POSTROUTING -s 172.17.0.2/32 -d 172.17.0.2/32 -p tcp -m tcp --dport 80 -j MASQUERADE
-A DOCKER ! -i docker0 -p tcp -m tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80
COMMIT
# Completed on Wed Apr  8 23:37:43 2015

docker info
Containers: 1
Images: 25
Storage Driver: aufs
 Root Dir: /var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 27
Execution Driver: native-0.2
Kernel Version: 3.16.0-4-amd64
Operating System: Debian GNU/Linux 8 (jessie)
CPUs: 4
Total Memory: 7.746 GiB
Name: nuc-001
ID: WCMU:MN3T:VFKR:IU42:6423:OEI6:IB5Q:WBNV:K75H:JZDS:UWU5:57WD
WARNING: No memory limit support
WARNING: No swap limit support

A: You can bind the port to your local machine. Then docker will not expose the port to the outside. (iptables)
docker run -p 127.0.0.1:8080:8080 some_image

A: Internally Docker is using iptables to forward connections to the docker host on port 8080 to the service listening on port 80 on the container. The key in your configuration is this line -
-A DOCKER ! -i docker0 -p tcp -m tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80
By inserting (-I) a new forward line, you can block connections from being forwarded to the container IP, in this case 172.17.0.2. Try this rule -
/sbin/iptables -I FORWARD '!' -s  123.456.789.0 -d 172.17.0.2 -p tcp --dport 80 -j DROP


text:
Q: Format a number that can be variably rounded with thousand separator I have code that ends up with a variable "dTot" which will be a number with up to 5 decimal places.
The user has an option to set the number of decimal places for rounding dTot, user selection is assigned to a variable "iDP", this can be anything between 0 and 5.
dTot = Round(dTot, iDP)` works just fine.
But, I also need to format the rounded number with thousand separator when adding to to another array.
Format(Round(dTot, iDP), "#,##0.00000")
works if iDP is 5, and
Format(Round(dTot, iDP), "#,##0.00")
if iDP is 2
How can I get the format to follow the iDP value?
I know I could use "Select Case iDP" and have 6 Cases, but since the formatting needs to be applied to up 6 expressions in each of 200 rows in the array I was hoping to find a way to avoid "Select Case"

A: Build the format mask string as needed.
Format(Round(dTot, iDP), "#,##0" & IIF(iDP, ".", "") & string(iDP, "0"))

A: EDIT: Added the brilliant '& IIF(iDP, ".", "")' used in the accepted answer by user10825204:
WorksheetFunction.Rept vs Replace(Space)
WorksheetFunction.Rept
Format(Round(dTot, iDp), "#,##0" _
    & IIF(iDP, ".", "") & WorksheetFunction.Rept("0", iDp))

Replace(Space)
Format(Round(dTot, iDp), "#,##0" _
    & IIF(iDP, ".", "") & Replace(Space(iDp), " ", "0"))


text:
Q: Nickelodeon special with puppets as "Goblins", looking for a crown This show was a late 80s/early 90s Nickelodeon or Nick Jr. special, utlizing puppets and live action cast members. It definitely wasn't The Dark Crystal. As I remember it, the basic premise was as follows:
Two factions of Goblins are trying to choose a king, and to do so they have to get a special crown before the end of one particular day. This day is the only time in which the crown can be touched, as Goblins can usually only move at night; if they are exposed to sunlight on any other day, they will turn to stone. The current king and his son are trying to claim the crown before the leader of the evil faction and his son find it. Somehow, a human boy became involved. At the end, the evil father and son are turned to stone.

A: This is The Crown of Bogg, a 30-minute special from 1981. From IMDb:

It is time to crown a new king of the kingdom of Bogg, and King Mildew's son, Milo, seems like the best creature for the job. However, Vandred, the king's brother, has other plans, and intends to put his son, Vandal, on the thrown. He challenges Milo, who must prove his worthiness by retrieving the Crown of Bogg and returning it to the kingdom. The crown has been banned from the kingdom for years because it is cursed, but Mildew and Milo are willing to face the risks of the quest in order to keep Vandred and Vandal from assuming control of the kingdom. But in order to retrieve the crown, they will have to leave Bogg and go to The Surface...where the humans are.

It's live-action with puppet creatures that are Henson-esque, but this is actually a Paul Fusco production (he created ALF). It ends like you described (the evil father and son run outside and turn to stone). It's currently available in its entirety on Youtube here, and here's that ending:


text:
Q: Laurent expansion on annulus Let $F(z)= \frac{1}{(z-1)^2(z+2)}$.
I need to find a Laurent expansion for $F$ on the annulus $A = \{z: \sqrt{2}<|z-i|<\sqrt{5}$}.
So far I have managed to write $F$ as $F(z)=\frac{-1}{9(z-1)}+\frac{1}{9(z+2)}+\frac{1}{3(z-1)^2}$. Then writing $z-i = w$, I got the following expansions:
$\frac{-1}{9(z-1)}$ = $\frac{-1}{9w} \sum_{n=0}^{\infty} (-1)^{n}(\frac{i-1}{w})^n $
$\frac{1}{3(z-1)^2}$ = $\frac{1}{3w^2} \sum_{n=0}^{\infty} (-1)^{n}(1+n)(\frac{i-1}{w})^n$.
But how do we get the expansion for $\frac{1}{9(z+2)}$?

A: You are interested in the Laurent series centered at $i$, rather than $0$. So, use the fact that\begin{align}F(z)&=F\bigl((z-i)+i\bigr)\\&=\frac1{\bigl((z-i)+i-1\bigr)^2\bigl((z-i)+i+2\bigr)}\\&=\frac1{9\bigl((2+i)+(z-i)\bigr)}+\frac1{9\bigl((1-i)-(z-i)\bigr)}+\frac1{3\bigl((1-i)-(z-i)\bigr)^2}\\&=\frac1{9(2+i)}\frac1{1-\frac{z-i}{2+i}}+\frac1{9(1-i)}\frac1{1-\frac{z-i}{1-i}}+\frac1{3(1-i)^2}\frac1{\left(1-\frac{z-i}{1-i}\right)^2}\\&=\frac1{9(2+i)}\sum_{n=0}^\infty\left(\frac{z-i}{2+i}\right)^n-\frac1{9(1-i)}\sum_{n=-\infty}^{-1}\left(\frac{z-i}{1-i}\right)^n+\\&\phantom{=}\quad-\frac1{3(1-i)^2}\sum_{n=-\infty}^{-2}(n+1)\left(\frac{z-i}{1-i}\right)^n.\end{align}It's only at the last step that I've used the fact that $\sqrt2<|z-i|<\sqrt5$.


text:
Q: Spring MVC testing: How do I check if a model attribute does not exist? I'm using Spring 3.2.11.RELEASE.  I'm using the new 3.2 mock MVC framework for unit testing, and normally I can check for model attributes using something like the following …
private MockMvc mockMvc;
…

@Test
public final void test()
{
…
    mockMvc.perform(get("/mypath")
                    .param("userId", customerId))
                    .andExpect(status().isOk())
                    .andExpect(model().attribute("attr1", "value"))
                    .andExpect(view().name("my view"));

but how would I adjust the above to verify that the attribute "attr1" was NOT included in my model?

A: Even easier approach than Mark's:
.andExpect(model().attributeDoesNotExist("attr"))

A: Since the model attributes are a held in a map you could check that the value of the attribute is null (Assuming that null isn't a valid value for the attribute).
.andExpect(model().attribute("attr1", nullValue());

where nullValue() is org.hamcrest.Matchers.nullValue.


text:
Q: Separate variable name from factor level in character string I am trying to separate the levels of a factor variable from the variable name (the format returned by a model).
My string (sorry: edited to be more representative)
vars <- c("(Intercept)", "wt", "gearyy", "cyl4", "cyl8")

Expected outcome (although a list would also be fine)
#     [,1]   [,2]
#[1,] "wt"   ""
#[2,] "gear" "yy"
#[3,] "cyl"  "4"
#[4,] "cyl"  "8"

My attempt: I thought i may be able to grep to partial search (but no success)
grep(paste0("\\b", "cyl", "\\b") , est$vars )

The model:
library(glmnet)

mtcars$gear <- factor(mtcars$gear, labels=c("xx", "yy", "zz"))
mtcars$am <- factor(mtcars$am, labels=c("yes", "no"))
mtcars$cyl <- factor(mtcars$cyl)

x <- model.matrix(~ wt + disp + gear + am + cyl, data=mtcars,
                  contrasts.arg = lapply(mtcars[sapply(mtcars, is.factor)],
                                         contrasts, contrasts=FALSE))

fit <- glmnet(x, mtcars$mpg)
cfs <- coef(fit, s=0.5)

est <- data.frame(vars=cfs@Dimnames[[1]][cfs@i+1], est=cfs@x, stringsAsFactors=F)

A: Try
 pat <- paste(colnames(mtcars), collapse="|")
 v2 <- sub(pat, '', vars[-1])
 v1 <- sub(paste(v2[nzchar(v2)], collapse='|'), '', vars[-1])
 data.frame(v1, v2)
 #    v1 v2
 #1   wt
 #2 gear yy
 #3  cyl  4
 #4  cyl  8

Update
According to comments from the OP, it may be better to have
 v1 <- sub(paste0(paste0(v2[nzchar(v2)], "+$"), collapse='|'), '', vars)


text:
Q: Spring : treat model variable as JS inside JSP I am using spring MVC. Inside controller I am setting a model value as below:
public class myClassObj{
   private String firstName;
   ..
   // setter getter
}

@RequestMapping(method = RequestMethod.GET,value = "path")
public String getPostGallery(ModelMap model) throws ContentDeletedException
{
    model.addAttribute("data",myClassObj);
    return "myPage";
}

Now inside myPage.jsp I have a function show(d) :
function show(d){
  $.each(d,function(k,v){});
}

If i call show(data) inside AJAX it iterate & display data correctly. but if I pass args as ${} it doesn't.
Is it possible to call show("${data}") and ${data} will be treated as JSON or js object?

A: You first need to set the variable in pageContext using
<c:set var="name" value="${variableNameFromController}"/>

and then in js you can use that variable using EL-Syntax or expression language.


text:
Q: window phone 8 emulator internet connection I was using the win8 phone emulator, but it's internet explorer could not display webpage ,showing no connectivity to internet. I checked a lot from microsoft site and tried, I'm sure that i enabled automatic DNS server.
I'm using wifi connection.
I saw lot of people having this issues as well, have anyone success to solve it?

A: I had the same problem and I configured the Windows Phone Emulator External Interface, on my emulator image. Here is what i did:

*

*Open you Hyper-V Manager

*Right click on the emulator image settings

*Click on Windows Phone Emulator External Interface

*Bind the Virtual switch to your physical network device (on my mbpro was the Intel Pro)

A: In my case only Windows Phone Emulator Internal Switch was configured.
Therefore, I had to add the external switch using those steps:

*

*Open the Hyper-V Manager, and click on your computer name in the
left pane (under Hyper-V Manager).

*Under Actions (on the right), click Virtual Switch Manager..
Virtual Switch Manager window will open, displaying all the
configured virtual switches.

*Verify that you have only one switch - named Windows Phone
Emulator Internal Switch. Its Connection type configured as
Internal network. Leave it as is.

*Now add a new (external) virtual network switch:
Set the Connection type to External Network, choose your active network adapter and check the Allow management operating system to share this network adapter.

*Save the changes and restart your emulator.

You can find more details here.


text:
Q: My slackapp not working on other workspaces My slack app is working perfectly fine on my workspace but when I try to install in on other workspaces, the home tab says "work still in progress".
I have tried different permissions one by one but nothing worked.

A: The "Work in progress" error could mean that you are not passing the correct user id in your views.publish call. Perhaps you are hard-coding the user id from your initial Workspace? Keep in mind that your user id is different in each Workspace. You will also need to extract the user id dynamically in order for other users to see the App Home content.
The best practice here would be to use the Events API and listen for the app_home_opened event. With the response from this event you can then use the user_id to display the view in the App Home for each user that accesses it.
https://api.slack.com/surfaces/tabs/events

A: When you are creating an app under an workspace you can use the current workspace to develop and test the app under all the circumstances.
However, if you want to port or install you Slack app in another workspace you need to install the app in the workspace using the app installation credentials from that workspace. To be specific of your App Home showing 'Work under progress' there may be a few reasons why that shows up:

*

*Check the values of bot token, user id and view payload modal used under the views.publish method.

*Toggle the Home Tab on and off, then re-install the app to workspace.

*Check the installation parameters of your Slack Application in the new workspace.


text:
Q: `-costToNode:` Not Sent to GKGraphNode2D Subclass in GameplayKit I have what is perhaps a stupid question about Apple's new GameplayKit.
I am creating a 2D grid-based node layout for my game. I mostly love the functionality of the GKGraphNode2D, but would like to tweak it in one way. I'd like to conditionally add a penalty when traversing a certain kind of node pair. In other words, I want some nodes connected in a straight-forward way, and some nodes connected such that their traversal distance is modified by my app.
I thought subclassing GKGraphNode2D and overriding -costToNode: and -estimatedCostToNode: would work perfectly! I'd return the value supplied by super sometimes, and tweak it for my game at other times. These two methods are methods on GKGraphNode, the superclass of GKGraphdNode2D.
Unfortunately, when I try to do this, it appears that -costToNode: and -estimatedCostToNode: are never called on my GKGraphNode2D subclass. I would expect these methods to be invoked when I call -findPathFromNode:toNode: on my GKGraph object that contains a bunch of my GKGraphNode2D subclass objects.
What am I doing wrong?
Edit:
The following is my code.
Create two classes, CheapNode and ExpensiveNode, that are subclasses of GKGraphNode2D, as follows:
@import UIKit;
@import GameplayKit;

@interface CheapNode : GKGraphNode2D
@end

@implementation CheapNode

- (float)estimatedCostToNode:(GKGraphNode *)node {
    return 1;
}

- (float)costToNode:(GKGraphNode *)node {
    return 1;
}

@end

and
@import UIKit;
@import GameplayKit;

@interface ExpensiveNode : GKGraphNode2D
@end

@implementation ExpensiveNode

- (float)estimatedCostToNode:(GKGraphNode *)node {
    return 100;
}

- (float)costToNode:(GKGraphNode *)node {
    return 100;
}

@end

Then in a test, I've created some nodes, connected them, added them to a graph, and sent the findPathFromNode:toNode: message to the graph. Then, I check the path that the graph finds, and I don't find what I expect.
- (void)testNodeCostsUsed {
    /*
     This is the graph we are creating:

     A---B---C
     |       |
     F---E---D

     where all of the nodes are `CheapNode` objects, except 'B', which is an
     `ExpensiveNode` object.

     This test finds a path from node A to node C.

     If the cost methods in the `CheapNode` and `ExpensiveNode` subclasses
     are used, the route going from A to C around B (down, then right, then up)
     should be used, since the cost of going from B to C is 100, and the cost of
     going from any other node to any other node is 1
     (see implementation of these classes).

     Instead, we see `GKGraph` choosing the "shortest" route in terms of number
     of nodes, from the top left immediately to the right to the top right.
     */

    CheapNode     *nodeA = [[CheapNode alloc]     initWithPoint:(vector_float2){0, 0}];
    ExpensiveNode *nodeB = [[ExpensiveNode alloc] initWithPoint:(vector_float2){1, 0}];
    CheapNode     *nodeC = [[CheapNode alloc]     initWithPoint:(vector_float2){2, 0}];
    CheapNode     *nodeD = [[CheapNode alloc]     initWithPoint:(vector_float2){2, 1}];
    CheapNode     *nodeE = [[CheapNode alloc]     initWithPoint:(vector_float2){1, 1}];
    CheapNode     *nodeF = [[CheapNode alloc]     initWithPoint:(vector_float2){0, 1}];

    [nodeA addConnectionsToNodes:@[ nodeB, nodeF ] bidirectional:YES];
    [nodeC addConnectionsToNodes:@[ nodeB, nodeD ] bidirectional:YES];
    [nodeE addConnectionsToNodes:@[ nodeF, nodeD ] bidirectional:YES];

    NSArray *allNodes = @[ nodeA, nodeB, nodeC, nodeD, nodeE, nodeF ];

    GKGraph *graph = [GKGraph graphWithNodes:allNodes];
    NSArray *nodes = [graph findPathFromNode:nodeA toNode:nodeC];

    NSArray *expectedPath   = @[ nodeA, nodeF, nodeE, nodeD, nodeC ];
    NSArray *prohibitedPath = @[ nodeA, nodeB, nodeC ];

    XCTAssert([nodes isEqualToArray:expectedPath], @"");
    XCTAssertFalse([nodes isEqualToArray:prohibitedPath], @"");
}

This test case fails. I also notice that estimatedCostToNode: and costToNode: are never sent to my GKGraphNode2D subclasses (as verified by log statements and breakpoints).
Here is a sample project demonstrating this issue. It should build and run on the latest developer beta of Xcode (as of 08/31/2015, Xcode beta 6).
Edit 2:
I have submitted the sample code and the description in this StackOverflow question as a bug (http://www.openradar.me/22524760) if anyone is interested in duping. If the bug persists after iOS 9 is released, I will use a developer support ticket to try to resolve this issue.
Edit 3:
Apple got back to me on my Developer Support Ticket. They admitted this is a bug, and it (as far as I can tell) seems to be fixed in iOS 9.2 beta 2 (7C46t).
Edit 4:
I have updated the sample project to illustrate another bug with this framework.

A: Apple responded to my developer support ticket related to this issue and told me it was a known issue, and that there was a potential fix in the iOS SDK 9.2 beta 2, released November 3, 2015. I verified that the tests in my test project pass in 9.2b2, and so I expect that version to resolve this issue.


text:
Q: Russian language causing IOException I'm making the bot for Google Dictionary using this API https://dictionaryapi.dev/. It's supposed to show  word definitions in different languages. And the bot works just fine for English and Spanish. But there's an IOException every time I put in Russian words. What can be the cause of it?
Here's my Bot class.
Bot.java:
public void onUpdateReceived(Update update) {
        //Model model = new Model();
        WordModel wordModel = new WordModel();
        Message message = update.getMessage();
        if (message != null && message.hasText())
        {
            switch (message.getText()) {
                case "/english":
                    DictionaryEntry.setLanguage("en");
                    sendMsg(message, DictionaryEntry.getLanguage());
                    break;
                case "/russian":
                    DictionaryEntry.setLanguage("ru");
                    sendMsg(message, DictionaryEntry.getLanguage());
                    break;
                case "/spanish":
                    DictionaryEntry.setLanguage("es");
                    sendMsg(message, DictionaryEntry.getLanguage());
                    break;
                default:
                    if (!message.getText().contains("/")) {
                        try {
                            sendMsgs(message, DictionaryEntry.getWords(message.getText(), wordModel));
                        } catch (IOException e) {
                            sendMsg(message, "Не найдено");
                            sendMsg(message, DictionaryEntry.getUrl().toString());
                        }
                    }
                    break;
            }
        }
    }

public void sendMsg(Message message, String text) {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(message.getChatId());
        sendMessage.setReplyToMessageId(message.getMessageId());
        sendMessage.setText(text);
        try {
            //setButtons(sendMessage);
            execute(sendMessage);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

public void sendMsgs(Message message, List<String> words) {
        for (int i = 0; i < words.size(); i++) {
            SendMessage sendMessage = new SendMessage();
            sendMessage.setChatId(message.getChatId());
            sendMessage.setReplyToMessageId(message.getMessageId());
            sendMessage.setText(words.get(i));
            try {
                //setButtons(sendMessage);
                execute(sendMessage);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
    }

And here's my DictionaryEntry class where I process JSON string that I get from URL.
DictionaryEntry.java:
private static String language = "ru";

    public static String getLanguage() {
        return language;
    }

    public static void setLanguage(String language) {
        DictionaryEntry.language = language;
    }

    public static URL getUrl() {
        return url;
    }

    private static URL url;

public static List<String> getWords(String message, WordModel wordModel) throws IOException {
        url = new URL("https://api.dictionaryapi.dev/api/v2/entries/"
                + DictionaryEntry.getLanguage() + "/" + message);

        Scanner in = new Scanner((InputStream) url.getContent());
        String result = "";

        while (in.hasNext())
        {
            result += in.nextLine();
        }

        String result2 = result.replaceAll("\"", "\\\"");

        List<WordModel> models = new ArrayList<>();
        List<String> results = new ArrayList<>();
        int count = 0;

        try {
            JSONArray mainArray = new JSONArray(result2);

            for (int i = 0; i < mainArray.length(); i++) {
                JSONObject wordEntry = mainArray.getJSONObject(i);
                String wordName = wordEntry.getString("word");
                wordModel.setWord(wordName);

                JSONArray meaningsArray = wordEntry.getJSONArray("meanings");
                for (int j = 0; j < meaningsArray.length(); j++) {
                    JSONObject meaningEntry = meaningsArray.getJSONObject(j);
                    JSONArray definitionsArray = meaningEntry.getJSONArray("definitions");
                    for (int k = 0; k < definitionsArray.length(); k++) {
                        //count++;
                        JSONObject definitionEntry = definitionsArray.getJSONObject(k);
                        String definition = definitionEntry.getString("definition");
                        wordModel.setDefinition(definition);

                        if (definitionEntry.has("example")) {
                            count++;
                            String example = definitionEntry.getString("example");
                            wordModel.setExample(example);
                        }
                        else {
                            wordModel.setExample("No examples found");
                        }

                        models.add(wordModel);
                        results.add("Word: " + wordModel.getWord() + "\n\n" +
                                "Definition: " + wordModel.getDefinition() + "\n\n" +
                                "Example: " + wordModel.getExample());
                    }
                }
            }

            /*result = "Word: " + wordModel.getWord() + "\n\n" +
                     "Definition: " + wordModel.getDefinition() + "\n\n" +
                     "Example: " + wordModel.getExample();*/
        } catch (JSONException e) {
            count = 50;
        }

        results.add(url.toString());

        return results;
    }

Here's the stack trace:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.dictionaryapi.dev/api/v2/entries/ru/мышь
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1932)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1528)
    at java.base/java.net.URLConnection.getContent(URLConnection.java:749)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getContent(HttpsURLConnectionImpl.java:404)
    at java.base/java.net.URL.getContent(URL.java:1181)
    at DictionaryEntry.getWords(DictionaryEntry.java:73)
    at Bot.onUpdateReceived(Bot.java:91)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
    at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:321)

A: + URLEncoder.encode(message, "UTF-8")

You are sending a HTTP request. The URL should be appropriate for the used encoding.
There are more aspects of using the right charset/encoding, but this might already be sufficient. The site probably uses UTF-8, as that can handle the full Unicode range.
400 is BAD REQUEST.

url = new URL("https://api.dictionaryapi.dev/api/v2/entries/"
            + DictionaryEntry.getLanguage() + "/"
            + URLEncoder.encode(message, "UTF-8"));

And
    Scanner in = new Scanner((InputStream) url.getContent(),
        StandardCharsets.UTF_8);
    StringBuilder sb = new StringBuilder();
    while (in.hasNextLine())
    {
        sb.append(in.nextLine()).append('\n');
    }
    String result = sb.toString();

A: Check in your environment that the file was in utf-8u format Because Cyrillic may not be supported


text:
Q: How to install a bot to microsoft teams (nodejs) Recently I have created a bot for microsoft teams. I have installed it to my teams successfully.But is there any way where all my organization users can install app by clicking on a single link that is displayed in my web page. For example like (authenticating slack bots, similarly like google auth). and I need to store the teams details of every user so that my bot can send messages to them.

A: If you want to give a link to install the app inside teams from an external webpage, you could do that using Deeplink to app installation. Here's the format of the link https://teams.microsoft.com/l/app/YourAppId. You could also add the app to your tenant app catalaog(Your organisational store) and all the members of your organisation can install the app from there.


text:
Q: switching UIViewController while using storyboard I'm developing an app for iPhone. My problem is, I have a uiviewcontroller that has something like a shortcuts menu. From there, I want to be able to switch page to any on storyboard but just presenting it like this
[self.mainID dismissViewControllerAnimated:YES
                         completion:^{
                             checkin_vc *sampleView = [[checkin_vc alloc] init];
                             [self.mainID presentViewController:sampleView animated:YES completion:nil];
                         }];

doesn't seem to cut it. nothing happens, and if I try to present it without dismissing the current controller first, then I get a black screen, most likely because I'm trying to present an object of class, not the actual view controller that is set up on the storyboard.
i tried
[self.mainID dismissViewControllerAnimated:YES
                         completion:^{
                             UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                             checkin_vc *sampleVIew = (checkin_vc *)[mainStoryboard instantiateViewControllerWithIdentifier:@"checkin_sid"];
                             [self.mainID presentViewController:sampleVIew animated:YES completion:nil];
                         }];

dismiss is done and I'm returned to previous view controller, but completion part never gets done.
I also get this warning:

2014-05-12 00:05:31.388 Roborder[5503:60b] Warning: Attempt to present  on  whose view is not in the window hierarchy!

A: My experience with storyboards is that instantiating via alloc init isn't going to work. Firstly make sure that every view controller you may call has, in the storyboard, a storyboardID set. It's just a unique string but you can use it as below to instatiate:
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
checkin_vc *sampleVIew = (checkin_vc *)[mainStoryboard instantiateViewControllerWithIdentifier:@"checkin_vc"];
//present as original code.

It's late though so let me know if I'm misunderstanding the question :)

A: *

*Cocoadelica's code is correct, but you need give your checkin_vc an Identifier in the storyboard to present it-- check the left panel -- show the identity inspector -- put a string in "Storyboard ID" (for example: checkin view controller)-- then you can use it in the code like this
checkin_vc *sampleVIew = (checkin_vc *)[mainStoryboard instantiateViewControllerWithIdentifier:@"checkin view controller"];

*you should not dismiss the shortcut menu(if it's your root menu) cause you're checkin_vc will lost it's parent(viewcontroller).

*here's my sample code of viewcontroller switch, hope it will help you:
in the MenuViewController.m
    -(IBAction)GotoShop:(id)sender {
      ShopViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ShopController"];
      [self presentViewController:viewController animated:YES completion:nil];
     }

this will present the shopViewController
and in the ShopViewController.m
-(IBAction)QuitShop:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

This will dismiss the shopViewController and return to it's parentviewcontroller --- in this case back to MenuViewController


text:
Q: Why must a primitive root be less than and relatively prime to n? "For instance there are no primitive roots modulo 8.  To see this note that the only integers less than 8 and relatively prime to 8 are 1, 3, 5, and 7..."
The author then proceeds to show that the order of these numbers with $n=8$ is less than $\phi(n)$.  I apologize if this seems basic - (maybe it arises from a definition), but why must primitive roots be less than and relatively prime to $n$?  What is to say that $16^\phi(8)$ is not the smallest power congruent to $1 \mod 8$?

A: The have to be relatively prime to $n$ because if $x$ is a primitive root, then $x^n \equiv 1$ for some $n$, and therefore $x^{n-1}$ must be the multiplicative inverse of $x$. But only numbers relatively prime to $n$ have a multiplicative inverse.
They don't strictly speaking have to be smaller than $n$, but any number larger than $n$ is equivalent modulo $n$ to some number smaller than $n$. Remember that $$
  a \equiv b \mod n \quad\Leftrightarrow\quad \exists k \in \mathbb{Z} \,:\, a - b = kn \text{.}
$$
So if $a \geq n$, we can substract $n$ until we reach an integer $b$ within $[0,n-1]$. If we had to subtract $k$ times, we have $b = a - kn$, i.e. $a - b = kn$, so $a \equiv b \mod n$.


text:
Q: as.Date convert Date in a data frame I'd like to convert a whole column with as.Date to a date format.
str(fluesse)
'data.frame':   1049 obs. of  28 variables:
$ Datum                      : Date, format: NA NA NA ...

the dates are formatted like this:
07.08.14
This is what I tried
as.Date(as.character("07.08.14"), format="%d.%m.%y")
[1] "2014-08-07"
as.Date(as.character(fluesse$Datum), format = "%d.%m.%y")
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

I always get NA for the entries in fluesse$Datum
and when I try to check what class it has i gives me
class("fluesse$Datum")
[1] "character"

What am I missing when I try to use as.character on the data.frame?

A: Well, your  fluesse$Datum in the str(.) is already of class "Date" with all the NAs.
Then below, you show another fluesse$Datum which is of class "character", so
as.character(.) will not have an effect.
Maybe you just confused yourself by calling both versions fluesse instead of say d.fl.1 and d.fl.2  (one convention likes to denote datasets by an initial d.)  ?

A: For all date conversions... Trying the "lubridate" package always helps. Functions like dmy_hms, mdy_hms help in parsing almost any date format. Just install the package and play around with it. I think you will figure out yourself.You can try this:

> library(lubridate)
> x <- "07.08.14"
> x <- dmy(x)
> as.Date(x, format="%d.%m.%y")
[1] "2014-08-07"

in place of "x" you can put your date vector and try.
Another possibility is that, the data has not been read in from the source, hence class() on date vector gives character "NA".


text:
Q: Configure a DSC Resource to restart I have a DSC resource that installs dotnet feature and then installs an update to dotnet.
In the Local Configuration Manager I have set RebootNodeIfNeeded to $true.
After dotnet installs, it does not request a reboot (even used xPendingReboot module to confirm this).
Configuration WebServer
{
WindowsFeature NetFramework45Core
{
    Name = "Net-Framework-45-Core"
    Ensure = "Present"
}

xPendingReboot Reboot
{
    Name = "Prior to upgrading Dotnet4.5.2"
}

cChocoPackageInstaller InstallDotNet452
{
    name = "dotnet4.5.2"
}

}

This is a problem as dotnet doesn't work properly with our app unless the server has been rebooted and we are trying to make these reboots happen automatically no user input required.
Is there any way to make a resource push to the localdscmanager (LCM) that it needs a reboot when there's something being installed?
I have found the below command
 $global:DSCMachineStatus = 1

Which sets a reboot. but I'm unsure as to how to use it to reboot right after the 4.5 module is installed.

A: Normally when I install .Net it works without rebooting, but if you want to force your configuration to reboot it after it installs it you can do the following.  It won't work for drift (.net being removed after initial installation.)  During configuration drift, the configuration will still install .net, but the script resource I added to reboot will believe it has already rebooted.
The DependsOn is very important here, you don't want this script running before the WindowsFeature has run successfully.
configuration WebServer
{
    WindowsFeature NetFramework45Core
    {
        Name = "Net-Framework-45-Core"
        Ensure = "Present"
    }

    Script Reboot
    {
        TestScript = {
            return (Test-Path HKLM:\SOFTWARE\MyMainKey\RebootKey)
        }
        SetScript = {
            New-Item -Path HKLM:\SOFTWARE\MyMainKey\RebootKey -Force
             $global:DSCMachineStatus = 1

        }
        GetScript = { return @{result = 'result'}}
        DependsOn = '[WindowsFeature]NetFramework45Core'
    }
}

A: To get $global:DSCMachineStatus = 1 working, you first need to configure Local Configuration Manager on the remote node to allow Automatic reboots. You can do it like this:
Configuration ConfigureRebootOnNode
{
    param (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $NodeName
    )

    Node $NodeName
    {
        LocalConfigurationManager
        {
            RebootNodeIfNeeded = $true
        }
    }
}

ConfigureRebootOnNode -NodeName myserver
Set-DscLocalConfigurationManager .\ConfigureRebootOnNode -Wait -Verbose

(code taken from colin's alm corner)


text:
Q: Flutter build Expansion tiles from List I know how to build Expansion tiles Statically, but am having trouble figuring out how to create them from a List. Could anyone help with this?
The Expansion tiles, would have up to three levels.
For example here is the 3 level list:
final List<MenuItem> loadedItems = [
MenuItem(
  id: "1",
  title: "MEN",
  type: "I",
  menuItems: [
    MenuItem(
      id: "1",
      title: "Clothing",
      type: "I",
      menuItems: [
        MenuItem(
          id: "1",
          title: "Tees & Tanks",
          type: "B",
        ),
        MenuItem(
          id: "1",
          title: "Shirts & Polos",
          type: "B",
        ),
        MenuItem(
          id: "1",
          title: "Boardshorts",
          type: "B",
        ),
      ],
    ),
    MenuItem(
      id: "1",
      title: "Accessories",
      type: "I",
      menuItems: [
        MenuItem(
          id: "1",
          title: "Caps & Hats & Beanies",
          type: "B",
        ),
        MenuItem(
          id: "1",
          title: "Wallets",
          type: "B",
        ),
        MenuItem(
          id: "1",
          title: "Socks",
          type: "B",
        ),
      ],
    ),
    MenuItem(
      id: "1",
      title: "Watches",
      type: "B",
    ),
    MenuItem(
      id: "1",
      title: "Footwear",
      type: "B",
    ),
    MenuItem(
      id: "1",
      title: "Sunglasses",
      type: "B",
    ),
    MenuItem(
      id: "1",
      title: "Special Offers",
      type: "B",
    ),
  ],
),

Been scratching my head for some time over this one, so would really appreciate any help.
Many thanks

A: You can use [].map((e){}).toList(); to iterate through a list and return list of widgets.
Here's the code
class ExpansionTileDemo extends StatefulWidget {
  @override
  _ExpansionTileDemoState createState() => _ExpansionTileDemoState();
}

class _ExpansionTileDemoState extends State<ExpansionTileDemo> {

final List<MenuItem> loadedItems = [
MenuItem(
  id: "1",
  title: "MEN",
  type: "I",
  menuItems: [
    MenuItem(
      id: "1",
      title: "Clothing",
      type: "I",
      menuItems: [
        MenuItem(
          id: "1",
          title: "Tees & Tanks",
          type: "B",
        ),
        MenuItem(
          id: "1",
          title: "Shirts & Polos",
          type: "B",
        ),
        MenuItem(
          id: "1",
          title: "Boardshorts",
          type: "B",
        ),
      ],
    ),
    MenuItem(
      id: "1",
      title: "Accessories",
      type: "I",
      menuItems: [
        MenuItem(
          id: "1",
          title: "Caps & Hats & Beanies",
          type: "B",
        ),
        MenuItem(
          id: "1",
          title: "Wallets",
          type: "B",
        ),
        MenuItem(
          id: "1",
          title: "Socks",
          type: "B",
        ),
      ],
    ),
    MenuItem(
      id: "1",
      title: "Watches",
      type: "B",
    ),
    MenuItem(
      id: "1",
      title: "Footwear",
      type: "B",
    ),
    MenuItem(
      id: "1",
      title: "Sunglasses",
      type: "B",
    ),
    MenuItem(
      id: "1",
      title: "Special Offers",
      type: "B",
    ),
  ],
),

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Expansion Tile Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 0.0),
        child: ListView.builder(
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          physics: BouncingScrollPhysics(),
          itemCount: monthModel.length,
          itemBuilder: (BuildContext context, int index) {
            return _buildList(loadedItems[index]);
          },
        ),
      ),
    );
  }

  Widget _buildList(MenuItem item) {
    return Card(
      child: ExpansionTile(
        title: Text(
          item.title,
          style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500),
        ),
        children: items
                .map((e){
                return ListTile(
            title: Text(
              e.title,
              style: TextStyle(fontWeight: FontWeight.w700),
            ),
          )
             }).toList(),
      ),
    );
  }
}


text:
Q: How to reduce Cython compiled code's interaction with Python I am trying to reduce a particularly computational heavy piece of Python code through compiling as C with Cython.  Surprisingly I have virtually no success in speeding it up.  With the original Python module the code runs in about 45sec and with the Cython compiled module it runs in about 45secs.
Compiling with annotate=True, I am left with a sea of yellow(ish) lines suggesting there is still a huge amount of Python interaction.
I have responded to this by switching off both boundscheck (False) and cdivision (True).  This had no effect.  The following snippet of code is an extract from this module and it insists on interacting with Python.  Why is this?  Nothing here need to interact with any pre-existing Python module, it is all very simple arithmatic?
cpdef float __distance_between(point1, point2)  except? -2:
    return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** (1/2)

point1 and point2 are Python lists each containing 2 doubles eg: [611811.997, -871083.372] The resulting C-code that is generated by Cython for the return line in the snippet is as follows:
+05: cpdef float __distance_between(point1, point2)  except? -2:
+06:     return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)**(1/2)
  __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_point1, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_2 = __Pyx_GetItemInt(__pyx_v_point2, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __pyx_t_3 = PyNumber_Subtract(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_3);
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
  __pyx_t_2 = PyNumber_Power(__pyx_t_3, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
  __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_point1, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_3);
  __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_point2, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_4 = PyNumber_Subtract(__pyx_t_3, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_4);
  __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_t_1 = PyNumber_Power(__pyx_t_4, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
  __pyx_t_4 = PyNumber_Add(__pyx_t_2, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_4);
  __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_t_1 = __Pyx_PyInt_From_long((1 / 2)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_2 = PyNumber_Power(__pyx_t_4, __pyx_t_1, Py_None); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_2);
  __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
  __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
  __pyx_t_5 = __pyx_PyFloat_AsFloat(__pyx_t_2); if (unlikely((__pyx_t_5 == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 6, __pyx_L1_error)
  __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
  __pyx_r = __pyx_t_5;
  goto __pyx_L0;

How can I better optimise the code or the compilation to make this snippet independent of Python?
There are many other lines in this module that are all rendered pretty yellow, but starting with this question may provide me with a better understanding of how to tackle the rest.

A: You haven't cdefed any of your variables; you know they're float, Cython doesn't. Tell it.
cpdef float __distance_between((double, double)point1, (double, double)point2)  except? -2:
    return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** (1/2)


text:
Q: Depuração remota .NET em Sistema operacional diferente É possível após instalar e depurar uma aplicação que está executando no linux através do mono de uma maquina windows?
O Ambiente é o seguinte:
Uma aplicação foi desenvolvida no Windows usando unica e exclusivamente as bibliotecas padrão do .NET 4.0.
Essa aplicação está sendo executada no Linux, a instalação foi feita, todos os arquivos foram criados sem problemas e a aplicação está executando, mas está com muitos problemas.
Está se tentando resolver os problemas de compatibilidade, contudo, a resolução está lenta e seria extremamente produtivo se pudesse ativar a depuração remota.
Em geral eu programo em Java, PHP e C, nessas linguagens é bem simples a depuração remota usando o Netbeans, Eclipse e etc...
Há como ativar a depuração remota para a partir do Visual Studio .NET e o programador poder depurar a aplicação que está rodando na máquina linux (que está com o mono)?
Se sim como fazer essa configuração?


text:
Q: How to build configurable facade over set of RESTful services It's time to ask question on StackOverflow because I did not find a good one in Google.
We have a legacy systems(2 in my case) that provide some functionality via RESTful web-services.
Now we are building a Java EE system that will consume RESTful services from that legacy systems.
Questiuon: how to build convenient facade API over mentioned RESTful web-services to use them easily in our Java EE app?
Are there some frameworks to easily consume a set of REST web-services and it can be XML-configured?

A: There is a number of options

*

*The most "low level" - HTTP Client (http://hc.apache.org/httpclient-3.x/)

*Something more abstract - RestEasy ClientRequest/ClientRespons (http://docs.jboss.org/resteasy/docs/1.2.GA/javadocs/org/jboss/resteasy/client/ClientRequest.html) there is a number of tutorials how to work with it

*You might like it most due to XML config - Spring Framework RestTemplate support (see, for instance http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/client/RestTemplate.html), there is a number of tutorials in the web too.


text:
Q: Why isn't my CSS working (even when I use !important) Why is my CSS not working? I'm trying to edit the margins for the image, to center it.
I've put "margin-left: 135px !important;" and "margin-right: 335px !important;" in my css file, selected the correct class and tag, and it is showing struck out in Google Chrome. Firefox isn't even showing the CSS.
The class is .mainlogo-img.
The site is www.barflypub.com

A: You mustn't use spaces between the value and "px".
margin: 0px 335px 0px 135px; will work.


text:
Q: Question about Dirichlet kernel of Fourier transform for $f\in L^p$ with $p\in [1,2]$, help needed in understanding proof. I am trying to understand the proof that the following two statements are equivalent. For fixed $R>0$ and $f\in L^p(\mathbb{R}^n)$ let
$$S_Rf(x)=\int_{|\xi|<R} \hat{f}(\xi)e^{2\pi i x . \xi}\,d\xi.$$
1) For all $f\in L^p$, $S_Rf \to f$ in $L^p$ as $R\to \infty$.
2) There exists a constant $c>0$ depending only on $p$ such that $||S_Rf||_{L^p}\leq c||f||_{L^p}$ for all $f$
Basically I have read everywhere that for 1) $\implies$ 2) (this is the direction I am interested in) you use the UBP but this is what I'm having difficulty understanding! How, for fixed $R>0$, is $S_R : L^p \to L^p$ a bounded map? I don't even see how $S_Rf$ is even in $L^p$? Any help would be appreciated, I've been trying to work it out for hours now. Thanks


text:
Q: Speed up JSON to dataframe w/ a lot of data manipulation I have a massive blob of JSON data formatted as follows:
[
    [{
        "created_at": "2017-04-28T16:52:36Z",
        "as_of": "2017-04-28T17:00:05Z",
        "trends": [{
            "url": "http://twitter.com/search?q=%23ChavezSigueCandanga",
            "query": "%23ChavezSigueCandanga",
            "tweet_volume": 44587,
            "name": "#ChavezSigueCandanga",
            "promoted_content": null
        }, {
            "url": "http://twitter.com/search?q=%2327Abr",
            "query": "%2327Abr",
            "tweet_volume": 79781,
            "name": "#27Abr",
            "promoted_content": null
        }],
        "locations": [{
            "woeid": 395277,
            "name": "Turmero"
        }]
    }],
    [{
        "created_at": "2017-04-28T16:57:35Z",
        "as_of": "2017-04-28T17:00:03Z",
        "trends": [{
            "url": "http://twitter.com/search?q=%23fyrefestival",
            "query": "%23fyrefestival",
            "tweet_volume": 141385,
            "name": "#fyrefestival",
            "promoted_content": null
        }, {
            "url": "http://twitter.com/search?q=%23HotDocs17",
            "query": "%23HotDocs17",
            "tweet_volume": null,
            "name": "#HotDocs17",
            "promoted_content": null
        }],
        "locations": [{
            "woeid": 9807,
            "name": "Vancouver"
        }]
    }]
]...

I wrote a function that formats it into a pandas dataframe that takes this form:
+----+--------------------------------+------------------+----------------------------------+--------------+--------------------------------------------------------------+----------------------+----------------------+---------------+----------------+
|    |              name              | promoted_content |              query               | tweet_volume |                             url                              |        as_of         |      created_at      | location_name | location_woeid |
+----+--------------------------------+------------------+----------------------------------+--------------+--------------------------------------------------------------+----------------------+----------------------+---------------+----------------+
| 47 | #BatesMotel                    |                  | %23BatesMotel                    | 59748        | http://twitter.com/search?q=%23BatesMotel                    | 2017-04-25T17:00:05Z | 2017-04-25T16:53:43Z | Winnipeg      | 2972           |
| 48 | #AdviceForPeopleJoiningTwitter |                  | %23AdviceForPeopleJoiningTwitter | 51222        | http://twitter.com/search?q=%23AdviceForPeopleJoiningTwitter | 2017-04-25T17:00:05Z | 2017-04-25T16:53:43Z | Winnipeg      | 2972           |
| 49 | #CADTHSymp                     |                  | %23CADTHSymp                     |              | http://twitter.com/search?q=%23CADTHSymp                     | 2017-04-25T17:00:05Z | 2017-04-25T16:53:43Z | Winnipeg      | 2972           |
| 0  | #WorldPenguinDay               |                  | %23WorldPenguinDay               | 79006        | http://twitter.com/search?q=%23WorldPenguinDay               | 2017-04-25T17:00:05Z | 2017-04-25T16:58:22Z | Toronto       | 4118           |
| 1  | #TravelTuesday                 |                  | %23TravelTuesday                 |              | http://twitter.com/search?q=%23TravelTuesday                 | 2017-04-25T17:00:05Z | 2017-04-25T16:58:22Z | Toronto       | 4118           |
| 2  | #DigitalLeap                   |                  | %23DigitalLeap                   |              | http://twitter.com/search?q=%23DigitalLeap                   | 2017-04-25T17:00:05Z | 2017-04-25T16:58:22Z | Toronto       | 4118           |
| …  | …                              | …                | …                                | …            | …                                                            | …                    | …                    | …             | …              |
| 0  | #nusnc17                       |                  | %23nusnc17                       |              | http://twitter.com/search?q=%23nusnc17                       | 2017-04-25T17:00:05Z | 2017-04-25T16:58:24Z | Birmingham    | 12723          |
| 1  | #WorldPenguinDay               |                  | %23WorldPenguinDay               | 79006        | http://twitter.com/search?q=%23WorldPenguinDay               | 2017-04-25T17:00:05Z | 2017-04-25T16:58:24Z | Birmingham    | 12723          |
| 2  | #littleboyblue                 |                  | %23littleboyblue                 | 20772        | http://twitter.com/search?q=%23littleboyblue                 | 2017-04-25T17:00:05Z | 2017-04-25T16:58:24Z | Birmingham    | 12723          |
+----+--------------------------------+------------------+----------------------------------+--------------+--------------------------------------------------------------+----------------------+----------------------+---------------+----------------+

This is the function that writes the JSON to a DataFrame:
def trends_to_dataframe(data):
    df = pd.DataFrame()

    for location in data:
        temp_df = pd.DataFrame()

        for trend in location[0]['trends']:
            temp_df = temp_df.append(pd.Series(trend), ignore_index=True)

        temp_df['as_of'] = location[0]['as_of']
        temp_df['created_at'] = location[0]['created_at']
        temp_df['location_name'] = location[0]['locations'][0]['name']
        temp_df['location_woeid'] = location[0]['locations'][0]['woeid']

        df = df.append(temp_df)

    return df

Unfortunately, with the amount of data I have (and some simple timers I tested with) this will take about 4 hours to finish.  Any thoughts on how to speed this up?

A: You could speed things up by async flattening the data with concurrent.futures, then loading it all into a DataFrame with from_records.
from concurrent.futures import ThreadPoolExecutor

def get_trends(location):
    trends = []
    for trend in location[0]['trends']:
        trend['as_of'] = location[0]['as_of']
        trend['created_at'] = location[0]['created_at']
        trend['location_name'] = location[0]['locations'][0]['name']
        trend['location_woeid'] = location[0]['locations'][0]['woeid']
        trends.append(trend)
    return trends

flat_data = []
with ThreadPoolExecutor() as executor:
    for location in data:
        flat_data += get_trends(location)

df = pd.DataFrame.from_records(flat_data)