text:
//
//  LoginController.m
//  qmcp
//
//  Created by 谢永明 on 16/4/10.
//  Copyright © 2016年 inforshare. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginView.h"
#import "AppManager.h"
#import "SettingViewController.h"
#import "RootViewController.h"
#import "User.h"
#import "TMCache.h"
#import "AddressViewController.h"
@interface LoginViewController ()<UITextFieldDelegate,UIGestureRecognizerDelegate>

@property(nonatomic, strong) LoginView *loginView;

@end

@implementation LoginViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

-(void)loadView{
    _loginView = [LoginView new];
    self.view = _loginView;
}

-(void)bindListener{
    _loginView.userNameText.delegate = self;
    _loginView.passWordText.delegate = self;

    [_loginView.userNameText addTarget:self action:@selector(returnOnKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [_loginView.passWordText addTarget:self action:@selector(returnOnKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];

    //添加手势,点击屏幕其他区域关闭键盘的操作
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidenKeyboard)];
    gesture.numberOfTapsRequired = 1;
    gesture.delegate = self;
    [self.view addGestureRecognizer:gesture];

    _loginView.loginBtn.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        [self loginBtnClick];
        return [RACSignal empty];
    }];

}

/**
 *  用户名密码验证
 */
-(void)p_validUsernameAndPassword{
    RACSignal *validUsernameSignal = [_loginView.userNameText.rac_textSignal
                                      map:^id(NSString *text) {
                                          return @([self p_isValidUsername:text]);
                                      }];
    RAC(_loginView.userNameText, textColor) =[validUsernameSignal map:^id(NSNumber *usernameValid){
        return[usernameValid boolValue] ? [UIColor blackColor]:[UIColor redColor];
    }];

    RACSignal *validPasswordSignal = [_loginView.passWordText.rac_textSignal
                                      map:^id(NSString *text) {
                                          return @([self p_isValidPassword:text]);
                                      }];
    RACSignal *signUpActiveSignal =
    [RACSignal combineLatest:@[validUsernameSignal, validPasswordSignal]
                      reduce:^id(NSNumber*usernameValid, NSNumber *passwordValid){
                          return @([usernameValid boolValue]&&[passwordValid boolValue]);
                      }];
    [signUpActiveSignal subscribeNext:^(NSNumber*signupActive){
        _loginView.loginBtn.backgroundColor = [signupActive boolValue] ? [UIColor nameColor] : [UIColor grayColor];
        _loginView.loginBtn.enabled = [signupActive boolValue];
    }];
}

/**
 * 用户名验证
 *
 *  @param text 用户名
 *
 *  @return bool
 */
-(BOOL)p_isValidUsername:(NSString *)text{
    NSString * regex = @"^[A-Za-z0-9-_@]{1,20}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:text];
    return isMatch;
}

/**
 *  密码验证
 *
 *  @param text 密码
 *
 *  @return bool
 */
-(BOOL)p_isValidPassword:(NSString *)text{
    return text.length > 0;
}

-(void)loginBtnClick{
    NSString *username = _loginView.userNameText.text;
    NSString *password = _loginView.passWordText.text;
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hub.detailsLabel.text = @"正在登录";

    // 请求参数
    NSDictionary *dic = @{ @"user":username,@"pwd":password};
    NSString *URLString = [NSString stringWithFormat:@"%@%@", QMCPAPI_ADDRESS,QMCPAPI_LOGIN];

    [HttpUtil postFormData:URLString param:dic finish:^(NSDictionary *obj, NSString *error) {
        if(!error){
            // 字典转模型
            User *account = [User mj_objectWithKeyValues:obj];
            if(account.authenticated){
                [Config saveUserName:username andPassword:password];
                [Config saveLoginStatus:true];
                hub.mode = MBProgressHUDModeCustomView;
                hub.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"HUD-done"]];
                hub.detailsLabel.text = [NSString stringWithFormat:@"登录成功"];
                [hub hideAnimated:YES afterDelay:kEndSucceedDelayTime];
                [[AppManager getInstance]setUser:account];
                [[TMCache sharedCache] setObject:account forKey:@"user"];
                UIStoryboard *discoverSB = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                RootViewController *discoverNav = [discoverSB instantiateViewControllerWithIdentifier:@"Nav"];
                [self presentViewController:discoverNav animated:YES completion:nil];
            }else{

                hub.mode = MBProgressHUDModeCustomView;
                hub.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"HUD-error"]];
                hub.detailsLabel.text = [NSString stringWithFormat:@"账号或密码错误"];
                [hub hideAnimated:YES afterDelay:kEndFailedDelayTime];
            }
        }else{
            hub.mode = MBProgressHUDModeCustomView;
            hub.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"HUD-error"]];
            hub.detailsLabel.text = error;
            [hub hideAnimated:YES afterDelay:kEndFailedDelayTime];
        }
    }];

}
-(void)loadData{
    NSArray *accountAndPassword = [Config getUserNameAndPassword];
    _loginView.userNameText.text = accountAndPassword? accountAndPassword[0] : @"";
    _loginView.passWordText.text = accountAndPassword? accountAndPassword[1] : @"";
    [self p_validUsernameAndPassword];
}
#pragma mark - 键盘操作

- (void)hidenKeyboard{
    [_loginView.userNameText resignFirstResponder];
    [_loginView.passWordText resignFirstResponder];
}

- (void)returnOnKeyboard:(UITextField *)sender{
    if (sender == _loginView.userNameText) {
        [_loginView.passWordText becomeFirstResponder];
    } else if (sender == _loginView.passWordText) {
        [self hidenKeyboard];
        if (_loginView.loginBtn.enabled) {
            [self loginBtnClick];
        }else{
            [self hidenKeyboard];
        }
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if (![_loginView.userNameText isFirstResponder] && ![_loginView.passWordText isFirstResponder]) {
        return NO;
    }
    return YES;
}

@end


text:
package org.teavm.classlib.java.util.stream.intimpl;

import java.util.function.IntPredicate;

public class TAnyMatchConsumer implements IntPredicate {
    public boolean matched;
    private IntPredicate predicate;

    public TAnyMatchConsumer(IntPredicate predicate) {
        this.predicate = predicate;
    }

    @Override
    public boolean test(int t) {
        matched = predicate.test(t);
        return !matched;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.IO;
using McMaster.Extensions.CommandLineUtils;
using NuGet.Common;

namespace NupkgWrench
{
    internal static class AddFilesCommand
    {
        public static void Register(CommandLineApplication cmdApp, ILogger log)
        {
            cmdApp.Command("add", (cmd) => Run(cmd, log), throwOnUnexpectedArg: true);
        }

        private static void Run(CommandLineApplication cmd, ILogger log)
        {
            cmd.Description = "Add a file to a nupkg.";
            cmd.HelpOption(Constants.HelpOption);
            var pathOption = cmd.Option("-p|--path", "Path to add file at within the nupkg, this must contain the file name also.", CommandOptionType.SingleValue);
            var fileOption = cmd.Option("-f|--file", "Path on disk to the file that will be added to the nupkg.", CommandOptionType.SingleValue);

            var idFilter = cmd.Option(Constants.IdFilterTemplate, Constants.IdFilterDesc, CommandOptionType.SingleValue);
            var versionFilter = cmd.Option(Constants.VersionFilterTemplate, Constants.VersionFilterDesc, CommandOptionType.SingleValue);
            var excludeSymbolsFilter = cmd.Option(Constants.ExcludeSymbolsTemplate, Constants.ExcludeSymbolsDesc, CommandOptionType.NoValue);
            var highestVersionFilter = cmd.Option(Constants.HighestVersionFilterTemplate, Constants.HighestVersionFilterDesc, CommandOptionType.NoValue);

            var argRoot = cmd.Argument(
                "[root]",
                Constants.MultiplePackagesRootDesc,
                multipleValues: true);

            var required = new List<CommandOption>()
            {
                pathOption,
                fileOption
            };

            cmd.OnExecute(() =>
            {
                var inputs = argRoot.Values;

                if (inputs.Count < 1)
                {
                    inputs.Add(Directory.GetCurrentDirectory());
                }

                // Gather all package data
                var packages = Util.GetPackagesWithFilter(idFilter, versionFilter, excludeSymbolsFilter, highestVersionFilter, inputs.ToArray());

                // Validate parameters
                foreach (var requiredOption in required)
                {
                    if (!requiredOption.HasValue())
                    {
                        throw new ArgumentException($"Missing required parameter --{requiredOption.LongName}.");
                    }
                }

                foreach (var nupkgPath in packages)
                {
                    using (var fileInput = File.OpenRead(fileOption.Value()))
                    {
                        Util.AddOrReplaceZipEntry(nupkgPath, pathOption.Value(), fileInput, log);
                    }
                }

                return 0;
            });
        }
    }
}


text:
#ifndef MXNET_OPERATOR_CONTRIB_FARTHEST_POINT_SAMPLING_INL_H_
#define MXNET_OPERATOR_CONTRIB_FARTHEST_POINT_SAMPLING_INL_H_

#include <vector>
#include <utility>
#include "../mshadow_op.h"
#include "../tensor/init_op.h"
#include "../operator_common.h"

namespace mxnet {
typedef std::vector<mxnet::TShape> ShapeVector;
namespace op {

// Declare enumeration of input order to make code more intuitive.
// These enums are only visible within this header
namespace farthest_point_sampling {
enum FarthestPointSamplingOpInputs { kData };
enum FarthestPointSamplingOpOutputs { kOut, kMinDist };
}  // namespace farthest_point_sampling

struct FarthestPointSamplingParam
    : public dmlc::Parameter<FarthestPointSamplingParam> {
  int npoints;
  DMLC_DECLARE_PARAMETER(FarthestPointSamplingParam) {
    DMLC_DECLARE_FIELD(npoints).describe("Number of keypoints.");
  }
};

template <typename xpu>
void FarthestPointSamplingForward(const nnvm::NodeAttrs& attrs,
                                  const OpContext& ctx,
                                  const std::vector<TBlob>& in_data,
                                  const std::vector<OpReqType>& req,
                                  const std::vector<TBlob>& out_data);
}
}

#endif  // MXNET_OPERATOR_CONTRIB_FARTHEST_POINT_SAMPLING_INL_H_


text:
{% extends "admin/base_site.html" %}
{% load i18n admin_static admin_list %}
{% load url from future %}
{% load admin_urls %}

{% block extrastyle %}
  {{ block.super }}
  {% if cl.formset or action_form %}
    {% url 'admin:jsi18n' as jsi18nurl %}

  {% endif %}
{% endblock %}

{% block extrahead %}
{{ block.super }}
{{ media.js }}
{% if action_form %}{% if actions_on_top or actions_on_bottom %}

{% endif %}{% endif %}
{% endblock %}

{% block bodyclass %}change-list{% endblock %}

{% if not is_popup %}
{% block right_of_title %}

    {% block object-tools %}
        {% if has_add_permission %}
            {% block object-tools-items %}

                {% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}

            {% endblock %}
        {% endif %}
    {% endblock %}

{% endblock %}

{% block breadcrumbs %}

        {% trans 'Home' %}

    /

        {{ app_label|capfirst|escape }}

    /

    {{ cl.opts.verbose_name_plural|capfirst }}

{% endblock %}
{% endif %}

{% block content %}

    <form id="changelist-form" action="" method="post"{% if cl.formset.is_multipart %} enctype="multipart/form-data"{% endif %}>
        <fieldset>
            {% csrf_token %}

            {% block result_list %}
                {% if action_form and actions_on_top and cl.full_result_count %}
                    {% admin_actions %}
                {% endif %}

                {% result_list cl %}

                {% if action_form and actions_on_bottom and cl.full_result_count %}
                    {% admin_actions %}
                {% endif %}
            {% endblock %}

            {% if cl.formset %}

{{ cl.formset.management_form }}

            {% endif %}

        </fieldset>
    </form>

    {% block pagination %}
        {% pagination cl %}
    {% endblock %}

{% endblock %}

{% block sidebar %}

    {% block search %}
        {% search_form cl %}
    {% endblock %}

    {% block filters %}
        {% if cl.has_filters %}

{% trans 'Filter' %}

            {% for spec in cl.filter_specs %}
                {% admin_list_filter cl spec %}
            {% endfor %}

        {% endif %}
      {% endblock %}

{% endblock %}

    {% if cl.formset.errors %}

            <button class="close" data-dismiss="alert">×</button>
            {% blocktrans count cl.formset.errors|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}

        {{ cl.formset.non_form_errors }}
    {% endif %}

        {% block date_hierarchy %}
            {% date_hierarchy cl %}
        {% endblock %}

      {% if cl.formset %}

{{ cl.formset.management_form }}

      {% endif %}

      </form>


text:
#ifndef __EASYIF_H
#define __EASYIF_H

/*
 * Prototypes for library-wide functions provided by easy.c
 */
void Curl_easy_addmulti(struct SessionHandle *data, void *multi);

void Curl_easy_initHandleData(struct SessionHandle *data);

#endif /* __EASYIF_H */


text:
class HelperWindows : public BWindow
{
public:
				HelperWindows(BRect frame, const char* title);
		void	AddText(BRect tframe, const char* hname, const char* helptext);
		bool	QuitRequested(void);

private:
		BView*			backView;
};

#endif


text:
package edu.uwec.cs.cs255.kunseljp.graphcoloring;

public interface State {
	public boolean hasMoreChildren();
	public State nextChild();
	public boolean isFeasible();
	public boolean isSolved();
}


text:
#include "stdafx.h"
#include <cassert>
#include <iostream>
#include <list>
#include <map>

#include <zorba/properties.h>
#include <zorba/store_manager.h>
#include <zorba/thesaurus.h>
#include <zorba/zorba.h>
#include <zorba/zorba_exception.h>

using namespace std;
using namespace zorba;
using namespace zorba::locale;

static bool destroy_called;

///////////////////////////////////////////////////////////////////////////////

class TestThesaurus : public Thesaurus {
public:
  // inherited
  void destroy() const;
  iterator::ptr lookup( String const &phrase, String const &relationship,
                        range_type at_least, range_type at_most ) const;
private:
  typedef std::list<String> synonyms_type;
  typedef std::map<String,synonyms_type const*> thesaurus_data_type;

  static thesaurus_data_type const& get_thesaurus_data();

  class iterator : public Thesaurus::iterator {
  public:
    iterator( synonyms_type const &s ) : synonyms_( s ), i_( s.begin() ) { }
    void destroy() const;
    bool next( String *synonym );
  private:
    synonyms_type const &synonyms_;
    synonyms_type::const_iterator i_;
  };
};

void TestThesaurus::destroy() const {
  destroy_called = true;
}

TestThesaurus::thesaurus_data_type const& TestThesaurus::get_thesaurus_data() {
  static thesaurus_data_type thesaurus_data;
  if ( thesaurus_data.empty() ) {
    static synonyms_type synonyms;
    synonyms.push_back( "foo" );
    synonyms.push_back( "foobar" );

    thesaurus_data[ "foo"    ] = &synonyms;
    thesaurus_data[ "foobar" ] = &synonyms;
  }
  return thesaurus_data;
}

Thesaurus::iterator::ptr
TestThesaurus::lookup( String const &phrase, String const &relationship,
                       range_type at_least, range_type at_most ) const {
  static thesaurus_data_type const &thesaurus_data = get_thesaurus_data();
  thesaurus_data_type::const_iterator const entry =
    thesaurus_data.find( phrase );
  iterator::ptr result;
  if ( entry != thesaurus_data.end() )
    result.reset( new iterator( *entry->second ) );
  return std::move( result );
}

void TestThesaurus::iterator::destroy() const {
  delete this;
}

bool TestThesaurus::iterator::next( String *synonym ) {
  if ( i_ != synonyms_.end() ) {
    *synonym = *i_;
    ++i_;
    return true;
  }
  return false;
}

///////////////////////////////////////////////////////////////////////////////

class TestThesaurusProvider : public ThesaurusProvider {
public:
  bool getThesaurus( iso639_1::type lang, Thesaurus::ptr* = 0 ) const;

  // inherited
  void destroy() const;
};

void TestThesaurusProvider::destroy() const {
  // do nothing
}

bool TestThesaurusProvider::getThesaurus( iso639_1::type lang,
                                          Thesaurus::ptr *result ) const {
  static TestThesaurus thesaurus;
  if ( result )
    result->reset( &thesaurus );
  return true;
}

///////////////////////////////////////////////////////////////////////////////

class TestThesaurusResolver : public URLResolver {
public:
  TestThesaurusResolver( String const &uri ) : uri_( uri ) { }

  // inherited
  Resource* resolveURL( String const &uri, EntityData const* );
private:
  String const uri_;
};

Resource*
TestThesaurusResolver::resolveURL( String const &uri, EntityData const *data ) {
  if ( data->getKind() == EntityData::THESAURUS ) {
    static TestThesaurusProvider provider;
    if ( uri == uri_ )
      return &provider;
  }
  return 0;
}

///////////////////////////////////////////////////////////////////////////////

namespace zorba {
namespace UnitTests {

int test_thesaurus( int argc, char *argv[] ) {
  void *const zstore = StoreManager::getStore();
  Zorba *const zorba = Zorba::getInstance( zstore );

  int result = 0;

  try {
    char const *const query_src =
      "let $x := <msg>foobar</msg> \n"
      "return $x contains text \"foo\" \n"
      "  using thesaurus at \"http://test\" \n";

    StaticContext_t sctx = zorba->createStaticContext();
    TestThesaurusResolver resolver( "http://test" );
    sctx->registerURLResolver( &resolver );
    XQuery_t xquery = zorba->compileQuery( query_src, sctx );

    Zorba_SerializerOptions ser_options;
    ser_options.omit_xml_declaration = ZORBA_OMIT_XML_DECLARATION_YES;
    std::ostringstream sout;
    xquery->execute( sout, &ser_options );

    if ( !destroy_called )
      result = 1;

    if ( sout.str() != "true" )
      result = 2;
  }
  catch ( ZorbaException const &e ) {
    cerr << e << endl;
    result = 3;
  }

  zorba->shutdown();
  StoreManager::shutdownStore( zstore );
  return result;
}

} // namespace UnitTests
} // namespace zorba

/* vim:set et sw=2 ts=2: */


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
com.mxgraph.costfunction (JGraph X 2.3.0.3 API Specification)
</TITLE>

<META NAME="date" CONTENT="2013-11-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

com.mxgraph.costfunction

Classes

mxConstCostFunction

mxCostFunction

mxDoubleValCostFunction


text:
external help file: Microsoft.Azure.Commands.Websites.dll-Help.xml
ms.assetid: D23BBF34-80C0-48B1-8E1C-6F345DEC61AD
online version:
schema: 2.0.0
---

# New-AzureRmWebAppSlot

## SYNOPSIS
Creates an Azure Web App slot.

## SYNTAX

```
New-AzureRmWebAppSlot [-ResourceGroupName] <String> [-Name] <String> [[-Slot] <String>]
 [[-AppServicePlan] <String>] [[-SourceWebApp] <Site>] [-IgnoreSourceControl] [-IgnoreCustomHostNames]
 [[-AppSettingsOverrides] <Hashtable>] [[-AseName] <String>] [[-AseResourceGroupName] <String>]
 [<CommonParameters>]
```

## DESCRIPTION
The **New-AzureRmWebApp** cmdlet creates an Azure Web App Slot in a given a resource group that uses the specified App Service plan and data center.

## EXAMPLES

### Example 1
```
PS C:\> New-AzureRmWebApp -ResourceGroupName Default-Web-WestUS -Name "ContosoSite" -Location "West US" -AppServicePlan "ContosoServicePlan" -Slot "Slot001"
```

This command creates a Slot named Slot001 under an existing Web App names ContosoSite in the existing resource group named Default-Web-WestUS in data center West US.
The command uses an existing App Service plan named ContosoServicePlan.

## PARAMETERS

### -AppServicePlan
App Service Plan Name

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: 3
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -AppSettingsOverrides
App Settings Overrides Hashtable

```yaml
Type: Hashtable
Parameter Sets: (All)
Aliases:

Required: False
Position: 8
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -AseName
App Service Environment Name

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: 9
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -AseResourceGroupName
App Service Environment Resource Group Name

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: 9
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -IgnoreCustomHostNames
Ignore Custom HostNames Option

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: 7
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -IgnoreSourceControl
Ignore Source Control Option

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: 6
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Name
Webapp Name

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -ResourceGroupName
Resource Group Name

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Slot
Webapp Slot Name

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -SourceWebApp
Source WebApp Object

```yaml
Type: Site
Parameter Sets: (All)
Aliases:

Required: False
Position: 4
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

## NOTES

## RELATED LINKS

[Get-AzureRMWebAppSlot](./Get-AzureRMWebAppSlot.md)

[Remove-AzureRMWebAppSlot](./Remove-AzureRMWebAppSlot.md)

[Restart-AzureRMWebAppSlot](./Restart-AzureRMWebAppSlot.md)

[Set-AzureRMWebAppSlot](./Set-AzureRMWebAppSlot.md)

[Start-AzureRMWebAppSlot](./Start-AzureRMWebAppSlot.md)

[Stop-AzureRMWebAppSlot](./Stop-AzureRMWebAppSlot.md)

[Get-AzureRmAppServicePlan](./Get-AzureRmAppServicePlan.md)

[Get-AzureRmWebApp](./Get-AzureRmWebApp.md)


text:
@implementation AppDelegate
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize managedObjectContext = _managedObjectContext;
@synthesize urlist;
@synthesize backgroundManagedObjectContext = _backgroundManagedObjectContext;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{

    [self reloadData];
    [self.urlTable reloadData];
    [self performSelectorInBackground:@selector(checking:) withObject:nil];
}

-(Url*)oneUrlNeedtoGet:(id)sender {

    __block NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity =
    [NSEntityDescription entityForName:@"Url"
                inManagedObjectContext:[self managedObjectContext]];
    [request setEntity:entity];

    NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@"pagerank == -1",-1];
    [request setPredicate:predicate];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                        initWithKey:@"address" ascending:YES];
    [request setSortDescriptors:@[sortDescriptor]];

    __block NSArray* ret;
    ret = [[self backgroundManagedObjectContext] executeFetchRequest:request error:nil];
    if ([ret count]>0) {

        Url* url = [ret objectAtIndex:0];
        return url;
    }
    return nil;
}

-(int)progress {

    return 100;
}

-(IBAction)checking:(id)sender {

    while (1) {

        __weak typeof(self) weakSelf = self;
        [self.backgroundManagedObjectContext performBlockAndWait:^{
            Url* url= [weakSelf oneUrlNeedtoGet:nil];
            if (url) {
                int pagerank = [weakSelf checkPagerank:url.address];
                if (pagerank!=-1) {
                    url.pagerank = [NSNumber numberWithInt:pagerank];
                    [weakSelf.backgroundManagedObjectContext save:nil];

                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        [weakSelf reloadData];
                        [weakSelf.urlTable reloadData];
                    }];
                    [NSThread sleepForTimeInterval:3];
                }
            }
            else
                [NSThread sleepForTimeInterval:1];

        }];
    }
}

-(int)checkPagerank:(NSString*)url {

    PageRank* pagerank = [[PageRank alloc] init];
    return [pagerank getPagerank:url];
}

- (NSURL *)applicationFilesDirectory
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *appSupportURL = [[fileManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask] lastObject];
    return [appSupportURL URLByAppendingPathComponent:@"org.tiny4.pagerankchecker"];
}

- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel) {
        return _managedObjectModel;
    }

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"urllist" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator) {
        return _persistentStoreCoordinator;
    }

    NSManagedObjectModel *mom = [self managedObjectModel];
    if (!mom) {
        NSLog(@"%@:%@ No model to generate a store from", [self class], NSStringFromSelector(_cmd));
        return nil;
    }

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *applicationFilesDirectory = [self applicationFilesDirectory];
    NSError *error = nil;

    NSDictionary *properties = [applicationFilesDirectory resourceValuesForKeys:@[NSURLIsDirectoryKey] error:&error];

    if (!properties) {
        BOOL ok = NO;
        if ([error code] == NSFileReadNoSuchFileError) {
            ok = [fileManager createDirectoryAtPath:[applicationFilesDirectory path] withIntermediateDirectories:YES attributes:nil error:&error];
        }
        if (!ok) {
            [[NSApplication sharedApplication] presentError:error];
            return nil;
        }
    } else {
        if (![properties[NSURLIsDirectoryKey] boolValue]) {
            // Customize and localize this error.
            NSString *failureDescription = [NSString stringWithFormat:@"Expected a folder to store application data, found a file (%@).", [applicationFilesDirectory path]];

            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setValue:failureDescription forKey:NSLocalizedDescriptionKey];
            error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:101 userInfo:dict];

            [[NSApplication sharedApplication] presentError:error];
            return nil;
        }
    }

    NSURL *url = [applicationFilesDirectory URLByAppendingPathComponent:@"pagerankchecker.storedata"];
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
    if (![coordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:url options:nil error:&error]) {
        [[NSApplication sharedApplication] presentError:error];
        return nil;
    }
    _persistentStoreCoordinator = coordinator;
    return _persistentStoreCoordinator;
}

// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:@"Failed to initialize the store" forKey:NSLocalizedDescriptionKey];
        [dict setValue:@"There was an error building up the data file." forKey:NSLocalizedFailureReasonErrorKey];
        NSError *error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        [[NSApplication sharedApplication] presentError:error];
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    return _managedObjectContext;
}

- (NSManagedObjectContext *)backgroundManagedObjectContext
{
    if (_backgroundManagedObjectContext) {
        return _backgroundManagedObjectContext;
    }

    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    [context setParentContext:self.managedObjectContext];
    _backgroundManagedObjectContext = context;

    return _backgroundManagedObjectContext;
}

-(void)reloadData {

    NSEntityDescription *entityDescription = [NSEntityDescription
                                              entityForName:@"Url" inManagedObjectContext:[self managedObjectContext]];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                        initWithKey:@"pagerank" ascending:NO];
    NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc]
                                        initWithKey:@"address" ascending:YES];

    [request setSortDescriptors:@[sortDescriptor,sortDescriptor2]];

    NSError *error;
    urlist = [[self managedObjectContext] executeFetchRequest:request error:&error];
}

- (IBAction)delUrl:(id)sender {

    NSIndexSet* sel = [self.urlTable selectedRowIndexes];
    if ([sel count] == 0)
        return;
    NSAlert *alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:@"OK"];
    [alert addButtonWithTitle:@"Cancel"];
    if ([sel count] ==1) {
        [alert setMessageText:@"Delete this url?"];
    }
    else {
        [alert setMessageText:@"Delete these urls?"];

    }
    [alert setInformativeText:@"Deleted urls cannot be restored."];
    [alert setAlertStyle:NSWarningAlertStyle];
    if ([alert runModal] == NSAlertFirstButtonReturn) {

        [sel enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
            Url* url = [urlist objectAtIndex:idx];
            [[self managedObjectContext] deleteObject:url];
            [[self managedObjectContext] save:nil];
        }];
        [self reloadData];
        [self.urlTable reloadData];
    }
}

- (IBAction)addUrl:(id)sender {

    NSString* url = self.urlInput.stringValue;
    [self addOneUrl:url];
    [[self managedObjectContext] save:nil];
    [self reloadData];
    [self.urlTable reloadData];
}

-(void)addOneUrl:(NSString*)url {

    url = [url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    if (url.length==0)
        return;

    if ([self findUrl:url])
        return;

    Url *entity = [NSEntityDescription insertNewObjectForEntityForName:@"Url" inManagedObjectContext:[self managedObjectContext]];
    entity.address = url;
    entity.pagerank = [NSNumber numberWithInt:-1];
}

-(void)addSomeUrls:(NSString*)urls {

    if (urls.length==0)
        return;

    NSArray* urlsArray = [urls componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    for (NSString* url in urlsArray) {

        [self addOneUrl:url];
    }
}

- (IBAction)addSitemap:(id)sender {
}

- (IBAction)addUrlsFromFile:(id)sender {
}

- (IBAction)sync:(id)sender {

}

- (IBAction)addUrlsByWildcardString:(id)sender {

    NSAlert *alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:@"Add"];
    [alert addButtonWithTitle:@"Cancel"];
    [alert setMessageText:@"Add these urls."];
    [alert setAccessoryView:self.wildcardView];
    [alert setAlertStyle:NSWarningAlertStyle];
    if ([alert runModal] != NSAlertFirstButtonReturn)
        return;

    int from = self.fromNum.intValue;
    int to = self.toNum.intValue;
    if (from>=to) {

        return;
    }

    NSString* pattern = self.urlPattern.stringValue;
    NSMutableArray* urls = [NSMutableArray arrayWithCapacity:to-from];
    for (int i = from; i<to+1; i++) {

        NSString* url = [pattern stringByReplacingOccurrencesOfString:@"*" withString:[NSString stringWithFormat:@"%d",i]];
        [urls addObject:url];
    }
    NSString* urlsStr = [urls componentsJoinedByString:@" "];

    NSTextField *input = [[NSTextField alloc]
                          initWithFrame:NSMakeRect(0, 0, 350, 24*6)];

    input.delegate = self;
    input.stringValue = urlsStr;
    alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:@"Add"];
    [alert addButtonWithTitle:@"Cancel"];
    [alert setMessageText:@"Add these urls."];
    [alert setAccessoryView:input];
    [alert setAlertStyle:NSWarningAlertStyle];
    if ([alert runModal] != NSAlertFirstButtonReturn)
        return;

    urlsStr = input.stringValue;
    [self addSomeUrls:urlsStr];
    [[self managedObjectContext] save:nil];
    [self reloadData];
    [self.urlTable reloadData];

}

- (IBAction)addUrls:(id)sender {

    NSTextField *input = [[NSTextField alloc]
                          initWithFrame:NSMakeRect(0, 0, 350, 24*6)];
    input.delegate = self;
    NSAlert *alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:@"Add"];
    [alert addButtonWithTitle:@"Cancel"];
    [alert setMessageText:@"Add these urls."];
    [alert setAccessoryView:input];
    [alert setAlertStyle:NSWarningAlertStyle];
    if ([alert runModal] != NSAlertFirstButtonReturn)
        return;

    NSString* urlsStr = input.stringValue;
    [self addSomeUrls:urlsStr];
    [[self managedObjectContext] save:nil];
    [self reloadData];
    [self.urlTable reloadData];
}

- (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
{
    BOOL result = NO;

    if (commandSelector == @selector(insertNewline:))
    {
        [textView insertNewlineIgnoringFieldEditor:self];
        result = YES;
    }
    else if (commandSelector == @selector(insertTab:))
    {
        [textView insertTabIgnoringFieldEditor:self];
        result = YES;
    }
    return result;
}

-(BOOL)findUrl:(NSString*)url {

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity =
    [NSEntityDescription entityForName:@"Url"
                inManagedObjectContext:[self managedObjectContext]];
    [request setEntity:entity];

    NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@"address == %@", url];
    [request setPredicate:predicate];

    NSError *error;
    NSInteger count = [[self managedObjectContext] countForFetchRequest:request error:&error];
    if (count>0)
        return YES;
    else
        return NO;
}

// Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application.
- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window
{
    return [[self managedObjectContext] undoManager];
}

// Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user.
- (IBAction)saveAction:(id)sender
{
    NSError *error = nil;

    if (![[self managedObjectContext] commitEditing]) {
        NSLog(@"%@:%@ unable to commit editing before saving", [self class], NSStringFromSelector(_cmd));
    }

    if (![[self managedObjectContext] save:&error]) {
        [[NSApplication sharedApplication] presentError:error];
    }
}

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
    // Save changes in the application's managed object context before the application terminates.

    if (!_managedObjectContext) {
        return NSTerminateNow;
    }

    if (![[self managedObjectContext] commitEditing]) {
        NSLog(@"%@:%@ unable to commit editing to terminate", [self class], NSStringFromSelector(_cmd));
        return NSTerminateCancel;
    }

    if (![[self managedObjectContext] hasChanges]) {
        return NSTerminateNow;
    }

    NSError *error = nil;
    if (![[self managedObjectContext] save:&error]) {

        // Customize this code block to include application-specific recovery steps.
        BOOL result = [sender presentError:error];
        if (result) {
            return NSTerminateCancel;
        }

        NSString *question = NSLocalizedString(@"Could not save changes while quitting. Quit anyway?", @"Quit without saves error question message");
        NSString *info = NSLocalizedString(@"Quitting now will lose any changes you have made since the last successful save", @"Quit without saves error question info");
        NSString *quitButton = NSLocalizedString(@"Quit anyway", @"Quit anyway button title");
        NSString *cancelButton = NSLocalizedString(@"Cancel", @"Cancel button title");
        NSAlert *alert = [[NSAlert alloc] init];
        [alert setMessageText:question];
        [alert setInformativeText:info];
        [alert addButtonWithTitle:quitButton];
        [alert addButtonWithTitle:cancelButton];

        NSInteger answer = [alert runModal];

        if (answer == NSAlertAlternateReturn) {
            return NSTerminateCancel;
        }
    }

    return NSTerminateNow;
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView {

    return [urlist count];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {

    Url* url = [urlist objectAtIndex:rowIndex];
    if ([[aTableColumn identifier] isEqualToString:@"0"]) {
        return [url address];
    }else if ([[aTableColumn identifier] isEqualToString:@"1"]) {
        return [url title];
    }else if ([[aTableColumn identifier] isEqualToString:@"2"]) {
        return [url pagerank];
    }
    return nil;
}
@end


text:
"""Tests for ast_util module."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import ast
import collections
import textwrap

import gast

from tensorflow.python.autograph.pyct import anno
from tensorflow.python.autograph.pyct import ast_util
from tensorflow.python.autograph.pyct import loader
from tensorflow.python.autograph.pyct import parser
from tensorflow.python.autograph.pyct import pretty_printer
from tensorflow.python.autograph.pyct import qual_names
from tensorflow.python.platform import test

class AstUtilTest(test.TestCase):

  def assertAstMatches(self, actual_node, expected_node_src):
    expected_node = gast.parse('({})'.format(expected_node_src)).body[0]
    msg = 'AST did not match expected:\n{}\nActual:\n{}'.format(
        pretty_printer.fmt(expected_node),
        pretty_printer.fmt(actual_node))
    self.assertTrue(ast_util.matches(actual_node, expected_node), msg)

  def setUp(self):
    super(AstUtilTest, self).setUp()
    self._invocation_counts = collections.defaultdict(lambda: 0)

  def test_rename_symbols_basic(self):
    node = parser.parse('a + b')
    node = qual_names.resolve(node)

    node = ast_util.rename_symbols(
        node, {qual_names.QN('a'): qual_names.QN('renamed_a')})
    source = parser.unparse(node, include_encoding_marker=False)
    expected_node_src = 'renamed_a + b'

    self.assertIsInstance(node.value.left.id, str)
    self.assertAstMatches(node, source)
    self.assertAstMatches(node, expected_node_src)

  def test_rename_symbols_attributes(self):
    node = parser.parse('b.c = b.c.d')
    node = qual_names.resolve(node)

    node = ast_util.rename_symbols(
        node, {qual_names.from_str('b.c'): qual_names.QN('renamed_b_c')})

    source = parser.unparse(node, include_encoding_marker=False)
    self.assertEqual(source.strip(), 'renamed_b_c = renamed_b_c.d')

  def test_rename_symbols_nonlocal(self):
    node = parser.parse('nonlocal a, b, c')
    node = qual_names.resolve(node)

    node = ast_util.rename_symbols(
        node, {qual_names.from_str('b'): qual_names.QN('renamed_b')})

    source = parser.unparse(node, include_encoding_marker=False)
    self.assertEqual(source.strip(), 'nonlocal a, renamed_b, c')

  def test_rename_symbols_global(self):
    node = parser.parse('global a, b, c')
    node = qual_names.resolve(node)

    node = ast_util.rename_symbols(
        node, {qual_names.from_str('b'): qual_names.QN('renamed_b')})

    source = parser.unparse(node, include_encoding_marker=False)
    self.assertEqual(source.strip(), 'global a, renamed_b, c')

  def test_rename_symbols_annotations(self):
    node = parser.parse('a[i]')
    node = qual_names.resolve(node)
    anno.setanno(node, 'foo', 'bar')
    orig_anno = anno.getanno(node, 'foo')

    node = ast_util.rename_symbols(node,
                                   {qual_names.QN('a'): qual_names.QN('b')})

    self.assertIs(anno.getanno(node, 'foo'), orig_anno)

  def test_rename_symbols_function(self):
    node = parser.parse('def f():\n  pass')
    node = ast_util.rename_symbols(node,
                                   {qual_names.QN('f'): qual_names.QN('f1')})

    source = parser.unparse(node, include_encoding_marker=False)
    self.assertEqual(source.strip(), 'def f1():\n    pass')

  def test_copy_clean(self):
    node = parser.parse(
        textwrap.dedent("""
      def f(a):
        return a + 1
    """))
    setattr(node, '__foo', 'bar')
    new_node = ast_util.copy_clean(node)
    self.assertIsNot(new_node, node)
    self.assertFalse(hasattr(new_node, '__foo'))

  def test_copy_clean_preserves_annotations(self):
    node = parser.parse(
        textwrap.dedent("""
      def f(a):
        return a + 1
    """))
    anno.setanno(node, 'foo', 'bar')
    anno.setanno(node, 'baz', 1)
    new_node = ast_util.copy_clean(node, preserve_annos={'foo'})
    self.assertEqual(anno.getanno(new_node, 'foo'), 'bar')
    self.assertFalse(anno.hasanno(new_node, 'baz'))

  def test_keywords_to_dict(self):
    keywords = parser.parse_expression('f(a=b, c=1, d=\'e\')').keywords
    d = ast_util.keywords_to_dict(keywords)
    # Make sure we generate a usable dict node by attaching it to a variable and
    # compiling everything.
    node = parser.parse('def f(b): pass')
    node.body.append(ast.Return(d))
    result, _, _ = loader.load_ast(node)
    self.assertDictEqual(result.f(3), {'a': 3, 'c': 1, 'd': 'e'})

  def assertMatch(self, target_str, pattern_str):
    node = parser.parse_expression(target_str)
    pattern = parser.parse_expression(pattern_str)
    self.assertTrue(ast_util.matches(node, pattern))

  def assertNoMatch(self, target_str, pattern_str):
    node = parser.parse_expression(target_str)
    pattern = parser.parse_expression(pattern_str)
    self.assertFalse(ast_util.matches(node, pattern))

  def test_matches_symbols(self):
    self.assertMatch('foo', '_')
    self.assertNoMatch('foo()', '_')
    self.assertMatch('foo + bar', 'foo + _')
    self.assertNoMatch('bar + bar', 'foo + _')
    self.assertNoMatch('foo - bar', 'foo + _')

  def test_matches_function_args(self):
    self.assertMatch('super(Foo, self).__init__(arg1, arg2)',
                     'super(_).__init__(_)')
    self.assertMatch('super().__init__()', 'super(_).__init__(_)')
    self.assertNoMatch('super(Foo, self).bar(arg1, arg2)',
                       'super(_).__init__(_)')
    self.assertMatch('super(Foo, self).__init__()', 'super(Foo, _).__init__(_)')
    self.assertNoMatch('super(Foo, self).__init__()',
                       'super(Bar, _).__init__(_)')

  def _mock_apply_fn(self, target, source):
    target = parser.unparse(target, include_encoding_marker=False)
    source = parser.unparse(source, include_encoding_marker=False)
    self._invocation_counts[(target.strip(), source.strip())] += 1

  def test_apply_to_single_assignments_dynamic_unpack(self):
    node = parser.parse('a, b, c = d')
    ast_util.apply_to_single_assignments(node.targets, node.value,
                                         self._mock_apply_fn)
    self.assertDictEqual(self._invocation_counts, {
        ('a', 'd[0]'): 1,
        ('b', 'd[1]'): 1,
        ('c', 'd[2]'): 1,
    })

  def test_apply_to_single_assignments_static_unpack(self):
    node = parser.parse('a, b, c = d, e, f')
    ast_util.apply_to_single_assignments(node.targets, node.value,
                                         self._mock_apply_fn)
    self.assertDictEqual(self._invocation_counts, {
        ('a', 'd'): 1,
        ('b', 'e'): 1,
        ('c', 'f'): 1,
    })

  def test_parallel_walk(self):
    src = """
      def f(a):
        return a + 1
    """
    node = parser.parse(textwrap.dedent(src))
    for child_a, child_b in ast_util.parallel_walk(node, node):
      self.assertEqual(child_a, child_b)

  def test_parallel_walk_string_leaves(self):
    src = """
      def f(a):
        global g
    """
    node = parser.parse(textwrap.dedent(src))
    for child_a, child_b in ast_util.parallel_walk(node, node):
      self.assertEqual(child_a, child_b)

  def test_parallel_walk_inconsistent_trees(self):
    node_1 = parser.parse(
        textwrap.dedent("""
      def f(a):
        return a + 1
    """))
    node_2 = parser.parse(
        textwrap.dedent("""
      def f(a):
        return a + (a * 2)
    """))
    node_3 = parser.parse(
        textwrap.dedent("""
      def f(a):
        return a + 2
    """))
    with self.assertRaises(ValueError):
      for _ in ast_util.parallel_walk(node_1, node_2):
        pass
    # There is not particular reason to reject trees that differ only in the
    # value of a constant.
    # TODO(mdan): This should probably be allowed.
    with self.assertRaises(ValueError):
      for _ in ast_util.parallel_walk(node_1, node_3):
        pass

  def assertLambdaNodes(self, matching_nodes, expected_bodies):
    self.assertEqual(len(matching_nodes), len(expected_bodies))
    for node in matching_nodes:
      self.assertIsInstance(node, gast.Lambda)
      self.assertIn(
          parser.unparse(node.body, include_encoding_marker=False).strip(),
          expected_bodies)

if __name__ == '__main__':
  test.main()


text:
module Gitlab
  module Ci
    module Ansi2json
      def self.convert(ansi, state = nil)
        Converter.new.convert(ansi, state)
      end
    end
  end
end


text:
var plugin = require('./index');
var base = require('@jupyter-widgets/base');

module.exports = {
  id: 'tensorflow_model_analysis',
  requires: [base.IJupyterWidgetRegistry],
  activate: function(app, widgets) {
    // Set a global variable to mark plugin as being run within Jupyter Lab.
    window['isJupyterLab'] = true;
    widgets.registerWidget({
      name: 'tensorflow_model_analysis',
      version: plugin.version,
      exports: plugin
    });
  },
  autoStart: true
};


text:
"""
    `Unit tests for cargo.statements.Insert`
--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--
   2016 Jared Lunde © The MIT License (MIT)
   http://github.com/jaredlunde
"""
import pickle
import random

from vital.security import randhex

from cargo import *
from cargo.orm import QueryState
from cargo.statements import Insert

from unit_tests import configure
from unit_tests.configure import new_field, new_clause, new_expression, \
                                 new_function

class TestInsert(configure.StatementTestCase):

    def test___init__(self):
        self.orm.uid(random.randint(0, 10000000))
        self.orm.payload(*self.orm.fields)
        self.orm.into('foo')
        q = Insert(self.orm)
        self.assertIs(q.orm, self.orm)

    def test_execute(self):
        self.orm.uid(random.randint(0, 10000000))
        self.orm.returning("*")
        self.orm.payload(*self.orm.fields)
        self.orm.into('foo')
        q = Insert(self.orm)
        cur = q.execute()
        item = q.orm.state.get('VALUES')
        self.assertIsNotNone(cur.fetchall()[0])

    def test__evaluate_state(self):
        self.orm.uid(random.randint(0, 10000000))
        clauses = [
            new_clause('INTO', safe('foo')),
            new_clause('RETURNING', safe('textfield'))
        ]
        self.orm.state.add(*clauses)
        self.orm.payload(*self.orm.fields)
        self.orm.into('foo')
        q = Insert(self.orm)
        self.assertIn(clauses[0].string, q.query)
        self.assertIn(clauses[1].string, q.query)
        self.assertIn(self.orm.fields[1].field_name, q.query)
        self.assertIn(self.orm.fields[0].field_name, q.query)

    def test_many(self):
        clauses = [
            new_clause('INTO', safe('foo')),
            new_clause('RETURNING', safe('textfield'))
        ]
        self.orm.state.add(*clauses)
        self.orm.values(random.randint(0, 100000), randhex(10))
        self.orm.values(random.randint(0, 100000), randhex(10))
        self.orm.payload(*(field for field in self.orm.fields
                         if field(random.randint(0, 1000000))))
        self.orm.into('foo')
        q = Insert(self.orm)
        self.assertIn(clauses[0].string, q.query)
        self.assertIn(clauses[1].string, q.query)
        self.assertIn(self.orm.fields[1].field_name, q.query)
        self.assertIn(self.orm.fields[0].field_name, q.query)
        self.assertEqual(len(q.execute().fetchall()), 3)

    '''def test_pickle(self):
        values = [
            field.value
            for field in self.orm.fields
            if field._should_insert() or field.default is not None
        ]
        self.orm.values(*values)
        self.orm.values(*values)
        q = Insert(self.orm, *self.orm.fields)
        b = pickle.loads(pickle.dumps(q))
        for k in dir(q):
            if k == '_client':
                continue
            if isinstance(
               getattr(q, k), (str, list, tuple, dict, int, float)):
                self.assertEqual(getattr(q, k), getattr(b, k))
            else:
                self.assertTrue(
                    getattr(q, k).__class__ == getattr(b, k).__class__)'''

if __name__ == '__main__':
    # Unit test
    configure.run_tests(TestInsert)


text:
require 'spec_helper'
require 'pact/provider/request'

describe Pact::Provider::Request::Replayable do

  let(:path) { '/path?something' }
  let(:body) { {a: 'body'} }
  let(:headers) { {} }
  let(:expected_request) do
    instance_double('Pact::Request::Expected',
      :method => 'post',
      :full_path => path,
      :body => body,
      :headers => headers)
  end

  subject { described_class.new(expected_request)}

  describe "method" do
    it 'returns the method' do
      expect(subject.method).to eq 'post'
    end
  end
  describe "path" do
    it "returns the full path" do
      expect(subject.path).to eq(path)
    end
  end

  describe "body" do
    context "when body is a NullExpectation" do
      let(:body) { Pact::NullExpectation.new }
      it "returns an empty string, not sure if it should do this or return nil???" do
        expect(subject.body).to eq ""
      end
    end
    context "when body is an empty string" do
      let(:body) { '' }
      it "returns an empty string" do
        expect(subject.body).to eq ""
      end
    end
    context "when body is a string" do
      let(:body) { 'a string'}
      it "returns the string" do
        expect(subject.body).to eq body
      end
    end
    context "when body is a Term" do
      let(:body) { Pact::Term.new(generate: 'a', matcher: /a/) }
      it "returns the generated value" do
        expect(subject.body).to eq "a"
      end
    end
    context "when body is not a string" do
      let(:body) { {a: 'body'} }
      it "returns the object as a json string" do
        expect(subject.body).to eq body.to_json
      end
    end
  end

  describe "headers" do
    context "when headers are expected" do
      let(:headers) { {"Content-Type" => "text/plain", "Accept" => "application/json"} }
      let(:expected_headers) { {"CONTENT_TYPE" => "text/plain", "HTTP_ACCEPT" => "application/json"} }
      it "transforms the headers into Rack format" do
        expect(subject.headers).to eq( expected_headers )
      end
    end
    context "when headers are not specified" do
      let(:headers) { Pact::NullExpectation.new }
      it "returns an empty hash" do
        expect(subject.headers).to eq({})
      end
    end
  end
end


text:
using System.Web.Mvc;
using System.Linq;
using Kendo.Mvc.Examples.Models;

namespace Kendo.Mvc.Examples.Controllers
{
    public partial class GridController : Controller
    {
        public ActionResult ServerRowTemplate()
        {
            return View(new NorthwindDataContext().Customers);
        }
    }
}


text:
layout: post
title:  "The Complexity of Nested Forms "
date:   2017-09-17 12:06:17 -0400
---

**The Big Picture**

In this lab, we are working with two models.  Namely, we are working with a `Post` and a `Tag`.  There are other models but we are focusing on these two.  We are looking at, exploiting, the association between these two models.  So, in our app, a `user`can create a new `post`, and they can add any number of `tags` they would like from a list of provided `tags`.  We want to create the functionality on our `post` form to allow the user to create a new `tag`.  This is reasonable enough.  The difficulty comes when we need to both instantiate a new `tag` and associate that `tag` with the newly instanatiated `post`.  To do this we must look at * nested forms.*

**The Frame Work**

In our application, our Post model `has_many` `tags, :through`, and our `Tag` model `has_many` `posts, :through` the `post_tags` table.  This association is provided by a joins-table, `post_tags`.  We join these two models by connecting them through the `post_tags` joins-table.

```
class Post < ActiveRecord::Base
  has_many :post_tags
  has_many :tags, :through => :post_tags
```

```
class Tag < ActiveRecord::Base
  has_many :post_tags
  has_many :posts, :through => :post_tags
```

What this does, out of the box, is allows us to ask a `@post` how many `tags` it has, with `@post.tags`.  Ultimately, what we want to be able to do is to nest the `tag` attribute `name` with our `post` on our `post` form page so it looks like, `@post[:tag][:name]`.  Rails will do a lot of heavy lifting for use, to accoplish this.

**The Role of Rails**

At this point, we have our associations wired up: we have our datatables, with the appropriate joins-table; we have our models with the necessary `has_many` relationships.  We now need to add some functionality to our `post` form.  Rails has a powerful metho, `accepts_nested_attributes_for`, which provides us the ability to nest data structures in our `post` form.  We add this method to our `Post`model, and allow to accept the attributes of `tags`.

```
class Post < ActiveRecord::Base
  has_many :post_tags
  has_many :tags, :through => :post_tags

	accepts_nested_attributes_for :tags
```

Now we can go to our form page, and write the functionality that will allow us to enter a new `tag`, and associated with the newly instantiated `post`.  We start with a form_for, passing it the instance variable `@post`.  This instance variable, `@post`, is made in the `posts#new`action, and provides rails with an object to work with.

```
<%= form_for(@post) do |f| %>
```

For the `post`, we pass the variable `f` the rails' method `.label` and `.text_field`.  This provides the html to allow the user to enter a the content of their post.  We wrap this in a <fieldset>.

```
<fieldset>
    <%= f.label :name %><br>
    <%= f.text_field :name %><br>
    <%= f.label :content %><br>
    <%= f.text_area :content %><br>
  </fieldset>
```

Additionally, we can provide a list of checkboxes for the user to pick the tag or tags they would like to associate with their `post`.  We can do this using the rails' method `.collection_check_boxes`.

```
    <%= f.collection_check_boxes :tag_ids, Tag.all, :id, :name %>
```

But what we want to do is add a new `tag` with its attributes.  This is where the functionality of `accepts_nested_attributes_for`is put on full display.  We call the rails' method `.fields_for`, and pass it two arguements.  The first is the parent object, in this case, our `@post`.  This is done with the variable `f`.  Then we pass it the variable `:tags`.

```
<%= f.fields_for :tags do |tag_forms| %>
      <%= tag_forms.label :name %>
      <%= tag_forms.text_field :name %>
    <% end %>
```

Now, the variable `tag_forms` gives us access to a ActionView::Helpers::FormBuilder.  This builder method gives us access to two objects: `post` and `tag`.  And, this is where the magic happens, it nests for us the attributes of our newly formed `tag`, and associates it with our newly instantiated `post`.  Here is the html that `tag_forms` produces.

```
#<input type="text" name="post[tags_attributes][0][name]" id="post_tags_attributes_0_name">"
```

There's a few things that I did that perhaps you can learn from.

**Remember to...**

When I began this lab, I started with the database.  Next, I made sure the models were correctly associated, and then I began to work on the `post` form.  After some review, I was able to build the `fields_for`that I wanted.  However, when I updated the browser, I got nothing!  The code didn't break, it just didn't render the output that I wanted.  After more review, I was reminded that, like the `@post` in the `posts#new`controller action, I needed to start the building process for `tags`.  I used the rails method `build`, which is a method like `new`, but `build`is smart enough to set the foreigh key.  So, once I updated my `posts#new`controller action, everything worked beautifully.

```
def new
    @post = Post.new
    @post.tags.build
  end
```

Okay, now the new data is passed to the `posts#create`controller action, and however, when I look at the `post_params`, I am unable to find my nested data.  I needed to update my strong params, `post_params`, to be able to instantiate a new `tag`and its attributes.  I updated my `post_params` with `:tags_attributes =>[:name]`.

```
def post_params
      params.require(:post).permit(:name, :content, :tags_attributes =>[:name], :tag_ids => [])
    end
```

After this last addition, I was able to instantiate both a new blog post with a new tag and its attribute(s).

**Conclusion**

I have been enjoying learning Rails.  The power and functionality that is at your finger tips is wonderful.  However, sometimes, you have to look under the hood, in order to make sense of all the moving parts.  What seemingly in straight forward functionality you are trying to initiate, becomes very abstract with Rails doing much of the heavy lifting.  It is important to go back, and review the underlying methods provided to us through Rails.


text:
package org.apache.spark.sql.util

import java.util.Locale

import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.catalog.v2.expressions._
import org.apache.spark.sql.catalyst.analysis._
import org.apache.spark.sql.types.{ArrayType, DataType, MapType, StructField, StructType}

/**
 * Utils for handling schemas.
 *
 * TODO: Merge this file with [[org.apache.spark.ml.util.SchemaUtils]].
 */
private[spark] object SchemaUtils {

  /**
   * Checks if an input schema has duplicate column names. This throws an exception if the
   * duplication exists.
   *
   * @param schema schema to check
   * @param colType column type name, used in an exception message
   * @param caseSensitiveAnalysis whether duplication checks should be case sensitive or not
   */
  def checkSchemaColumnNameDuplication(
      schema: StructType, colType: String, caseSensitiveAnalysis: Boolean = false): Unit = {
    checkColumnNameDuplication(schema.map(_.name), colType, caseSensitiveAnalysis)
  }

  // Returns true if a given resolver is case-sensitive
  private def isCaseSensitiveAnalysis(resolver: Resolver): Boolean = {
    if (resolver == caseSensitiveResolution) {
      true
    } else if (resolver == caseInsensitiveResolution) {
      false
    } else {
      sys.error("A resolver to check if two identifiers are equal must be " +
        "`caseSensitiveResolution` or `caseInsensitiveResolution` in o.a.s.sql.catalyst.")
    }
  }

  /**
   * Checks if input column names have duplicate identifiers. This throws an exception if
   * the duplication exists.
   *
   * @param columnNames column names to check
   * @param colType column type name, used in an exception message
   * @param resolver resolver used to determine if two identifiers are equal
   */
  def checkColumnNameDuplication(
      columnNames: Seq[String], colType: String, resolver: Resolver): Unit = {
    checkColumnNameDuplication(columnNames, colType, isCaseSensitiveAnalysis(resolver))
  }

  /**
   * Checks if input column names have duplicate identifiers. This throws an exception if
   * the duplication exists.
   *
   * @param columnNames column names to check
   * @param colType column type name, used in an exception message
   * @param caseSensitiveAnalysis whether duplication checks should be case sensitive or not
   */
  def checkColumnNameDuplication(
      columnNames: Seq[String], colType: String, caseSensitiveAnalysis: Boolean): Unit = {
    // scalastyle:off caselocale
    val names = if (caseSensitiveAnalysis) columnNames else columnNames.map(_.toLowerCase)
    // scalastyle:on caselocale
    if (names.distinct.length != names.length) {
      val duplicateColumns = names.groupBy(identity).collect {
        case (x, ys) if ys.length > 1 => s"`$x`"
      }
      throw new AnalysisException(
        s"Found duplicate column(s) $colType: ${duplicateColumns.mkString(", ")}")
    }
  }

  /**
   * Returns all column names in this schema as a flat list. For example, a schema like:
   *   | - a
   *   | | - 1
   *   | | - 2
   *   | - b
   *   | - c
   *   | | - nest
   *   |   | - 3
   *   will get flattened to: "a", "a.1", "a.2", "b", "c", "c.nest", "c.nest.3"
   */
  def explodeNestedFieldNames(schema: StructType): Seq[String] = {
    def explode(schema: StructType): Seq[Seq[String]] = {
      def recurseIntoComplexTypes(complexType: DataType): Seq[Seq[String]] = {
        complexType match {
          case s: StructType => explode(s)
          case a: ArrayType => recurseIntoComplexTypes(a.elementType)
          case m: MapType =>
            recurseIntoComplexTypes(m.keyType).map(Seq("key") ++ _) ++
              recurseIntoComplexTypes(m.valueType).map(Seq("value") ++ _)
          case _ => Nil
        }
      }

      schema.flatMap {
        case StructField(name, s: StructType, _, _) =>
          Seq(Seq(name)) ++ explode(s).map(nested => Seq(name) ++ nested)
        case StructField(name, a: ArrayType, _, _) =>
          Seq(Seq(name)) ++ recurseIntoComplexTypes(a).map(nested => Seq(name) ++ nested)
        case StructField(name, m: MapType, _, _) =>
          Seq(Seq(name)) ++ recurseIntoComplexTypes(m).map(nested => Seq(name) ++ nested)
        case f => Seq(f.name) :: Nil
      }
    }

    explode(schema).map(UnresolvedAttribute.apply(_).name)
  }

  /**
   * Checks if the partitioning transforms are being duplicated or not. Throws an exception if
   * duplication exists.
   *
   * @param transforms the schema to check for duplicates
   * @param checkType contextual information around the check, used in an exception message
   * @param isCaseSensitive Whether to be case sensitive when comparing column names
   */
  def checkTransformDuplication(
      transforms: Seq[Transform],
      checkType: String,
      isCaseSensitive: Boolean): Unit = {
    val extractedTransforms = transforms.map {
      case b: BucketTransform =>
        val colNames = b.columns.map(c => UnresolvedAttribute(c.fieldNames()).name)
        // We need to check that we're not duplicating columns within our bucketing transform
        checkColumnNameDuplication(colNames, "in the bucket definition", isCaseSensitive)
        b.name -> colNames
      case NamedTransform(transformName, refs) =>
        val fieldNameParts =
          refs.collect { case FieldReference(parts) => UnresolvedAttribute(parts).name }
        // We could also check that we're not duplicating column names here as well if
        // fieldNameParts.length > 1, but we're specifically not, because certain transforms can
        // be defined where this is a legitimate use case.
        transformName -> fieldNameParts
    }
    val normalizedTransforms = if (isCaseSensitive) {
      extractedTransforms
    } else {
      extractedTransforms.map(t => t._1 -> t._2.map(_.toLowerCase(Locale.ROOT)))
    }

    if (normalizedTransforms.distinct.length != normalizedTransforms.length) {
      val duplicateColumns = normalizedTransforms.groupBy(identity).collect {
        case (x, ys) if ys.length > 1 => s"${x._2.mkString(".")}"
      }
      throw new AnalysisException(
        s"Found duplicate column(s) $checkType: ${duplicateColumns.mkString(", ")}")
    }
  }

  /**
   * Returns the given column's ordinal within the given `schema`. The length of the returned
   * position will be as long as how nested the column is.
   *
   * @param column The column to search for in the given struct. If the length of `column` is
   *               greater than 1, we expect to enter a nested field.
   * @param schema The current struct we are looking at.
   * @param resolver The resolver to find the column.
   */
  def findColumnPosition(
      column: Seq[String],
      schema: StructType,
      resolver: Resolver): Seq[Int] = {
    def find(column: Seq[String], schema: StructType, stack: Seq[String]): Seq[Int] = {
      if (column.isEmpty) return Nil
      val thisCol = column.head
      lazy val columnPath = UnresolvedAttribute(stack :+ thisCol).name
      val pos = schema.indexWhere(f => resolver(f.name, thisCol))
      if (pos == -1) {
        throw new IndexOutOfBoundsException(columnPath)
      }
      val children = schema(pos).dataType match {
        case s: StructType =>
          find(column.tail, s, stack :+ thisCol)
        case ArrayType(s: StructType, _) =>
          find(column.tail, s, stack :+ thisCol)
        case o =>
          if (column.length > 1) {
            throw new AnalysisException(
              s"""Expected $columnPath to be a nested data type, but found $o. Was looking for the
                 |index of ${UnresolvedAttribute(column).name} in a nested field
              """.stripMargin)
          }
          Nil
      }
      Seq(pos) ++ children
    }

    try {
      find(column, schema, Nil)
    } catch {
      case i: IndexOutOfBoundsException =>
        throw new AnalysisException(
          s"Couldn't find column ${i.getMessage} in:\n${schema.treeString}")
      case e: AnalysisException =>
        throw new AnalysisException(e.getMessage + s":\n${schema.treeString}")
    }
  }

  /**
   * Gets the name of the column in the given position.
   */
  def getColumnName(position: Seq[Int], schema: StructType): Seq[String] = {
    val topLevel = schema(position.head)
    val field = position.tail.foldLeft(Seq(topLevel.name) -> topLevel) {
      case (nameAndField, pos) =>
        nameAndField._2.dataType match {
          case s: StructType =>
            val nowField = s(pos)
            (nameAndField._1 :+ nowField.name) -> nowField
          case ArrayType(s: StructType, _) =>
            val nowField = s(pos)
            (nameAndField._1 :+ nowField.name) -> nowField
          case _ =>
            throw new AnalysisException(
              s"The positions provided ($pos) cannot be resolved in\n${schema.treeString}.")
      }
    }
    field._1
  }
}


text:
import config from '../../config';

// Load Passport's
Object.keys(config.oAuth).forEach((key) => {
  if (config.oAuth[key].enabled)
    require(`../passports/${key}.passport`);
});


text:
<VerticalLayout captionMargin="0" margin="true" width="100%" height="100%" spacing="true">
  <ValidationSettings withApply="false" withAttach="true" withPrint="true" />
  <GuiTable title="COMPANIES" name="COMPANY_TABLE" dataPath="DATAROOT" sortingExpression="NAME" pageLength="10">
    <OpenForm containerWindow="same window" />
    <TableColumn name="NAME" caption="Name" link="true"/>
    <TableColumn name="DESCRIP" caption="Description" />
  </GuiTable>
</VerticalLayout>


text:
package org.apache.pluto.container.bean.processor.fixtures.mocks;

import java.util.Collection;

import javax.portlet.PortletMode;
import javax.portlet.RenderResponse;

/**
 * @author Scott Nicklous
 *
 */
public class MockRenderResponse extends MockMimeResponse implements RenderResponse {

   /* (non-Javadoc)
    * @see javax.portlet.RenderResponse#setNextPossiblePortletModes(java.util.Collection)
    */
   @Override
   public void setNextPossiblePortletModes(Collection<? extends PortletMode> arg0) {
   }

   /* (non-Javadoc)
    * @see javax.portlet.RenderResponse#setTitle(java.lang.String)
    */
   @Override
   public void setTitle(String arg0) {
   }

}


text:
namespace display {

// Observer class used by NativeDisplayDelegate to announce when the display
// configuration changes.
class DISPLAY_TYPES_EXPORT NativeDisplayObserver {
 public:
  virtual ~NativeDisplayObserver() {}

  virtual void OnConfigurationChanged() = 0;

  // DisplaySnapshots owned by NativeDisplayDelegate are about to be
  // invalidated and any stored pointers to them should be deleted.
  virtual void OnDisplaySnapshotsInvalidated() = 0;
};

}  // namespace display

#endif  // UI_DISPLAY_TYPES_NATIVE_DISPLAY_OBSERVER_H_


text:
layout: post
title: √2 is crazy find out why
categories: musings, Maths
tags:
- musings
- Maths
---

Back in my school days, my mathematics professor always used to praise maths as **_Natural Science_**. It is indeed. However during school / college days, I used to wonder why the hell I'm learning the differentiation / integration / ordinary differential equations / Fourier transforms bla bla bla.
However, after spending 7 odd years in IT career and filling by mind with arrays, structures, sockets, RPCs, observer design patters, memory leaks, core dumps, GDB, conference calls, proposals, delivery **_Huhhhhh_**  😦 I wanted to go back to my 10 std and immerse myself in _trigonometry_ & _algebra_.

My friends used to mock me being a nerd as I always use to tell speed of the light is not $$ 3 \times 10^8 m/sec $$ , it is $$ 2.99792458 \times 10^6 m/sec $$ .  :) [ Now I know, why those people called me a nerd  :) ]

Mathematics & Physics were my most sought-after subject. It still intrigues me when I see movies like A beautiful mind Apollo 13 Inter-Stellar Martian etc. Not just for sci-fi scenes ( could anyone forget Back to the future series wow… ), but for the subtle physical & mathematical facts that is buried deep inside story and dialogues.

Of all the mathematical figures, $$ \sqrt{2} $$ is my favorite number. It is because, it a number, however it is categorized as *irrational*.

> Irrational means, not being rational. i.e going [bonkers](http://www.thesaurus.com/browse/going%20bonkers)

Well let me explain how.

Any rational number can be explained in fractional form. So let us say  $$ \sqrt{2} $$ can be expressed as by 2 numbers $$ p $$ & $$ q $$, such that, $$ \frac {p}{q} = \sqrt{2} $$

But we should also remember that, P or Q should be ODD number. Because, if both P & Q are even number, then should get cancelled until, they become odd. Just think about it, $$ \frac {128}{48} $$ will eventually become $$ \frac {8}{3} $$ . So our first _premise_ is this.

> **_$$ \sqrt{2} $$ is a rational number expressed by $$ \frac {p}{q} = \sqrt{2} $$, such that P or Q are odd numbers._**

Now let us try to prove our premise and try to add support for our argument.

$$
\begin{align}
\sqrt{2} & = \frac{p}{q} \\
& = \frac{2n}{q}  \text{p = 2n} \\
& = 2 = \frac{4n^2}{q^2}  \text{squaring on both sides} \\
& = 2q^2 = 4n^2  \text{re-arranging} \\
& = q^2 = 2n^2   \text{Taking out the common factor}
& = \approx q^2 \approx \text{q is even}
\end{align}
$$

_Eq-1_ <center> $$ \frac {p}{q} = \sqrt{2} $$ </center> [ premise ]

_Eq-2_ <center> $$ \frac {p^2}{q^2} = 2 $$    </center> [ squaring on both sides ]

_Eq-3_ <center> $$ p^2 = 2q^2 $$           </center> [ re-arranging ]

Since anything multiplied by $$ 2 $$ is _even number_, we can term that, $$ p^2 $$ is _even_ . If $$ p^2 $$ is even, then even $$ p $$ is even, since square of an odd number is odd and square of even number is even.

Okay, so now we had deduced $$ p $$ is even, there can be only one thing possible to prove the above premise. i.e $$ q $$ is _Odd_.
Let us try to find out, whether $$ q $$ is odd or not.

**Eq-4** $$ \frac {2n}{q} = \sqrt{2} $$  [ Given p is even, any even number p can be represented as $$ p = 2n $$, where n being odd or even ]


text:
package com.twosigma.beaker.widgets;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import com.twosigma.jupyter.handler.Handler;
import com.twosigma.jupyter.message.Message;

import static com.google.common.base.Preconditions.checkNotNull;

public abstract class DOMWidget extends Widget {

  public static final String DATA = "data";
  public static final String SYNC_DATA = "sync_data";

  private Layout layout;

  private UpdateValueCallback updateValueCallback = () -> {
  };

  public DOMWidget() {
    super();
    layout = new Layout();
  }

  @SuppressWarnings("unchecked")
  @Override
  protected void addValueChangeMsgCallback() {
    getComm().addMsgCallbackList(new ValueChangeMsgCallbackHandler() {

      @Override
      public void updateValue(Object value, Message message) {
        DOMWidget.this.doUpdateValueWithCallback(value);
      }

    });

  }

  public abstract class ValueChangeMsgCallbackHandler implements Handler<Message> {

    @SuppressWarnings("unchecked")
    public Optional<Object> getSyncDataValue(Message msg){
      Optional<Object> ret = Optional.empty();
      if (msg != null && msg.getContent() != null && msg.getContent().containsKey(DATA)) {
        Map<String,Serializable> data = (Map<String,Serializable>) msg.getContent().get(DATA);
        if (data.containsKey(SYNC_DATA)) {
          Map<String,Serializable> sync_data = (Map<String,Serializable>) data.get(SYNC_DATA);
          if (sync_data.containsKey(VALUE)) {
            ret = Optional.of(sync_data.get(VALUE));
          }
        }
      }
      return ret;
    }

    public void handle(Message message){
      Optional<Object> value = getSyncDataValue(message);
      if(value.isPresent()){
        updateValue(value.get(), message);
      }
    }

    public abstract void updateValue(Object value, Message message);

  }

  public void register(UpdateValueCallback updateValueCallback) {
    this.updateValueCallback = checkNotNull(updateValueCallback);
  }

  public abstract void updateValue(Object value);

  public void doUpdateValueWithCallback(Object value){
    updateValue(value);
    this.updateValueCallback.execute();
  }

  @Override
  protected HashMap<String, Serializable> content(HashMap<String, Serializable> content) {
    content.put(Layout.LAYOUT, Layout.IPY_MODEL + getLayout().getComm().getCommId());
    content.put("font_family", "");
    content.put("font_size", "");
    content.put("font_style", "");
    content.put("font_weight", "");
    content.put("background_color", null);
    content.put("color", null);
    return content;
  }

  public Layout getLayout() {
    if(layout == null){
      layout = new Layout();
    }
    return layout;
  }

}


text:
package com.instructure.canvasapi.api;

import com.instructure.canvasapi.model.Alert;
import com.instructure.canvasapi.utilities.APIHelpers;
import com.instructure.canvasapi.utilities.CanvasCallback;
import com.instructure.canvasapi.utilities.ExhaustiveBridgeCallback;

import retrofit.Callback;
import retrofit.client.Response;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Path;

public class AlertAPI extends BuildInterfaceAPI {

    public static final String AIRWOLF_DOMAIN_AMERICA = "https://airwolf-iad-prod.instructure.com/";
    public static final String AIRWOLF_DOMAIN_DUBLIN = "https://airwolf-dub-prod.instructure.com/";
    public static final String AIRWOLF_DOMAIN_SYDNEY = "https://airwolf-syd-prod.instructure.com/";
    public static final String AIRWOLF_DOMAIN_SINGAPORE = "https://airwolf-sin-prod.instructure.com/";
    public static final String AIRWOLF_DOMAIN_FRANKFURT = "https://airwolf-fra-prod.instructure.com/";

    public static final String[] AIRWOLF_DOMAIN_LIST = { AIRWOLF_DOMAIN_AMERICA, AIRWOLF_DOMAIN_DUBLIN,
            AIRWOLF_DOMAIN_SYDNEY, AIRWOLF_DOMAIN_SINGAPORE, AIRWOLF_DOMAIN_FRANKFURT };

    interface AlertInterface {
        @GET("/alerts/student/{parentId}/{studentId}")
        void getFirstPageOfAlertsForStudent(@Path("parentId") String parentId, @Path("studentId") String studentId, Callback<Alert[]> callback);

        @GET("/{next}")
        void getNextPageOfAlertsForStudent(@Path(value = "next", encode = false) String nextURL, CanvasCallback<Alert[]> callback);

        @FormUrlEncoded
        @POST("/alert/{parentId}/{alertId}")
        void markAlertAsRead(@Path("parentId") String parentId, @Path("alertId") String alertId, @Field("read") String isRead, CanvasCallback<Response> callback);

        @FormUrlEncoded
        @POST("/alert/{parentId}/{alertId}")
        void markAlertAsDismissed(@Path("parentId") String parentId, @Path("alertId") String alertId, @Field("dismissed") String isDismissed, CanvasCallback<Response> callback);

    }

    /////////////////////////////////////////////////////////////////////////
    // API Calls
    /////////////////////////////////////////////////////////////////////////

    public static void getAllAlertsForStudent(String parentId, String studentId, final CanvasCallback<Alert[]> callback){
        if(APIHelpers.paramIsNull(callback)) { return; }

        CanvasCallback<Alert[]> bridge = new ExhaustiveBridgeCallback<>(Alert.class, callback, new ExhaustiveBridgeCallback.ExhaustiveBridgeEvents() {
            @Override
            public void performApiCallWithExhaustiveCallback(CanvasCallback bridgeCallback, String nextURL, boolean isCached) {
                if(callback.isCancelled()) { return; }

                AlertAPI.getNextPageAlertsChained(bridgeCallback, nextURL, isCached);
            }
        });

        buildCacheInterface(AlertInterface.class, APIHelpers.getAirwolfDomain(callback.getContext()), callback).getFirstPageOfAlertsForStudent(parentId, studentId, bridge);
        buildInterface(AlertInterface.class, APIHelpers.getAirwolfDomain(callback.getContext()), callback).getFirstPageOfAlertsForStudent(parentId, studentId, bridge);
    }

    public static void getNextPageAlertsChained(CanvasCallback<Alert[]> callback, String nextURL, boolean isCached) {
        if (APIHelpers.paramIsNull(callback, nextURL)) return;

        callback.setIsNextPage(true);
        if (isCached) {
            buildCacheInterface(AlertInterface.class, APIHelpers.getAirwolfDomain(callback.getContext()), callback, false).getNextPageOfAlertsForStudent(nextURL, callback);
        } else {
            buildInterface(AlertInterface.class, APIHelpers.getAirwolfDomain(callback.getContext()), callback, false).getNextPageOfAlertsForStudent(nextURL, callback);
        }
    }

    public static void markAlertAsRead(String parentId, String alertId, CanvasCallback<Response> callback) {
        if (APIHelpers.paramIsNull(callback)) return;

        buildInterface(AlertInterface.class, APIHelpers.getAirwolfDomain(callback.getContext()), callback, false).markAlertAsRead(parentId, alertId, "true", callback);
    }

    public static void markAlertAsDismissed(String parentId, String alertId, CanvasCallback<Response> callback) {
        if (APIHelpers.paramIsNull(callback)) return;

        buildInterface(AlertInterface.class, APIHelpers.getAirwolfDomain(callback.getContext()), callback, false).markAlertAsDismissed(parentId, alertId, "true", callback);
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using EasyRpc.AspNetCore.EndPoints;

namespace EasyRpc.AspNetCore.Routing
{
    /// <summary>
    /// Service that provides an internal routing method path => IEndPointHandler
    /// </summary>
    public interface IInternalEndPointRouteBuilder
    {
        /// <summary>
        /// Builds routing function given a dictionary of handlers
        /// </summary>
        /// <param name="handlers"></param>
        /// <returns></returns>
        Func<string, IEndPointHandler> BuildRouteFunc(IDictionary<string, IEndPointHandler> handlers);
    }

    /// <summary>
    /// Internal route building service
    /// </summary>
    public class InternalEndPointRouteBuilder : IInternalEndPointRouteBuilder
    {
        private readonly ParameterExpression _pathParameter = Expression.Parameter(typeof(string), "path");
        private readonly PropertyInfo _charsProperty = typeof(string).GetProperty("Chars");
        private readonly PropertyInfo _lengthProperty = typeof(string).GetProperty("Length");

        /// <inheritdoc />
        public Func<string, IEndPointHandler> BuildRouteFunc(IDictionary<string, IEndPointHandler> handlers)
        {
            List<KeyValuePair<string, IEndPointHandler>> pathList = null;

            if (handlers.Count == 0)
            {
                return s => null;
            }

            pathList = handlers.ToList();

            pathList.Sort((x, y) => Comparer<string>.Default.Compare(x.Key, y.Key));

            return GenerateStartingMethod(pathList);
        }

        private Func<string, IEndPointHandler> GenerateStartingMethod(List<KeyValuePair<string, IEndPointHandler>> pathList)
        {
            var searchMethod = GenerateSearchMethod(pathList, 0, 0, pathList.Count);

            return GenerateDelegate(searchMethod);
        }

        private Expression GenerateSearchMethod(List<KeyValuePair<string, IEndPointHandler>> pathList, int currentStringIndex,
            int pathListStart, int pathListEnd, int level = 0)
        {
            var distinctCharacters = DistinctCharacters(pathList, currentStringIndex, pathListStart, pathListEnd);

            if (distinctCharacters == 1)
            {
                return GenerateLongMatch(pathList, currentStringIndex, pathListStart, pathListEnd, level);
            }

            if (pathListEnd - pathListStart < 10)
            {
                return GenerateNodeMethod(pathList, currentStringIndex, pathListStart, pathListEnd);
            }

            if (distinctCharacters < 5)
            {
                return GenerateIfBranchMethod(pathList, currentStringIndex, pathListStart, pathListEnd, level, distinctCharacters);
            }

            return GenerateSwitch(pathList, currentStringIndex, pathListStart, pathListEnd);
        }

        private Expression GenerateLongMatch(List<KeyValuePair<string, IEndPointHandler>> pathList, int currentStringIndex, int pathListStart, int pathListEnd, int level)
        {
            var longMatch = PathMatchCount(pathList, currentStringIndex, pathListStart, pathListEnd);

            // this is to handle the case where the path ends with a / and it should still match
            if (pathListEnd - pathListStart == 1 && pathList[pathListStart].Key.EndsWith("/"))
            {
                longMatch--;
            }

            var comparisonStatement =
                GenerateStringComparisonStatements(pathList[pathListStart].Key, currentStringIndex, longMatch, longMatch);

            Expression matchLogic = null;

            if (pathListEnd - pathListStart > 1)
            {
                matchLogic = GenerateSearchMethod(pathList, currentStringIndex + longMatch, pathListStart, pathListEnd, level);
            }
            else
            {
                matchLogic = Expression.Constant(pathList[pathListStart].Value, typeof(IEndPointHandler));
            }

            return Expression.Condition(comparisonStatement, matchLogic, Expression.Constant(null, typeof(IEndPointHandler)));
        }

        private BinaryExpression GenerateStringComparisonStatements(string path, int currentStringIndex, int stringLength, int testLength)
        {
            Expression currentExpression = null;

            for (int i = 0; i < stringLength; i++)
            {
                var index = currentStringIndex + i;

                var testExpression = GenerateCharacterComparisonStatement(index, path[index]);

                if (currentExpression == null)
                {
                    currentExpression = testExpression;
                }
                else
                {
                    currentExpression = Expression.AndAlso(testExpression, currentExpression);
                }
            }

            var testStatement = Expression.GreaterThanOrEqual(Expression.Property(_pathParameter, _lengthProperty),
                Expression.Constant(currentStringIndex + testLength));

            if (currentExpression == null)
            {
                return testStatement;
            }

            return Expression.AndAlso(testStatement, currentExpression);
        }

        private Expression GenerateCharacterComparisonStatement(int index, char compare)
        {
            var lower = char.ToLowerInvariant(compare);
            var upper = char.ToUpperInvariant(compare);

            if (lower == upper)
            {
                return Expression.Equal(Expression.Property(_pathParameter, _charsProperty, Expression.Constant(index)), Expression.Constant(compare));
            }

            var lowerCompare = Expression.Equal(Expression.Property(_pathParameter, _charsProperty, Expression.Constant(index)), Expression.Constant(lower));
            var upperCompare = Expression.Equal(Expression.Property(_pathParameter, _charsProperty, Expression.Constant(index)), Expression.Constant(upper));

            return Expression.OrElse(lowerCompare, upperCompare);
        }

        private Expression GenerateIfBranchMethod(List<KeyValuePair<string, IEndPointHandler>> pathList, int currentStringIndex,
            int pathListStart, int pathListEnd, int level, int distinctCharacters)
        {
            var startingPath = pathList[pathListStart];

            IEndPointHandler endPointHandler = null;

            if (startingPath.Key.Length == currentStringIndex)
            {
                endPointHandler = startingPath.Value;
                pathListStart++;
            }

            var currentChar = char.ToLowerInvariant(pathList[pathListStart].Key[currentStringIndex]);
            var currentStart = pathListStart;

            Expression currentExpression = Expression.Constant(endPointHandler, typeof(IEndPointHandler));

            for (var i = pathListStart; i < pathListEnd; i++)
            {
                var path = pathList[i].Key;
                var newChar = char.ToLowerInvariant(path[currentStringIndex]);

                if (newChar == currentChar)
                {
                    continue;
                }

                var newExpression = GenerateSearchMethod(pathList, currentStringIndex + 1, currentStart, i, level);

                var comparison = GenerateStringComparisonStatements(pathList[currentStart].Key, currentStringIndex, 1, 1);

                currentExpression = Expression.Condition(comparison, newExpression, currentExpression);

                currentStart = i;
                currentChar = newChar;
            }

            var lastExpression = GenerateSearchMethod(pathList, currentStringIndex + 1, currentStart,
                pathListEnd, level);

            var lastComparison = GenerateStringComparisonStatements(pathList[currentStart].Key, currentStringIndex, 1, 1);

            currentExpression = Expression.Condition(lastComparison, lastExpression, currentExpression);

            return currentExpression;
        }

        private Expression GenerateNodeMethod(List<KeyValuePair<string, IEndPointHandler>> pathList, int currentStringIndex,
            int pathListStart, int pathListEnd)
        {
            Expression currentExpression = Expression.Constant(null, typeof(IEndPointHandler));

            var exactMatch = false;

            for (var i = pathListStart; i < pathListEnd; i++)
            {
                var path = pathList[i].Key;
                var value = pathList[i].Value;

                BinaryExpression comparison = null;

                if (path.Length - currentStringIndex == 0)
                {
                    exactMatch = true;

                    if (value.SupportsLongerPaths)
                    {
                        comparison = Expression.GreaterThanOrEqual(Expression.Property(_pathParameter, _lengthProperty),
                            Expression.Constant(path.Length));
                    }
                    else
                    {
                        comparison = Expression.Equal(Expression.Property(_pathParameter, _lengthProperty),
                            Expression.Constant(path.Length));
                    }
                }
                else
                {
                    var length = path.Length - currentStringIndex;
                    var testLength = length;

                    if (exactMatch)
                    {
                        //testLength++;
                    }
                    else
                    {
                        // this is to handle the case where the path ends with a / and it should still match
                        if (path.EndsWith("/"))
                        {
                            length--;
                        }

                        testLength = length;
                    }

                    comparison = GenerateStringComparisonStatements(path, currentStringIndex, length, testLength);
                }

                currentExpression = Expression.Condition(comparison, Expression.Constant(value, typeof(IEndPointHandler)), currentExpression);
            }

            return currentExpression;
        }

        private Expression GenerateSwitch(List<KeyValuePair<string, IEndPointHandler>> pathList, int currentStringIndex, int pathListStart, int pathListEnd)
        {
            var currentChar = char.ToLower(pathList[pathListStart].Key[currentStringIndex]);
            var currentStart = pathListStart;

            var caseList = new List<SwitchCase>();

            for (var i = pathListStart; i < pathListEnd; i++)
            {
                var newValue = char.ToLower(pathList[i].Key[currentStringIndex]);

                if (newValue == currentChar)
                {
                    continue;
                }

                caseList.Add(CreateCaseStatements(pathList, currentChar, currentStringIndex, currentStart, i));

                currentChar = newValue;
                currentStart = i;
            }

            caseList.Add(CreateCaseStatements(pathList, currentChar, currentStringIndex, currentStart, pathListEnd));

            return Expression.Switch(Expression.Property(_pathParameter, _charsProperty, Expression.Constant(currentStringIndex)), Expression.Constant(null, typeof(IEndPointHandler)), caseList.ToArray());
        }

        private SwitchCase CreateCaseStatements(List<KeyValuePair<string, IEndPointHandler>> pathList, char currentChar,
            int currentStringIndex, int start, int end)
        {
            var expression = GenerateSearchMethod(pathList, currentStringIndex + 1, start, end);

            var compiledDelegate = GenerateDelegate(expression);
            var target = compiledDelegate.Target;

            var callExpression = Expression.Invoke(Expression.Constant(compiledDelegate), _pathParameter);

            var lowerCase = char.ToLowerInvariant(currentChar);
            var upperCase = char.ToUpperInvariant(currentChar);

            if (lowerCase == upperCase)
            {
                return Expression.SwitchCase(callExpression, Expression.Constant(currentChar));
            }
            else
            {
                return Expression.SwitchCase(callExpression, Expression.Constant(upperCase), Expression.Constant(lowerCase));
            }
        }

        private int PathMatchCount(List<KeyValuePair<string, IEndPointHandler>> pathList, int currentStringIndex, int pathListStart,
            int pathListEnd)
        {
            var count = 0;

            while (true)
            {
                var matches = true;
                var currentCheckString = pathList[pathListStart].Key;

                if (currentStringIndex >= currentCheckString.Length)
                {
                    break;
                }

                var currentChar = char.ToLowerInvariant(currentCheckString[currentStringIndex]);

                for (var i = pathListStart; i < pathListEnd; i++)
                {
                    currentCheckString = pathList[i].Key;

                    if (currentCheckString.Length < currentStringIndex ||
                        char.ToLowerInvariant(currentCheckString[currentStringIndex]) != currentChar)
                    {
                        matches = false;
                        break;
                    }
                }

                if (matches)
                {
                    count++;
                    currentStringIndex++;
                }
                else
                {
                    break;
                }
            }

            return count;
        }

        private int DistinctCharacters(List<KeyValuePair<string, IEndPointHandler>> pathList, int currentStringIndex,
            int pathListStart,
            int pathListEnd)
        {
            if (currentStringIndex >= pathList[pathListStart].Key.Length)
            {
                return 0;
            }

            var currentChar = pathList[pathListStart].Key[currentStringIndex];
            var count = 1;

            for (var i = pathListStart; i < pathListEnd; i++)
            {
                if (pathList[i].Key[currentStringIndex] == currentChar)
                {
                    continue;
                }

                currentChar = pathList[i].Key[currentStringIndex];
                count++;
            }

            return count;
        }

        private Func<string, IEndPointHandler> GenerateDelegate(Expression expression)
        {
            return Expression.Lambda<Func<string, IEndPointHandler>>(expression, _pathParameter).Compile();
        }
    }
}


text:
use strict;
use warnings;

unlink("parser.c");
unlink("parser_defs.h");

chdir "..\\..\\tools\\gnu_bison\\bin" or die "chdir failed: $!";
system "bison.exe -v --output=parser.c --defines d:\\prog\\compilers2\\frontend_cc\\scripts\\parser.y >bison.output";
chdir "d:\\prog\\compilers2\\frontend_cc\\scripts" or die "chdir failed: $!";

rename("..\\..\\tools\\gnu_bison\\bin\\parser.h", 		"..\\src\\headers\\parser_codes.h") or die "error: $!";
rename("..\\..\\tools\\gnu_bison\\bin\\parser.c", 		"..\\src\\src\\parser.c") or die "error: $!";
rename("..\\..\\tools\\gnu_bison\\bin\\parser.output", 	".\\parser.output") or die "error: $!";
rename("..\\..\\tools\\gnu_bison\\bin\\bison.output", 	".\\bison.output") or die "error: $!";

system "type bison.output";


text:
/* JS #1 */
if (!this.BOOTGETJSTEST) {
    this.BOOTGETJSTEST = { scriptCounter: 0 };
}
this.BOOTGETJSTEST.js1 = true;
this.BOOTGETJSTEST.currentScript = 1;
this.BOOTGETJSTEST.scriptCounter += 1;
if (this.console) {
    this.console.log("Executed js1.js.");
}