Tips and Tricks in a world of Mix

Scoro-Infographic-Productivity-Tips.png

Advertisements
  1. As always for 1 of April Google geeks are comping up with different guffy stuff to make us smile.

 

Today, as you go out to get some Friday beer, navigate through Google Maps.

 

You can see the Pacman button near drive to button.

 

Randomly, Google maps will choose some area on the global map and change the map to Pacman game.

 

Try It!

If you did, please, like this post.

 

Screenshot_2017-03-31-20-57-52Screenshot_2017-03-31-22-05-45

 

 

angular4So, all of us heard about Angular 4, but where do we start.
IN THIS POST IT’S A SHORT LIST OF ACTIONS TO START WORKING WITH ANGULAR 4.

npm install -g @angular/cli

 

ng new projectname
cd projectname
ng -v
Copy paste BY YOUR OPERATING SYSTEM to cmd and run.

We have two main ways to update. If you have an existing project, you should be able to run:

On Linux/Mac: npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@next --save On Windows: npm install @angular/common@next @angular/compiler@next @angular/compiler-cli@next @angular/core@next @angular/forms@next @angular/http@next @angular/platform-browser@next @angular/platform-browser-dynamic@next @angular/platform-server@next @angular/router@next @angular/animations@next --save

Then run whatever ng serve or npm startcommand you normally use, and everything should work.

Please ensure that you are using Typescript v2.1.6 or higher.

If you rely on Animations you’ll also need to install the animations package @angular/animationsand import the new BrowserAnimationsModulefrom @angular/platform-browser/animationsin your root NgModule. Without this, your code will compile and run, but animations won’t activate. Imports from @angular/core were deprecated, use imports from the new package import { trigger, state, style, transition, animate } from '@angular/animations';.
Update typescript
In cmd
npm install typescript@2.2.1 – – save
ng -v
ng serve
________________________
To work with quickstart
 npm install
ng -v  (uses angular 2)
Again paste the lines from the changelog
Then
npm start

 

face4

Many times we need the data of social and marketing networks available offline or at least off the network itself. For better BI and retrospective of the data we can export all the data from the Facebook , but how?

In this post I am going to summarize the easy way to connect your Facebook marketing accounts to get the data from the facebook.

 

  1. Get https://github.com/facebook/facebook-python-ads-sdk.git
  2. The bootstrapping

Meaning we set our facebook account to use with every function we will use against the facebook api – graph facebook.

my_app_id = '<APP_ID>'
my_app_secret = '<APP_SECRET>'
my_access_token = '<ACCESS_TOKEN>'

But how?

Well , I’ve struggled with it quit a bit.

The app_id and app_secret is easy – you just go to the specific app you want to use and copy it from there.

https://developers.facebook.com/apps/

But how to get the token ?

2.a  https://developers.facebook.com/tools/access_token/  shows you the token

2.b  The more complicated and strong way is through the https://developers.facebook.com/tools/explorer/

Choose an app

.face6a1

Login and allow to get data

face6a

Get user access token

face6

If you don’t have enough permissions facebook will inform you what is needed.

{
  “error”: {
    “message”: “(#298) Requires extended permission: read_mailbox”,

 

3.  Go to pycharm. Add config file as config.json.example inside the example folder of  facebook-python-ads-sdk

{
  "app_id": "<YOUR_APP_ID>",
  "app_secret": "<YOUR_APP_SECRET>",
  "act_id": "act_<YOUR_ACCOUNT_ID>",
  "page_id": "<YOUR_PAGE_ID>",
  "access_token": "<ACCESS_TOKEN>"
}

4. Go to https://business.facebook.com/home/

Choose the account / business you want to work with

business_id== page_id

Go to https://www.facebook.com/ads/manager

face7.PNG

You can see an id of account in the dropbox the act_id or press on the account and see the “act=” value.

Pay attention that you need to add “act_” prefix and then copy paste the id itself.

5. Now inside the Pycharm just right click and debug any of the examples..

 

 

P.S.

Changed

AdCampaign to just Campaign in code

from facebookads.objects import (
    AdUser, Campaign,
    #AdCampaign,
)

 

Code example to get campaigns and insights

 

from facebookads import FacebookSession
from facebookads import FacebookAdsApi
from facebookads.adobjects.adsinsights import AdsInsights
import datetime

from facebookads.objects import (
    AdUser, Campaign,
    #AdCampaign,
)

import json
import os
import pprint

pp = pprint.PrettyPrinter(indent=4)
this_dir = os.path.dirname(__file__)
config_filename = os.path.join(this_dir, 'config.json')

config_file = open(config_filename)
config = json.load(config_file)
config_file.close()

### Setup session and api objects
session = FacebookSession(
    #set4u.biz
    config['app_id'],
    config['app_secret'],
    config['access_token'],
)
api = FacebookAdsApi(session)

if __name__ == '__main__':
    FacebookAdsApi.set_default_api(api)

    print('\n\n\n********** Reading objects example. **********\n')

    ### Setup user and read the object from the server
    me = AdUser(fbid='me')

    ### Read user permissions
    print('>>> Reading permissions field of user:')

    pp.pprint(me.remote_read(fields=[AdUser.Field.permissions]))

    ### Get first account connected to the user
    my_account = me.get_ad_account()

    ### Read connections (in this case, the accounts connected to me)

    # Pro tip: Use list(me.get_ad_accounts()) to make a list out of
    # all the elements out of the iterator

    my_accounts_iterator = me.get_ad_accounts()#[0]
    print('>>> Reading accounts associated with user')
    for account in my_accounts_iterator:
        pp.pprint(account)
        for campaign in account.get_campaigns(fields=[Campaign.Field.name]):
            print(">>> Campaign Stats")
            campaignObj = Campaign(campaign._json[u'id'])
            campaignObj.remote_read(fields=[
                Campaign.Field.name,
                Campaign.Field.effective_status,
                Campaign.Field.objective,
            ])
            pp.pprint(campaignObj);

            today = datetime.date.today()
            start_time = str(today - datetime.timedelta(weeks=1))
            end_time = str(today)

            campaign = Campaign(campaign._json[u'id'])
            params = {
                'time_range': {
                    'since': start_time,
                    'until': end_time,
                },
                'fields': [
                    AdsInsights.Field.impressions,
                    AdsInsights.Field.unique_clicks,
                    AdsInsights.Field.reach,
                    AdsInsights.Field.unique_actions
                ],
            }
            insights = campaign.get_insights(params=params)
            print(insights)

 

This slideshow requires JavaScript.

 

 

 

Angular 2 MeshRehovot eYAL vARDI 03.02.2017


https://www.WebComponents.org added to browsers and deleteing the declerative programming

the components will be built in browser

Chrome 58 תומך ב אסמבלי
מגיעים למליון שורות קוד וזה כבד מדיי

Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. Custom components and widgets build on the Web Component standards, will work across modern browsers, and can be used with any JavaScript library or framework that works with HTML.

Web components are based on existing web standards. Features to support web components are currently being added to the HTML and DOM specs, letting web developers easily extend HTML with new elements with encapsulated styling and custom behavior.

 


http://webassembly.org – has a demo of running an extra large code through https://www.WebComponents.org
– we can run it only using the chrome canary version.

http://beta.unity3d.com/jonas/AngryBots/ This is an experimental demo of Angry Bots, a Unity game which has been ported to WebAssembly.

You can see a screen record of the chrome canary browser.

http://webassembly.org can get binary code and even run c++


.net is dead in a long run. That is a tendency which we can see for a long time now.

Even the new items of .net team are directed for using the js as a base.

For instance in a TechSummit at a lecture reviewing new SharePoint the Microsoft representatives were only talking about how to build web-parts with Angular and React. You can read more at my post about that event here – SharePoint with all the new toys. It’s beyond the theme of this post , but it vividly shows the direction of the high-tech industry overall.

The future is in fullstack js – including node.js

Examples are at – paypal, netflix, linkedin – moving to js.


http://universal.angular.io – quick bootstrap option .

Better Perceived Performance

First time users of your application will instantly see a server rendered view which greatly improves perceived performance and the overall user experience. According to research at Google, the difference of just 200 milliseconds in page load performance has an impact on user behavior.

Optimized for Search Engines

Although Googlebot crawls and renders most dynamic sites, many search engines expect plain HTML. Server-side pre-rendering is a reliable, flexible and efficient way to ensure that all search engines can access your content.


ng-metadata – a library from angular1 to angular2

ng-metadata is a great solution for people who want to gradually update an existing ng1 codebase to TypeScript/ES2015 using Angular 2 conventions and styles that runs today on Angular 1.4+.

 

js with typescript – getting the experience of java and .net
java is big data so it will survive more time.
java has ide for free , but has more solutions and frameworks.

.net – updated the syntex each two years but has just .core, webapi and mvc solutions.

Angular4 is released.  You can get it fromgithub https://github.com/angular/angular/tree/4.0.0-rc.2
The changes in Angular4 will be in eco system and not in programming syntax.
It should enable us to upload 1 milion rows code.

Tooks core-js with pollyfills for es5 but added es6.
______________________________________________
Libraries – the ones to use for future
______________________________________________
Core.js

Modular standard library for JavaScript. Includes polyfills for ECMAScript 5, ECMAScript 6: promises, symbols, collections, iterators, typed arrays, ECMAScript 7+ proposals, setImmediate, etc. Some additional features such as dictionaries or extended partial application. You can require only needed features or use it without global namespace pollution.
Rx.js

RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code. This project is a rewrite of Reactive-Extensions/RxJS with better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface.
Zone

A Zone is an execution context that persists across async tasks. You can think of it as thread-local storage for JavaScript VMs.
System
______________________________________________
Framework – you just write a part of code and someone else activates it
______________________________________________
Router Http Compiler Platform
Core&Common
______________________________________________
Application
Custom tag –

Injector – service – business logic
Directive – metadata – for template
Components

MOdule – is container connecting all together

_______________________________________________

Compiler (JIT vs AOT)

JIT 1.1mg of compiler –
SOurce COde –> RUntime: (template +parser+ abstract syntax tree)

at the aot
(template +parser+ abstract syntax tree) is created on the server from before the runtime at the client
so it’s very quick and the outcome is that the comipler itself is smaller 100kb instead of JIT compiler of 1.1MB

________________________________________________

webpack.js – for production
system.src.js – for debug , quicker

shim is a pollifill for older browsers

point of entry System.ipmort async after rendering the dom – setting of the first main.js

platformBrowserDynamic – can be changed for nativescript for android ios , and more options of platforms.
______________________________________________

Why components are also in @NgModule declarations
needed for compiler

the compiler takes the templates and translates it
inside the appmodule in sources in the chrome browser the rendered code is not working on dom but goes through th e self.renderer

______________________________________________

AOT
Offline compile (template +parser+ abstract syntax tree)
A tree shaker walks the dependency graph top to bottom and shakes out unused code.
Minification – removes all unnecessary chars without changing functionality.
______________________________________________

Typescript compiles the code from ts to js.Can define tsconfig.js comiplerOptions:”es5″
For now compiles to es5 for browsers to be compatible. After will just change the es5 to es6. Can see the compatibility of the browsers in a www
The compiler compiles the templates of html to js.
______________________________________________

var p=Injector.resolveAndCReate([A,B,C])
var c1 = p.resolveAndCReateChild([A,B])
var c2 = c1.resolveAndCReateChild([A]) –creates new

Can approach the fathers through the declaration.

Each component has it’s own injector.
Will go up in hierarchy untill gets the needed injected object, if null throws error if not @Optional.

READ MORE!
______________________________________________

First off all write business logic
WOrk with getter
get tasks(){
return this.todoService.tasks;
}
and
not this.tasks = this.todoService.tasks;
______________________________________________
in component code behind

remove(){
this.todos.removeTask(this.task);
}

for deleteing the item

{{task.desc}}

______________________________________________

Don’t use Event Emmitter
Always through a service.
If it’s connected to the parent just inject parents services.
______________________________________________

Lazy initialization
useclass when you give a provide of the type of the class in the constructor
you can add useclass to direct constructor to init lazy load only when needed.

CHeck! READ MORE!
______________________________________________
Template Context

NgModule
bootstrap defining the most upper module
imports is like using in .net — inner use aloud inside the module
exports is what i am aloud to use in outside the module
index.html is not compiled that s why we set only the css , scripts and entry point – its like the manifest for the app.
providers defined in NgModule is recognized by Application Injector, so no need to add it to imports because it’s already available.

if it’s lazy bounding then it’ll be injected to the Module Injector and not Application.

Core Module – only in App module (like HttpModule,BrowserModule)
Add .Core to Module if it’s core module.

Shared Module – is a module for UI , connected to different features.(Unifying controls of Grids,Controlls – almost always third party + some extentions on your part)

Feature Module –

Protection for COre Module

constructor(@Optional() @SkipSelf() parentModule:CoreModule){
if(parentModule) — meaning there are two of them
{ throw new Error(“CoreModule is already loaded’);
}
}

static forRoot(config:UserServiceConfig):ModuleWithProviders{

}

______________________________________________

Model Challenges

NgZone
Data changes if there are
Timer , Communication or UI Events
Wrapps the events and calls tick at the end to refresh
Angular build a tree of expressions per component
Caclulates the previous expressions to the current each async event and the tick slows

Freq*Qexp = Speed

High Frequency Problem
Disconnect from the tick specific component

ngcourse.org/ng-course/demos/change_detection/index.html#/counter

find code
______________________________________________

On Push Strategy

ngcourse.org/ng-course/demos/change_detection/index.html#/ondirty

cd:ChangeDetectorRef

cd.detach in ctor

this.cd.detectChanges in method

rx auditTime(500) – each half second – reduces the events
auditTime.threshold(15) – if the prev and curr the same don’t updated

scan – saves state

creates observable

feed.service.ts start works with worker adding callback for update

enables chaining

______________________________________________

Ways to reduce ticks

Detach one loaded components
On push – only when getting new data will update
On dirty – adding threshold when to refresh

Don’t use setinterval, only setimeout – Zone run outside angular.
______________________________________________

Hooks
Creates
OnInit
AfterContentInit
AfterViewInit

Changes
DoCHeck
..

Closing
OnDestroy

Order of hooks

OnChanges – gets inputs
OnInitDOCHeck
AfterContentInit
AfterContentChecked
AfterViewInit
AfterViewChecked

______________________________________________
Templates

{{}} interpullation expression returns string
[] expression that can return object or array. it’s a property of dom object of the current tag.
() event on dom
*ngIf *ngFor – it’s like words describing the dom
______________________________________________

Component Infrastracture

ElementRef
Renderer — work with jQUery — leave element.nativeELement to able to switch to other clients other than browser

Adding events and binding without them knowing the controls effected.
@HostBinding
@HostListener

______________________________________________

Directive
NgIf uses ViewCOntainerRef – enables acces to dom inner html
bennadel using an item template an html dropdown menu component in angular

using ViewCOntainerRef to inject item for each

Using ContentChild or ContentChildren of type TemplateRef

ngTemplateOutlet
ngOutletContext

Creating data template for dropdown

______________________________________________
angular.io/resources

ui-component
wijmo – webexpress

Taken from http://ift.tt/2kd10Q1

How to use Vagrant on Windows

2015/01/25

"Vagrant logo"

This article shows how to deal with Windows’ specificities while trying to work with Vagrant. If you are not familiar at all with the latter, I suggest you go through this Vagrant tutorial first.

Note: the following was tested on Windows 8, but the steps described below shouldn’t change too much between the different versions.

Vagrant ssh

The first issue I came across was that vagrant ssh doesn’t work out of the box. I was greeted with a constructive message:

`ssh` executable not found in any directories in the %PATH% variable. Is an SSH client installed? Try installing Cygwin, MinGW or Git, all of witch contain an SSH client. Or use your favorite SSH client with the following authentication information shown below:

Host: 127.0.0.1
Port: 2222
Username: vagrant
Private key: C:/path/to/project/.vagrant/machines/default/virtualbox/private_key

Fine. Let’s install Git, then (considering it is not already the case).

Git install

The key is when the “Adjusting your PATH environment” screen pops up:

"Adjusting your PATH environment screen"

You want to select “Use Git and optional Unix tools from the Windows Command Prompt”.

Now I know the message in red looks quite scary, but honestly, unless you are a hardcore user of the Windows console, there is not much to worry about. Basically it will override some of the commands and add a few others.

Personally, it never caused me any trouble.

If you are still a bit worried tho, be reassured: none of this is irreversible. All you would need to do is uninstall Git, or update the PATH variable removing the incriminated part.

More on that in a minute.

Try to vagrant ssh your VM again, this time it should do it (you might need to open a new terminal for the update to take effect, tho).

What if Git is installed already?

Well, it was the case for me as well.

You could always remove it and install it again, but there is another way.

You will have to do manually what the installation of Git could have done for you, but fortunately it is quite trivial:

  • Open the Control Panel
  • Go to System and Security
  • Click on System, then on the Change Settings button
  • Display the Advanced tab and click on Environment Variables…
  • Look for the Path variable in the System variables list, select it then Edit…

At the end of the string, add the path to Git’s bin (something like “C:\Program Files\Git\bin”) (don’t forget to add a semicolon first to separate it from the previous path):

"Edit the PATH variable"

Validate and close the different menus. Try to vagrant ssh your box again, it should work (again, you might need to open a new terminal first).

You probably guessed it already, but if you don’t want Git’s commands to override the Windows ones anymore, all you need to do is to remove that bit.

You will need to find another way for ssh to work though!

Ah, but wait. There is another way.

PuTTY

Remember that error message we initially got trying to ssh the box? Let’s have a look at the second part of it:

Or use your favorite SSH client with the following authentication information shown below:

Host: 127.0.0.1
Port: 2222
Username: vagrant
Private key: C:/path/to/project/.vagrant/machines/default/virtualbox/private_key

I wasn’t joking when I said it was constructive, because it really tells you what to do.

The Windows console works ok but let’s be honest, in the long run it is a real pain to use. It does the trick for a quick vagrant ssh but when the time comes to actually do some work on an Ubuntu server for example, a better shell is desirable.

Enter PuTTY

PuTTY is a very lightweight tool that allows to do a lot of cool stuff. Some of you are probably familiar with it already, and using it jointly with Vagrant is quite nice.

We will use it to ssh our boxes, and rely on the info given by the message above to that purpose.

First, download it if that is not the case already (the first putty.exe link will do).

Download puttygen.exe as well, we are going to need it.

PuTTY and PuTTYGen are stand-alone applications (no need to install them), so just double click on the .exe files.

Let’s open PuTTYGen first: PuTTY uses its own key format, and we need to convert Vagrant’s one first. Click on File then Load private key, select the file indicated by the error message earlier (e.g. “C:/path/to/project/.vagrant/machines/default/virtualbox/private_key”).

Once selected, PuTTY is kind enough to tell us what to do with it:

"PuttyGen"

Ensure SSH-2 RSA is selected, and that the number in Number of bits in a generated key is 2048. Then click on Save private key (don’t set a passphrase) and save it under your own user directory’s .ssh folder, as “vagrant_private_key”. From now on, we will use this key for all the Vagrant boxes.

Close PuTTYGen and open PuTTY. In the Hostname field, type 127.0.0.1. In the Port one, 2222. Ensure SSH is selected and, in the Saved Sessions field, type vagrant and click Save:

"Putty SSH connection configuration 1"

Go to Connection then Data, and in the Auto-login username field, enter “vagrant”:

"Putty SSH connection configuration 2"

Next, still under Connection, go to SSH then Auth. Browse for the key you generated earlier in the Private key file for authentication field. Now head back to the Session menu, save again the “vagrant” one.

Now click on Open: if everything went alright, you should now be in your Vagrant box \(^o^)/

Using multiple Vagrant boxes simultaneously

Now let’s say you already have a box running, and you need to start a second one. You vagrant up it, the Virtual Machine boots and you want to SSH it. But all the boxes cannot use the same SSH port!

It all happens when the box is being booted:

"Windows console"

See the highlighted line? Seeing port 2222 was busy already, Vagrant picked the port 2200 instead.

Now to SSH it using PuTTY, open it, load the “vagrant” session, and in the Port field, replace “2222” with “2200”. Click Open: there you are, connected to the second box.

Known limitations

Shared folders and symlinks

One of the fairly known limitations of using Vagrant on Windows with VirtualBox is that the latter won’t let you create symlinks on the shared folders for security reasons. This quickly becomes problematic when dealing with npm packages, for example.

One of the workarounds is to use the “no bin link” parameter (e.g. npm install --no-bin-link), but this is not always enough.

Fortunately, there is a way to bypass this restriction. In your Vagrantfile, add the following piece of config:

config.vm.provider "virtualbox" do |v|
  v.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/v-root", "1"]
end

As Windows won’t let standard users create symlinks, you now need to start your Vagrant box in administrator mode (open a Windows terminal in admin mode before running vagrant up, for example). Make sure no other box is already running though, as it won’t start if VirtualBox is already running in standard mode.

Maximum path length

Another recurring problem comes from the fact that Windows’ maximum length for a path is 255 characters. Again, this is quickly an issue when dealing with npm packages, especially when they have dependencies, themselves having dependencies, etc.

The solution in that case is to create a symbolic link between the “node_modules” directory and another directory outside of the shared folders.

Which brings us to our practical example.

Practical example: npm packages

So you have this project relying on npm packages. You tried to install them using --no-bin-link but no luck, looks like some of the paths are too long.

Fear not, Macless: update your Vagrant config as shown above to allow the creation of symlinks, boot your VM in admin mode, create a destination directory for your npm packages somewhere outside of the shared folder and create a symlink between it and the “node_modules” one:

mkdir ~/node_modules
ln -s /home/vagrant/node_modules /vagrant/node_modules
cd /vagrant
npm install

Et voilà.

Note: this implies preventing the “node_modules” directory from being versionned.

Conclusion

Here you go, now using Vagrant on Windows in decent conditions.

The process can look a bit convoluted, and really it is. It took me quite a while to put everything together, and if today I am rather satisfied, I am still a bit bugged about the multiple Vagrant boxes part. Having to check the SSH port and update it in the PuTTY session everytime is a bit annoying, even though dealing with several instances at the same time might be an edge case.

Anyways, if you have any suggestions about that, don’t hesitate to leave a comment.

ang1_1.png

 

Working with components allow us to use the life cycle hooks .

Enables separating instantiating and initialization to build a model steps.

Instantiating not interact with services for instance.

 

 

So now we can use the $onInit hook to get the data using the $http service after separating the controller logic to a private function.

ang1_2.png

We divide the logic from the controller and just use the function of fetching the movies by usage of $http.

 

Pay attention –

import the annotation of dependencies to the controller definition of the component using array.

initialize the movies as empty array at the controller.- thus , nullifying the previous values. 

 

Now at the template we can create a relevant table with some actions buttons.

ang1_3.png

Using emmet plugin we are creating the bootstrap pattern for table with buttons using the glyphicons to up vote and down vote the movies.

 

Now we add the logic of up and down voting to the controller.

ang1_4.png

We are setting conditions to be more than 1 and less than 5. Simple logic to be improved if needed.

 

In component we always build an element with isolated scope. It is less dynamic then building the directives but it is a best practice and does answer 95% of scenarios needed for business app.

ang1_5.png

 

If we want to change our rating to component we can create it separately (instead of directive as we would do it in the past).

SO we create the files for it – component and html for it.

We’ll add the glyphicons to show the stars at the html of the component of the ratings

ang1_6.png

We’ll create a transclude content for the stars with astrix , this way if none defined from external source the astrix will be shown.

ang1_7.png

 

and inside the component we will define the transclude as true to enable the injection of the glyphicons into the component.

ang1_9.png

the binding “<” says that we will get the data from external source from outside world.

controllerAs changes the $ctrl to model name using isolated scope.

the transclude = true says that if no data will be entered from outside we will use inner data to init the visuals.

 

ang1_8.png

 

Testing definitions :

 

ang1_10.png

So now we create the karma test using the controller initialization to movieList and use it to initialize the controller getting back the controller from the component

ang1_11.png

Adding the routing

ang1_12.png

Adding ngRoute to the module and creating extra component and adding the routingang1_13.png

 

 

Tag Cloud

%d bloggers like this: