text:
Q: 0Auth2 Stuck on Permission Page Currently having an issue with 0auth2 permissions. It keeps on getting stuck to this page: Stuck101. It doesn't crash, just remains completely dormant.
The debug console shows this:
[Debug] OAuth2: Initialization finished
[Debug] OAuth2: Looking for items in keychain
[Debug] OAuth2: Starting authorization
[Debug] OAuth2: No access token, checking if a refresh token is available
[Debug] OAuth2: Error refreshing token: I don't have a refresh token, not
trying to refresh
[Debug] OAuth2: Opening authorize URL embedded: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?state=7A3CEE60&response_type=code&scope=openid+profile+offline_access+User.Read+Mail.Read+Calendars.Read&redirect_uri=KTracker2%3A%2F%2Foauth2%2Fcallback&client_id=584bb6db-5b71-4d7c-9015-fab8a9dfae4c
2018-05-09 04:49:47.198828+0100 KTracker2[8281:180974] [App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction

My App delegate file houses this code:
//  AppDelegate.swift
//  KTracker2
//
//  Created by CaudyMac  on 07/05/2018.
//  Copyright © 2018 Kallum Caudwell. All rights reserved.
//

import UIKit
 @UIApplicationMain
      class AppDelegate: UIResponder, UIApplicationDelegate {

        var window: UIWindow?

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
        if url.scheme == "KTracker2" {
            let service = OutlookService.shared()
            service.handleOAuthCallback(url: url)
            return true
        }
        else {
            return false
        }
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}

Service Code is here:
//  OutlookService.swift
//  KTracker2
//  Created by CaudyMac  on 09/05/2018.
//  Copyright © 2018 Kallum Caudwell. All rights reserved.

import Foundation
import p2_OAuth2
import SwiftyJSON

      class OutlookService {

        // Configure the OAuth2 framework for Azure
        private static let oauth2Settings = [
            "client_id" : "584bb6db-5b71-4d7c-9015-fab8a9dfae4c",
            "authorize_uri": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
            "token_uri": "https://login.microsoftonline.com/common/oauth2/v2.0/token",
            "scope": "openid profile offline_access User.Read Mail.Read Calendars.Read",
            "redirect_uris": ["KTracker2://oauth2/callback"],
            "verbose": true,
            ] as OAuth2JSON

        private static var sharedService: OutlookService = {
            let service = OutlookService()
            return service
        }()

        private let oauth2: OAuth2CodeGrant

        private init() {
            oauth2 = OAuth2CodeGrant(settings: OutlookService.oauth2Settings)
            oauth2.authConfig.authorizeEmbedded = true
            //oauth2.authConfig.ui.useSafariView = false

            userEmail = ""
        }

        class func shared() -> OutlookService {
            return sharedService
        }

    var isLoggedIn: Bool {
        get {
            return oauth2.hasUnexpiredAccessToken() || oauth2.refreshToken != nil
        }
    }

    func handleOAuthCallback(url: URL) -> Void {
        oauth2.handleRedirectURL(url)
    }

    func login(from: AnyObject, callback: @escaping (String?) -> Void) -> Void {
        oauth2.authorizeEmbedded(from: from) {
            result, error in
            if let unwrappedError = error {
                callback(unwrappedError.description)
            } else {
                if let unwrappedResult = result, let token = unwrappedResult["access_token"] as? String {
                    // Print the access token to debug log
                    NSLog("Access token: \(token)")
                    callback(nil)
                }
            }
        }
    }

    func logout() -> Void {
        oauth2.forgetTokens()
    }

    func makeApiCall(api: String, params: [String: String]? = nil, callback: @escaping (JSON?) -> Void) -> Void {
        // Build the request URL
        var urlBuilder = URLComponents(string: "https://graph.microsoft.com")!
        urlBuilder.path = api

        if let unwrappedParams = params {
            // Add query parameters to URL
            urlBuilder.queryItems = [URLQueryItem]()
            for (paramName, paramValue) in unwrappedParams {
                urlBuilder.queryItems?.append(
                    URLQueryItem(name: paramName, value: paramValue))
            }
        }

        let apiUrl = urlBuilder.url!
        NSLog("Making request to \(apiUrl)")

        var req = oauth2.request(forURL: apiUrl)
        req.addValue("application/json", forHTTPHeaderField: "Accept")

        let loader = OAuth2DataLoader(oauth2: oauth2)

        // Uncomment this line to get verbose request/response info in
        // Xcode output window
        //loader.logger = OAuth2DebugLogger(.trace)

        loader.perform(request: req) {
            response in
            do {
                let dict = try response.responseJSON()
                DispatchQueue.main.async {
                    let result = JSON(dict)
                    callback(result)
                }
            }
            catch let error {
                DispatchQueue.main.async {
                    let result = JSON(error)
                    callback(result)
                }
            }
        }
    }

    private var userEmail: String

    func getUserEmail(callback: @escaping (String?) -> Void) -> Void {
        // If we don't have the user's email, get it from
        // the API
        if (userEmail.isEmpty) {
            makeApiCall(api: "/v1.0/me") {
                result in
                if let unwrappedResult = result {
                    let email = unwrappedResult["mail"].stringValue
                    self.userEmail = email
                    callback(email)
                } else {
                    callback(nil)
                }
            }
        } else {
            callback(userEmail)
        }
    }

    func getInboxMessages(callback: @escaping (JSON?) -> Void) -> Void {
        let apiParams = [
            "$select": "subject,receivedDateTime,from",
            "$orderby": "receivedDateTime DESC",
            "$top": "10"
        ]

        makeApiCall(api: "/v1.0/me/mailfolders/inbox/messages", params: apiParams) {
            result in
            callback(result)
        }
    }

    func getEvents(callback: @escaping (JSON?) -> Void) -> Void {
        let apiParams = [
            "$select": "subject,start,end",
            "$orderby": "start/dateTime ASC",
            "$top": "10"
        ]

        makeApiCall(api: "/v1.0/me/events", params: apiParams) {
            result in
            callback(result)
        }
    }

    func getContacts(callback: @escaping (JSON?) -> Void) -> Void {
        let apiParams = [
            "$select": "givenName,surname,emailAddresses",
            "$orderby": "givenName ASC",
            "$top": "10"
        ]

        makeApiCall(api: "/v1.0/me/contacts", params: apiParams) {
            result in
            callback(result)
        }
    }
}

I also have KTracker2 added in the plist files
Any ideas to why my app lies dormant would be great. Thanks a bunch.


text:
Q: If $a^2+b^2+c^2+d^2=4$ then $(a+2)(b+2)\geq cd$ Let $a,b,c,d$ be real numbers with $a^2+b^2+c^2+d^2=4$. Prove that $(a+2)(b+2)\geq cd$.
My approach: I have considered an expression $$\begin{aligned}(a+2)(b+2)-cd=&4+2(a+b)+(ab-cd)\\=&(a^2+b^2+c^2+d^2)+2a+2b+(ab-cd)\end{aligned}$$ I was trying to write it as the sum of squares but I failed.
Can anyone show how to solve this problem please?

A: Because by AM-GM $$(a+2)(b+2)=ab+2(a+b)+4=$$
$$=\frac{1}{2}(2ab+4a+4b+4+a^2+b^2)+2-\frac{1}{2}(a^2+b^2)=$$
$$=\frac{1}{2}(a+b+2)^2+2-\frac{1}{2}(a^2+b^2)\geq$$
$$\geq2-\frac{1}{2}(a^2+b^2)=\frac{1}{2}(c^2+d^2)\geq |cd|\geq cd.$$

A: Using the AM-GM inequality, we have
$$(a+2)(b+2) = \frac{4-a^2-b^2-c^2-d^2}{2}+\frac{(a+b+2)^2}{2}+\frac{c^2+d^2}{2}$$
$$\geqslant \frac{c^2+d^2}{2} \geqslant cd.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ngrx can't access state properties? I'm following the tutorial on the ngrx website to create a store / state, but I can't access the state properties:
auth.ts
export interface Auth{
    email: string;
    token: string;
    isLoggedIn: boolean;
}

auth.actions.ts
import { createAction, props } from '@ngrx/store';
import {Auth} from '../../models/auth';

export const authenticateUser = createAction('[Login Component] Authtenticate User', props<{payload: Auth}>());
export const logoutUser = createAction('[Navbar Component] Logout User');

auth.reducer.ts
import { Action, createReducer, on } from '@ngrx/store';
import * as AuthActions from '../actions/auth.actions';

export interface State {
  email: string;
  token: string;
  isLoggedIn: boolean;
}

export const initialState: State = {
    email: 'test@test',
    token: '',
    isLoggedIn: false
}

const _authReducer = createReducer(
    initialState,
    on(AuthActions.authenticateUser, (state, { payload }) => ({
        email: payload.email,
        token: payload.token,
        isLoggedIn: payload.isLoggedIn,
    })),
    on(AuthActions.logoutUser, state => ({
        email: '',
        token: '',
        isLoggedIn: false,
    }))
)

export function authReducer(state: State | undefined, action: Action) {
    return _authReducer(state, action);
  }

In my app.module.ts i'm importing
...
import { StoreModule } from '@ngrx/store';
import {authReducer} from './store/reducers/auth.reducer';

imports: [
    ...
    StoreModule.forRoot({ auth: authReducer }),
  ],

And i have a navbar component where i want to show the user email, but when i try to access {{auth.email}} in html i get an error:
"Identifier 'email' is not defined. 'Observable' does not contain such a memberng".
navbar.component.ts
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { Auth } from './../models/auth';

...

auth: Observable<Auth>;

constructor(private store: Store<{auth :Auth}>) {
    this.auth = store.select('auth');
}


text:
Q: Powershell: Cannot index into a null array error I am writing a script to import a LUN list which contain fields "Volume Name", "LUN UID", "Capacity (GiB)", "Storage Pool Name", "Storage System name", "Storage Tier" and "Host Mappings" in variable $luns.
Then I need to match the "LUN UID" in the $luns variable to another variable $dsnaa created to store the datastore naa.
The idea to get a list of all virtual machines residing on the datastores which match the Storage Volume/ LUN ID in the imported excel file.
Error:
Cannot index into a null array.
At C:\Users\troyh\Documents\WindowsPowerShell\ServerList_from_LUN_List.ps1:18 char:40
+ ... re | where {($_.ExtensionData.Info.Vmfs.Extent[0]).DiskName -like $ds ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

Script:
$luns = Import-Excel ~\Documents\WindowsPowerShell\Imports\LUN_Import.xlsx
$arr1 = @()

foreach($lun in $luns)
 {
   $dsnaa = $lun.'LUN UID'
   $dsnaa = "*$dsnaa*"

   $datastore = Get-Datastore | where {($_.ExtensionData.Info.Vmfs.Extent[0]).DiskName -like $dsnaa}
   $vms = Get-Datastore $datastore.Name | Get-VM

   foreach($vm in $vms)
    {

      $data = New-Object System.Object

      $data | Add-Member -MemberType NoteProperty -Name "Name" -Value $vm.Name
      $data | Add-Member -MemberType NoteProperty -Name "Datastore" -Value $datastore.'Name'
      $data | Add-Member -MemberType NoteProperty -Name "naa" -Value $lun.'LUN UID'
      $data | Add-Member -MemberType NoteProperty -Name "Storage Pool Name" -Value $lun.'Storage Pool Name'
      $data | Add-Member -MemberType NoteProperty -Name "Storage System Name" -Value $luns.'Storage System name'

      $arr1 += $data

   }
}

   $arr1 | Export-Excel ~\Documents\WindowsPowerShell\Exports\ServerList_$(Get-Date -Format 'yyyy-MM-dd_H"H"mm').xlsx –Show

A: This line is the problem:
$datastore = Get-Datastore | where {($_.ExtensionData.Info.Vmfs.Extent[0]).DiskName -like $dsnaa}

You need to remove the index:
$datastore = Get-Datastore | where {($_.ExtensionData.Info.Vmfs.Extent).DiskName -like $dsnaa}

The line above will get all datastores that match the criteria that used your -like operator. If you are only interested in getting the first datastore in the list, then index the datastore variable like so in the next line.
$datastore = Get-Datastore | where {($_.ExtensionData.Info.Vmfs.Extent).DiskName -like $dsnaa}
$vms = Get-Datastore $datastore[0].Name | Get-VM

The Get-VM cmdlet does take an array of datastores if you want to grab everything at once.
I have made a few more edits to try to accomplish what you are trying. The problem here besides the indexing is putting the datastore name into the data object. Here is a rewrite using a lot of your code:
$luns = Import-Excel ~\Documents\WindowsPowerShell\Imports\LUN_Import.xlsx
$arr1 = @()

foreach($lun in $luns)
 {
   $dsnaa = $lun.'LUN UID'
   $dsnaa = "*$dsnaa*"

   $datastore = Get-Datastore | where {($_.ExtensionData.Info.Vmfs.Extent).DiskName -like $dsnaa}
   $VMs = @()
   $datastore | foreach-object {
     $dstore = $_.name
     $VMs += get-VM -datastore $dstore | select @{n="Name";e={$_.name}},@{n="Datastore_Name";e={$dstore}}
   }

   foreach($vm in $vms)
    {

      $data = New-Object System.Object

      $data | Add-Member -MemberType NoteProperty -Name "Name" -Value $vm.Name
      $data | Add-Member -MemberType NoteProperty -Name "Datastore" -Value $vm.'Datastore_Name'
      $data | Add-Member -MemberType NoteProperty -Name "naa" -Value $lun.'LUN UID'
      $data | Add-Member -MemberType NoteProperty -Name "Storage Pool Name" -Value $lun.'Storage Pool Name'
      $data | Add-Member -MemberType NoteProperty -Name "Storage System Name" -Value $luns.'Storage System name'

      $arr1 += $data

   }
}

   $arr1 | Export-Excel ~\Documents\WindowsPowerShell\Exports\ServerList_$(Get-Date -Format 'yyyy-MM-dd_H"H"mm').xlsx –Show


text:
Q: Nullpointer Exception at net.multiplesystem.nosms.displaydata.BindingData.getView package net.multiplesystem.nosms.displaydata;

import java.util.ArrayList;

import net.multiplesystem.nosms.R;

import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class BindingData extends BaseAdapter {
 ArrayList<String> sender;
 ArrayList<String> receiver;

 LayoutInflater inflater;

 public BindingData() {

 }

 public BindingData(Activity act, ArrayList<String> sender, ArrayList<String> receiver) {
  this.sender = sender;
  this.receiver = receiver;

  inflater = (LayoutInflater) act
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 }

 @Override
 public int getCount() {
  return sender.size();
 }

 @Override
 public Object getItem(int position) {
  return null;
 }

 @Override
 public long getItemId(int position) {
  return 0;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  Holder holder;
  if (convertView == null) {
   holder = new Holder();
   convertView = inflater.inflate(R.layout.chatbox_listitems, null);
   holder.txtSender = (TextView) convertView.findViewById(R.id.sender);
   holder.txtReceiver = (TextView) convertView
     .findViewById(R.id.receiver);

  } else {
   holder = (Holder) convertView.getTag();
  }
  holder.txtSender.setText(Html.fromHtml( sender.get(position)));
  holder.txtReceiver.setText(Html.fromHtml(receiver.get(position)));
  return convertView;
 }

 private class Holder {
  TextView txtSender, txtReceiver;
 }
}

here is the logcat
02-06 06:50:46.840: E/AndroidRuntime(23655): FATAL EXCEPTION: main
02-06 06:50:46.840: E/AndroidRuntime(23655): Process: net.multiplesystem.nosms, PID: 23655
02-06 06:50:46.840: E/AndroidRuntime(23655): java.lang.NullPointerException
02-06 06:50:46.840: E/AndroidRuntime(23655):    at net.multiplesystem.nosms.displaydata.BindingData.getView(BindingData.java:62)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.widget.AbsListView.obtainView(AbsListView.java:2240)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.widget.ListView.makeAndAddView(ListView.java:1790)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.widget.ListView.fillDown(ListView.java:691)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.widget.ListView.fillGap(ListView.java:655)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5136)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3236)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.widget.AbsListView.onTouchMove(AbsListView.java:3580)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.widget.AbsListView.onTouchEvent(AbsListView.java:3424)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.View.dispatchTouchEvent(View.java:7690)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2210)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1945)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2066)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1515)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.app.Activity.dispatchTouchEvent(Activity.java:2457)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2014)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.View.dispatchPointerEvent(View.java:7870)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3919)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3808)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3406)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3456)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3425)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3510)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3433)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3567)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3406)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3456)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3425)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3433)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3406)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5520)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5500)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5471)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5594)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:182)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.os.MessageQueue.nativePollOnce(Native Method)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.os.MessageQueue.next(MessageQueue.java:137)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.os.Looper.loop(Looper.java:124)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at android.app.ActivityThread.main(ActivityThread.java:4998)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at java.lang.reflect.Method.invokeNative(Native Method)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at java.lang.reflect.Method.invoke(Method.java:515)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
02-06 06:50:46.840: E/AndroidRuntime(23655):    at dalvik.system.NativeStart.main(Native Method)

Basically i am displaying XML file data into listview.The data fetch from XML file successfully and also displayed in listview. But the application stopped while scrolling the listview data. I have no idea about it. The problem is in getView method of BindingData class. please help me. Thanx in advance.

A: A problem is your implementation here:
 @Override
 public Object getItem(int position) {
  return null;
 }

 @Override
 public long getItemId(int position) {
  return 0;
 }

Change it to return real data:
 @Override
 public Object getItem(int position) {
  return sender.get(position);
 }

 @Override
 public long getItemId(int position) {
  return position;
 }

The rest is answered by laatlo.

A: You forgot to store the holder with setTag(). The holder will be null with recycled views. Add
convertView.setTag(holder);

to the convertView == null branch.
Also make sure your chatbox_listitems layout in fact contains views with ids sender and receiver.
Also, you have two constructors, out of which only the other initializes inflater, sender and receiver. Remove the other to make sure you're not accidentally using it, though that's not the reason for this NPE (it would have occurred earlier).
Generally, NPEs like this are easy to figure out if you single-step the code in debugger.

A: Try replacing
  ArrayList<String> sender;
     ArrayList<String> receiver;

by
 ArrayList<String> sender=  new ArrayList<String>();
     ArrayList<String> receiver=  new ArrayList<String>();


text:
Q: tensorflow cifar-10 evaluation example softmax outputs I want to view the probabilities of each test image, so I modified the code(cifar10_eval.py) like this
def eval_once(saver, summary_writer, logits, labels, top_k_op, summary_op):
...............
      while step < num_iter and not coord.should_stop():
        result1, result2  = sess.run([logits, labels])
        print('Step:', step, 'result',result1, 'Label:', result2)
...............

and I run the python code like this.
# python cifar10_eval.py --batch_size=1 --run_once=True

The screen results are like this
Step: 0 result [[ 0.01539493 -0.00109618 -0.00364288 -0.00898853 -0.00086198  0.00587899  0.00981337 -0.00785329 -0.00282823 -0.00171288]] Label: [4]
Step: 1 result [[ 0.01539471 -0.00109601 -0.00364273 -0.00898863 -0.00086192  0.005879  0.00981339 -0.00785322 -0.00282811 -0.00171296]] Label: [7]
Step: 2 result [[ 0.01539475 -0.00109617 -0.00364274 -0.00898876 -0.00086183  0.00587886  0.00981328 -0.00785333 -0.00282814 -0.00171295]] Label: [8]
Step: 3 result [[ 0.01539472 -0.00109597 -0.00364275 -0.0089886  -0.00086183  0.00587902  0.00981344 -0.00785326 -0.00282817 -0.00171299]] Label: [4]
Step: 4 result [[ 0.01539488 -0.00109631 -0.00364294 -0.00898863 -0.00086199  0.00587896  0.00981327 -0.00785329 -0.00282809 -0.00171307]] Label: [0]
Step: 5 result [[ 0.01539478 -0.00109607 -0.00364292 -0.00898858 -0.00086194  0.00587904  0.00981335 -0.0078533  -0.00282818 -0.00171321]] Label: [4]
Step: 6 result [[ 0.01539493 -0.00109627 -0.00364277 -0.00898873 -0.0008618   0.00587892  0.00981339 -0.00785325 -0.00282807 -0.00171289]] Label: [9]
Step: 7 result [[ 0.01539504 -0.00109619 -0.0036429  -0.00898865 -0.00086194  0.00587894  0.0098133  -0.00785331 -0.00282818 -0.00171294]] Label: [4]
Step: 8 result [[ 0.01539493 -0.00109627 -0.00364286 -0.00898867 -0.00086183  0.00587899  0.00981332 -0.00785329 -0.00282825 -0.00171283]] Label: [8]
Step: 9 result [[ 0.01539495 -0.00109617 -0.00364286 -0.00898852 -0.00086186  0.0058789  0.00981337 -0.00785326 -0.00282827 -0.00171287]] Label: [9]

The Label values seem to be good, but the logits outputs seem to be same values!
Why?
Anyone can tell me the reason?
This is new cifar10_eval.py source code.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from datetime import datetime
import math
import time

import numpy as np
import tensorflow as tf

#from tensorflow.models.image.cifar10 import cifar10
import cifar10

FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('eval_dir', '/tmp/cifar10_eval',
                           """Directory where to write event logs.""")
tf.app.flags.DEFINE_string('eval_data', 'test',
                           """Either 'test' or 'train_eval'.""")
tf.app.flags.DEFINE_string('checkpoint_dir', '/tmp/cifar10_train',
                           """Directory where to read model checkpoints.""")
tf.app.flags.DEFINE_integer('eval_interval_secs', 60 * 5,
                            """How often to run the eval.""")
tf.app.flags.DEFINE_integer('num_examples', 10000,
                            """Number of examples to run.""")
tf.app.flags.DEFINE_boolean('run_once', True,
                         """Whether to run eval only once.""")

def eval_once(saver, summary_writer, logits, labels, top_k_op, summary_op):
  with tf.Session() as sess:
    ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
    if ckpt and ckpt.model_checkpoint_path:
      saver.restore(sess, ckpt.model_checkpoint_path)
      global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
    else:
      print('No checkpoint file found')
      return

    # Start the queue runners.
    coord = tf.train.Coordinator()
    try:
      threads = []
      for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):
        threads.extend(qr.create_threads(sess, coord=coord, daemon=True,
                                         start=True))

      #num_iter = int(math.ceil(FLAGS.num_examples / FLAGS.batch_size))
      #total_sample_count = num_iter * FLAGS.batch_size
      num_iter = FLAGS.num_examples
      total_sample_count =  FLAGS.num_examples
      print (num_iter, FLAGS.batch_size, total_sample_count)
      true_count = 0  # Counts the number of correct predictions.
      step = 0
      time.sleep(1)
      while step < num_iter and not coord.should_stop():
        result1, result2  = sess.run([logits, labels])
        #label = sess.run(labels)
        print('Step:', step, 'result',result1, 'Label:', result2)
        step += 1
      precision = true_count / step

      print('Summary -- Step:', step, 'Accurcy:',true_count * 100.0 / step * 1.0, )
      print('%s: total:%d true:%d precision @ 1 = %.3f' % (datetime.now(), total_sample_count, true_count, precision))

    except Exception as e:  # pylint: disable=broad-except
      coord.request_stop(e)

    coord.request_stop()
    coord.join(threads, stop_grace_period_secs=10)

def evaluate():
  """Eval CIFAR-10 for a number of steps."""
  with tf.Graph().as_default():
    # Get images and labels for CIFAR-10.
    eval_data = FLAGS.eval_data == 'test'
    images, labels = cifar10.inputs(eval_data=eval_data, )

    # Build a Graph that computes the logits predictions from the
    # inference model. logits is softmax
    logits = cifar10.inference(images)

    # Calculate predictions.
    top_k_op = tf.nn.in_top_k(logits, labels, 1)

    # Restore the moving average version of the learned variables for eval.
    variable_averages = tf.train.ExponentialMovingAverage(
        cifar10.MOVING_AVERAGE_DECAY)
    variables_to_restore = variable_averages.variables_to_restore()
    saver = tf.train.Saver(variables_to_restore)

    # Build the summary operation based on the TF collection of Summaries.
    summary_op = tf.merge_all_summaries()

    graph_def = tf.get_default_graph().as_graph_def()
    summary_writer = tf.train.SummaryWriter(FLAGS.eval_dir,
                                            graph_def=graph_def)

    while True:
      eval_once(saver, summary_writer, logits, labels,top_k_op, summary_op)
      if FLAGS.run_once:
        break
      time.sleep(FLAGS.eval_interval_secs)

def main(argv=None):  # pylint: disable=unused-argument
  cifar10.maybe_download_and_extract()
  if tf.gfile.Exists(FLAGS.eval_dir):
    tf.gfile.DeleteRecursively(FLAGS.eval_dir)
  tf.gfile.MakeDirs(FLAGS.eval_dir)
  print('Evaluate Start')
  evaluate()

if __name__ == '__main__':
  tf.app.run()

A: I have trained with 1k steps(accuracy 10% or so).
But after I trained with 100k steps(accuracy 86% or so), the result is very good
.................
Step: 9991 result: [[  1.30259633   0.71064955  -2.6035285   -1.30183697  -4.1291523   -3.00246906   0.30873945  -4.02916574  13.05054665  -0.42556083]] Label: 8
Step: 9992 result: [[-1.05670786 -1.86572766  0.28350741  1.78929067  0.03841069  1.23079467    2.97172165 -1.18722486 -1.17184007 -1.02505279]] Label: 6
Step: 9993 result: [[  1.50454926   2.34122658  -3.45632267  -0.55308843  -4.35214806    -2.28931832  -1.74908364  -4.71527719  11.44062901   1.72015083]] Label: 8
Step: 9994 result: [[ 1.96891284 -2.57139373  0.29864013  1.30923986  1.72708285  0.95571399   -0.49331608  0.49454236 -2.26134181 -1.39561605]] Label: 0
Step: 9995 result: [[-0.65523863  1.58577776  0.13226865  1.43122363 -2.34669352  0.18927786   -2.51019335 -1.70729315 -0.21297894  4.06098557]] Label: 9
Step: 9996 result: [[-2.17944765 -3.22895575  2.29571438  2.63287306  0.46685112  4.42715979   -0.76104468  2.39603662 -3.21783161 -2.8433671 ]] Label: 2
Step: 9997 result: [[  4.26957560e+00   1.95574760e-03   1.91038296e-01  -8.00723195e-01    -2.36319876e+00  -2.12906289e+00  -3.35138845e+00   7.97132492e-01   6.60009801e-01   2.73786736e+00]] Label: 0
Step: 9998 result: [[ 0.42694128 -2.07150149  0.47749567  2.62247086  1.11608386  3.05186462   -0.19805858  0.03386561 -2.87092948 -2.59781456]] Label: 5
Step: 9999 result: [[ 0.23629765 -3.21540785  1.01075113  0.46802399  3.44423246  0.25743011    4.71304989 -1.12128389 -3.07727337 -2.7076664 ]] Label: 6
2016-04-09 00:32:49.861650 Total:10000 True:8631: precision @ 1 = 0.863


text:
Q: PHP adding months and days to the current time() and ovoid weekend days I need to add N months and M days to the current time() in PHP. My current solution is simple, but I was wondering can it be even simpler :)?
$my_time = strtotime("+6 days", strtotime("+1 month", time()));

I am also wondering if there is a chance to avoid weekends (Saturday and Sunday) in the target date?

A: Yes, you can simplify it to:
$my_time = strtotime("+6 days 1 month", time());

Or:
$my_time = strtotime("+6 days 1 month");

See this

A: I would use the DateTime class, because it is much faster than strtotime.
$date = new DateTime();
$date->add(new DateInterval('P1M6D'));
echo $date->format('Y-m-d');

Detailed synthax info for the DateInterval can be found here.

A: Try this following Methods
use strtotime() function add days months years
For Day add
    date('Y-m-d', strtotime("+3 days"));
For month add
date('Y-m-d', strtotime("+3 month"));

year add
date('Y-m-d', strtotime("+3 year"));

For day month year add
date('Y-m-d', strtotime("+1 days 1 month 1 year "));

For subtract day month year
date('Y-m-d', strtotime("-1 days 1 month 1 year "));

just use (+ and -) symbols


text:
Q: Reset font-size:0 doesn't work with 'em' unit I have a parent element that sets the font-size to 0 (zero) and its child that restore the value
.parent {
  font-size: 0;
}

.child {
  font-size: 1em;
  /* font-size: 16px; */
}

Using em it doesn't work. Using px as unit makes the text appear again instead.
Can anybody explain me why?

A: Yes, it's normal. Because em it's a relative meassure. If you think in what are you making, you are making this:
0 * 1 = 0

So if you reset to 0 you'll obtain forever a zero value.
You need to use rem (root em) or px.
.child {
   font-size: 1rem;
}

Rems are from the document


text:
Q: API Access to Tesco personal purchases in store Is there a programmatic (read Pythonic and/or RESTful) way to access Tesco Clubcard personal history and/or through a unique receipt token, for in store purchases?
It doesn't seem so from this thread on Tesco Labs and TESCO API Documentation


text:
Q: FTP server active mode I'd like to connect to the FileZilla ftp server running on Windows 7 host from ftp client on Slackware guest. I can successfully login, pwd cd, etc. When the mode is passive i can ls or get but when in active (passive == off) i got the following result:
150 Opening data channel for directory listing of "/DNS"
425 Can't open data connection for transfer of "/DNS"
ABOR
226 ABOR command successful

Why doesn't the active mode work? What to do to make it works?
I'm running VirtualBox in the NAT network mode with port forwarding enabled.

A: Active and Passive mode communicate differently.
In Passive mode, your computer connects to port 21, then makes a second outbound connection to the server to transfer data.
In Active Mode your computer connects to port 21 on the server, and the server then communicates back from port 20 to your computer.
This all means that passive mode is easier to program, because simple firewalls and NAT gateways tend to allow anything to leave the network, but only related connections to return.   In the case of an active mode connection, the router needs to do connection tracking to associate the 2 connections, and this is failing.   You are almost certainly running into this problem.
In addition to port forwarding you will need to load connection tracking (and probably FTP connection tracking) modules.  This will vary depending on your host OS, but could be nf_conntrack_ftp or nf_nat_ftp under Linux.


text:
Q: ends up getting taken ,why the gerund is being used "getting"?thank you so much Indecision is a decision. Ignorance, when we know we should act, doesn't suddenly stop the world from spinning. It goes on, and the path with the favorable odds ends up getting taken.

A: The passive "it gets taken" means "{an unspecified|absent someone} takes it".

A path gets taken.

To take a path means to choose it or to follow it. But if the path simply "gets taken", there is no chooser or follower involved in the statement. The passive form lacking a "by" phrase eliminates the agent from the choice.
ends up wants as its complement a state or condition, because "ends us" acts like a predicate. The complement of ends up is a subject complement:

It ends up broken.
The marathon runner ends up tired and blistered.

Now let's combine those two ideas: to express the idea of a passively acquired state or condition which is the result of an absent agent or absent actor, we use "being" or "getting" in combination with the past participle:

When played with too roughly, the toy ends up being broken.
When played with too roughly, the toy ends up getting broken.

The -ing form of the verb there expresses the idea that a process is involved in the acquisition of this state.  The toy becomes broken.
Back to your example:
The person who must make a decision is compared to a hiker who is confronted with a fork in the path. If the hiker does not actively decide which path to take, but simply allows current circumstance or mere chance to make that determination for him, the most likely or most probable path "ends up getting taken".
The passive form eliminates the actor from the predicate.


text:
Q: Chrome extensions WebRequest filtering by tabId not working? I'm refactoring an existing chrome extension and I have a call to chrome.webRequest.onBeforeSendHeaders which should be filtered according to the currently selected tab.
I'm using the documentation here and, with regards to the filtering it states:

The webRequest.RequestFilter filter allows limiting the requests for
  which events are triggered in various dimensions:
URLs URL patterns such as *://www.google.com/foo*bar. Types Request
  types such as main_frame (a document that is loaded for a top-level
  frame), sub_frame (a document that is loaded for an embedded frame),
  and image (an image on a web site). See webRequest.RequestFilter. Tab
  ID The identifier for one tab. Window ID The identifier for a window.

From this, it is my understanding that if I define a tabid as part of the listener, I should have all the requests filtered according to the tab ID (therefore, only catching the requests headers coming from that particular tab).
The problem is that this does not happen. When I adopt the tabid:xx filter I keep catching all the requests coming from the various tabs I have opened.
What am I missing?
Here is my sample code from the background script background.html:
var currentTabId = -1;

chrome.tabs.getSelected(null, function(tab){
    currentTabId = tab.id;
    console.log("tab id in getselected "+currentTabId);

});

chrome.webRequest.onBeforeSendHeaders.addListener(
    function(req){

        console.log("-> Request Headers received for "+req.url);

        console.log('onBeforeSendHeaders tab id: '+currentTabId)
        console.log('onBeforeSendHeaders: '+JSON.stringify(req))
    }

, { urls:["http://*/*", "https://*/*"], tabId: currentTabId }, ['requestHeaders','blocking']);

currentTabId is e.g. 1666 while the tabId in the object req is another one, that could come from any of the tabs I have opened and I'm using (it's not filtered out on 1666).

A: Your sample code has wrong execution order; chrome.tabs.getSelected is asynchronous.
var currentTabId = -1;
chrome.tabs.getSelected(null, function(tab){
    currentTabId = tab.id;
    // Here, currentTabId is defined properly
    console.log("tab id in getselected "+currentTabId);
});
// Here, it is still -1

You need to move your addListener call into the getSelected callback:
chrome.tabs.getSelected(null, function(tab){
    currentTabId = tab.id;
    console.log("tab id in getselected "+currentTabId);
    chrome.webRequest.onBeforeSendHeaders.addListener(/*...*/);
});


text:
Q: Alignment div horizontally, stop floating on window resize A very stupid simple question, i know, but.. sorry :)
I have 2 div, one for list on the left and one for details on the right. When i resize window, the div on the right float under the first one, i would like to keep the alignment, even with a scroll bar.
How achieve this?
HTML

      ...table list...

      ...table details...

CSS
#parent div{
   float:left;
   clear:none;
}

A: I think adding display:inline-block to your css will fix this.
EDIT:
Actually, to use this method, you will want to remove the float and give both child elements this display property.
HTML

      ...table list...

      ...table details...

CSS
.my_block {
    display:inline-block;
}

A: Try this:
CSS:
.table{
    display:table
}

.table-cell{
    display:table-cell;
}

HTML:

...table list...

...table details...

This will keep both divs aligned horizontally when you resize the browser.
Or keep it really simple...
CSS:
#parent > div{
    display:inline-block;
}


text:
Q: System.Web.HttpRequest.FillInFormCollection() and System.Web.HttpRequest.GetEntireRawContent() very slow I've been following performance of my website and out of all slow-executing code (>1s), more than 90% is because of System.Web.HttpRequest.GetEntireRawContent() (called by System.Web.HttpRequest.FillInFormCollection())
Is this normal for ASP.NET sites... to sometimes spend more than 10 seconds in FillInFormCollection method (obviously it's called from System.Web.UI.Page.PerformPreInit())?
Or there is a way to fix this problem?
I'm compiling for .NET Framework 3.5.
Page I'm mostly having trouble is Login page, although there is nothing unusual about it - two TextBoxes, Checkbox for RememberLogin and Login button. Request.ContentLength is around 5KB (I've logged Request.Form.ToString() - found nothing unusual). I've performed lots of tracing (were expecting huge POSTs) and debugging but couldn't find any rational reason for FillInFormCollection to take more than 10 seconds (I once had extreme example with 250 seconds). I've even tried slowing down my connection with Fiddler, but couldn't reproduce the problem.
EDIT: Thanks for all the comments guys. I've continued pursuing this issue... if it gets solved at least it'll save other people quite some time ;). Here are answers to some of the questions.

*

*It's plain HTTP (not HTTPS), 0 errors in Log (funny thing is that requests actually get completed ;)

*Site is not being loaded when user hits Login.aspx. Site is actually working pretty good 99% of the time (handles around 40 million HTTP requests per week with AVG CPU utilization below 10%)

*It's definitely application/x-www-form-urlencoded - ASP.NET Forms (runat=server) get submitted that way. The only thing I don't understand is why .NET needs >10 seconds to read POST that's less than 6KB.

*The only rational conclusion I came up with (so far) is -> customers accessing site from really slow connections (remember GPRS?). But I would really like to explore all other options rather than just resort to "it's user connection". And if that was the case - I expect I would be seeing similar thing happening for user on every page.

*Just hoping it's not something like this: IIS 6.0 Server Too Busy HTTP 503 Connection_Dropped DefaultAppPool

*Got referred to this page: Identifying Slow HTTP Attack Vulnerabilities on Web Applications It is possible that this is happening.

A: Here is what I found to be the problem, or should I say cause, of my application showing poor performance on the method: System.Web.HttpRequest.FillInFormCollection()
It seems the System.Web.HttpRequest.FillInFormCollection() starts as soon as it gets the beginning of the data being submitted to the form and completes once the last bit of data has been received.  If my user has a poor connection it can take a long time for this information to be completely submitted. Hence the long times for this method.
I used a bandwidth limiter on my local machine and was able to reproduce consistent results that were in line with the varying speeds I tested at, the slower the connection speed the longer the System.Web.HttpRequest.FillInFormCollection() took to run.
Unless you are getting complaints that your web site is not working you are probably just looking at code run by users with crappy connections.


text:
Q: Adding Dividers I currently have a Storedproc t hat is returning values for me to bind with a gridview in asp.net.  One thing I want to do is combine two fields into one seperated by a / but I cannot seem to get this working.
Here is my stored proc
DECLARE @SQL VARCHAR(MAX);

BEGIN
SET @SQL = N'SELECT SYSTEM AS ''System''
            , ENTN AS ''Entity''
            , MED_CTR AS ''Medical Center''
            , MED_CTR_LEVEL AS ''Medical Center Level''
            , DEPT_ID AS ''Department ID''
    FROM V_ROLLUP_SYSTEM_DESC_REV1
    WHERE (DEPT_ID = '+CONVERT(VARCHAR,@DEPTCODE)+')
        AND SYSTEM IN ('+@SYS+')'
PRINT(@SQL)
EXEC(@SQL)

So I want to combine MED_CTR with MED_CTR_LEVEL seperated by a "/" and labeled as Medical Center/ Level.  I cant seem to combine it thus far since every method I have tried to add a "/" in it has returned me nothing.

A: This should work:
SET @SQL = N'SELECT SYSTEM AS [System]
            , ENTN AS [Entity]
            , (MED_CTR +''/''+ MED_CTR_LEVEL) as [Medical Center/ Level]
            , DEPT_ID AS [Department ID]
    FROM V_ROLLUP_SYSTEM_DESC_REV1
    WHERE (DEPT_ID = '+CONVERT(VARCHAR,@DEPTCODE)+')
        AND SYSTEM IN ('+@SYS+')'

And if you want to make sure the concat of the 2 columns always succeeds, you can do this:
SET @SQL = N'SELECT SYSTEM AS [System]
            , ENTN AS [Entity]
            , ISNULL(MED_CTR,''N/A'') +''/''+ ISNULL(MED_CTR_LEVEL,''N/A'') ) as [Medical Center/ Level]
            , DEPT_ID AS [Department ID]
    FROM V_ROLLUP_SYSTEM_DESC_REV1
    WHERE (DEPT_ID = '+CONVERT(VARCHAR,@DEPTCODE)+')
        AND SYSTEM IN ('+@SYS+')'


text:
Q: jQuery and AngularJS not working together I am using RequireJS and Angular but they are not working together in my set up. Things work fine when jQuery version is 1.7.2. However I wanted to use jQuery 1.8.1 and jQuery UI and angular app even fails to initialize the my main module with this.
Here is the problem:
Case sensitive variables: jQuery and jquery. In jquery 1.8.1 source code, towards the end they have defined window.jQuery. Where as in earlier version 1.7.2 had window.jquery defined.
Since I want to use jQuery UI in my app included the file jquery-ui-1.8.23.custom.min.js. After including it I got the error that "jQuery" is undefined.
So, I decided to upgrade my jQuery version and downloaded the said 1.8.1 version. Towards the end of the jQuery source code I could see that this version defined window.jQuery (correct case as needed by jQuery UI).
I updated my require-jquery JS with latest version from James Burke github project and updated it with jquery 1.8.1.
But including the updated jQuery/RequireJS project, angularjs has stopped working.
I get this error in Chrome console:

If I revert to 1.7.2 angular works. Or if I edit jQuery file to define window.jquery instead of window.jQuery (note the case) it again works. But that means jQuery UI won't.

A: I fixed this solution by removing the line from jQuery source which made $ and jQuery the global variables. This line looks something like window.jQuery = window.$ = jQuery.
If you are also using AngularJS with RequireJS and are facing similar problem, remove these lines.
Furthermore, you will have to use jqueryui-amd in your project. Download the utility from the Github page and it will convert jQuery UI script to AMD modules.
Using the AngularJS feature called 'directives' to extend HTML elements I was able to use jQuery UI components in reusable and sane manner.
I've to say that I've hated and loved AngularJS while working on my project, sometimes even letting everybody on Twitter know that I hate AngularJS. However, after having implemented and finished two projects over the last month I have fairly good idea on when to use it and when not to use it.
Here is one jsFiddle I've created to demonstrate the use of jQuery UI with AngularJS:
http://jsfiddle.net/samunplugged/gMyfE/2/

A: Using jQuery's noConflict method is a more elegant and future proof solution to this problem.
View extensive documentation on http://api.jquery.com/jQuery.noConflict/
UPDATE (example from the link):
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
  // Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.
</script>

A: Easily fixed this after my two days try..
When try
Include the particular Slider Jquery files to the view.html directly. remove jquery from index.html file


text:
Q: HTML div from behind shouldn't be detected but must be in front with CSS position absolute Description
I have a div with a table, which each TD of this table will have an event onClick.
But sometimes, I will need to show some texts in front of this table, eventhough, this text can not mess my table's TDs.
So my problem is, I need to show a text in front of a table, but when I click on this text, it will not affect anything, and the correct clicked TD behind the text should call its event.

What I have done:
I have #div1 and #div2, #div1 is behind, #div2 is the front (both are position:absolute).

So, #div1 is there, but it's invisible, only #div2 is shown.
Eventhough, only #div2 is being shown, I need to show the text from #div1 in front of #div2.
In order to make this, I put a span on #div1 and set span's z-index:1.
This way, #div1 is still not appearing, but its span is.
Everything is OK, but I got a new problem now.
I need to click on #div2 (the front), and get the event on the whole div.
Even if there is a text from #div1, it shouldn't have bussiness there, just be showed.
It's hard to understand just reading, so I made this Fiddle.
Click on the red "Text1 from #div1...", I need it to alert the TD html content!

A: You can try this workaround: http://jsfiddle.net/W9jy5/5/
JavaScript
$(document).ready(function(){
    $("#div2").click(function(){
        clickedOnDiv2();
    });
    $('#span1').click(function (e) {
        var div2 = $('#div2'),
            offset = div2.offset();
        if (e.pageX > offset.left && e.pageX < offset.left + div2.width() &&
            e.pageY > offset.top && e.pageY < offset.top + div2.height()) {
                clickedOnDiv2();
            }
    });

    function clickedOnDiv2() {
        alert('#div2');
    }
})

In this workaround there's a click event listener on the span element. If the user click on Text1 and the click is over #div2 we execute clickOnDiv2.
And here it answer for the question in your comment http://jsfiddle.net/W9jy5/17/.
It's cross-browser.

A: Since the #div1 and #div2 are DOM siblings, you can't "capture" the events of #div1 in #div2. And since the SPAN is a descendant to #div1, but you still want the same handler as you attached to #div2, you need to attach the listener on multiple elements or rearrange the DOM.
One way to solve this is to delegate the click to a parent div instead:
$("#container").on('click', '#div2, #div1 span', function(){
    alert("#div2");
})

Demo: http://jsfiddle.net/Pwkqq/

A: You can have the click "fall-through" the #div1 span1 with some CSS:
#div1 span{
  pointer-events: none;
}

It should work in FF and webkit browsers, but you're out of luck with IE8 and lower.
Working example: http://jsfiddle.net/W9jy5/12/


text:
Q: my Dll size blown out by introducing large switch cases, how can I reduce my Dll size(MSVC C++)? My Dll size is of 2 MB. Now I have a situation where I need to add a switch case with 2500 case arms.. each case invoking a function. So total 2500 different functions are being called through this switch case with 2500 cases in it. (The entire code for 2500 functions is already exist in the DLL of 2MB. Extra code included is only switch cases). Now my issue is that the size of the Dll is increased by 15 MB in the Release build resulting DLL size into 17 MB which is huge as per my requirements. Please suggest me some way where i can maintain my Dll size to the minimum by handling switch cases properly.. any alternative methods..
I am using MSVC 2005, c/c++. I invoked optimization to minimize size(/01), /ltcg, (/OPT:REF), (/OPT:ICF),etc ..all best possible optimization features. (Not using precompiled headers)
Your suggestions are much needed
Thanks in Advance
Anil

A: If all the functions have the same signature, consider populating a map or similar data structure with function pointers with what you're switching on as the lookup key. No human being is going to be able to understand a switch statement with 2500 cases, so I would recommend not having one in your code.

A: Almost certainly you have a lot of duplicated code in your case blocks (via macros / inline functions / STL). Change your case to use a non-inline function with arguments, to reduce each case block to merely "HandleGenericCase(x);". Don't use STL or other template/inlined code in your case blocks.
Without seeing your code, it will be hard to give a good answer in which case "verify the specific cause of bloat" is really the best advice.

A: Even if the switch statement takes 100 bytes per case, that is only 1/4 MB, and it is probably a lot less.
Can you get a map file of the dll? I would do that and just sample it at random a few times to see what kinds of functions are in there. My bet is it's full of stuff you don't really need, often generated by templates.
Also, I bet those 2500 functions contain a lot of gas. If the switch statement is the only way they are called, they could be expanded in-line right in the switch statement, saving a lot of entry/exit code.

A: With The intial trials i came to conclusion that theres nothing much when we try with Function pointers.. i found contiguous switch cases and function pointers are almost same as per my requirement where as maps are blowing my Dll size abit more.   Here the issue is not with the switch cases as i thought but with the code that i have written in the functions that i am calling.. I have used many STLs, some common code.. and still fews things like strings.. that i am looking at which causing code bloat. It may take some time for me to make my code efficient. This Answer is to give an idea for beginners like me and a request for the experienced people to suggest some points where and how code can bloat.(Ofcourse I dont forget google)  Still I am left with many loops and gaps .. I need to find what happens when code generated by the compiler.. its very interesting to know


text:
Q: "Clôture" vs "Fermeture" dans la littérature française What is the difference between the two terms "clôture" and "fermeture" in mathematical contexts? For example, in topology, is it more common (or more proper) to say "la clôture de l'ensemble A" or "la fermeture de l'ensemble A"? What about other contexts?
To frame the question properly, my questions are: is there any difference between the two terms? which one is more frequently used? does the usage depend on the context? and is there any rule of thumb?

A: 1) In a topological space the closure of a subset is almost always called adhérence.
I have never seen clôture in place of adhérence and I might remember having seen fermeture, but that would be in fairly old literature.
2) Algebraic closure is  clôture algébrique, and similarly we have clôture séparable, radicielle, intégrale,....
3) The word fermeture is used for a relative situation:
For example we might say la fermeture algébrique de $\mathbb R$ dans $\mathbb C(X)$est $\mathbb C$, meaning that the set of elements of $\mathbb C(X)$  algebraic over $\mathbb R$ is  $\mathbb C$.
Similarly we may speak of:
la fermeture séparable de $k$ dans $K$, la fermeture intégrale de $A$ dans $B$, etc.


text:
Q: Why Dev-C++ does not run my program I'm learning Cpp programming and I'm using Dev-C++ as compiler. I made this example to see how class & objects works in this programming language but the problem is the compiler does not even running the code! Here's the code:
    #include <iostream>

using namespace std;

class BuckysClass{
    public:
        void coolSaying(){
            cout << "Some Sentences" << endl;
        }
};

int main(){
    BuckysClass buckysObj;
    buckysObj.coolSaying();
    return 0;
}

I have saved the file with .cpp extension and tried to run it by pressing Ctrl+F10.
Please if u know what I'm doing wrong ,let me know I really appreciate that. Thanks in advance...

A: First of all:
F9 - compile the source program
F10 - run the source program
In case if your terminal disappears, you can add getchar() before return 0. This will make the command prompt wait for your input, and thus you will be able to see the results.
PS: Don't use Dev-C++. It hasn't been updated for a long time.

A: You just need to add a getchar() or system("pause") before return 0

A:
Nothing! The command prompt just appears in just 1 second and then
  disappear...

Need to add a system("PAUSE"); (I'm supposing you are under Windows)
Try this:
class BuckysClass{
    public:
        void coolSaying(){
            cout << "Some Sentences" << endl;
        }
};

int main(){
    BuckysClass buckysObj;
    buckysObj.coolSaying();

    system("PAUSE");
    return 0;
}

A: Try to build it first then run it. also you need to add system("pause") before return 0 to pause the screen so you can see the result.
I highly recommand you use either CodeBlocks or Eclipce rather than Dev-C++.


text:
Q: Get elements of tuple from tf.data.Dataset I am building a neural network with two input nodes that are connected to an embedding layer each.
I have created a tf.data.Dataset with a tuple as input for the model.
How can I split the tensors in the tuple to forward the first tensor (scalar) to embedding layer 1 and the second tensor (array) to embedding layer 2 in a custom forward pass?
I provided an example below.
Thanks in advance.
import pandas as pd
import tensorflow as tf

from random import randrange

df = pd.DataFrame(columns=['cust', 'items'])

for i in range(100):

    cust = randrange(100)
    items = [randrange(100), randrange(100), randrange(100), randrange(100), randrange(100)]

    df = df.append({"cust": cust, "items": items}, ignore_index=True)

    i += 1

dataset = tf.data.Dataset.from_tensor_slices((df["cust"], df["items"]))

dataset_batches = dataset.batch(10)

# custom forward pass
def call(self, inputs):
    x = inputs[0]  # This does not work.
    y = inputs[1]  # This does not work.

    x = self.cust(x)  # input layer 1
    y = self.items(y)  # input layer 2

    x = self.emb_cust(x)  # embedding layer 1
    y = self.emb_items(y)  # embedding layer 2

    z = self.pre_calc([x, y])  # lambda layer

    return z

A: For somebody with a similar question:
My solution above is actually correct, so you can extract the elements of the tuple from the current batch and put it forward as a list for the forward pass.
def run_model(self, epochs, dataset_batches):

    for epoch in range(epochs):

            for step, (cust, items) in enumerate(dataset_batches):

                   # execute forward pass
                   y_pred = self([cust, items], training=True)
                   ...


text:
Q: Error : TypeError: can't multiply sequence by non-int of type 'list' For below code i am getting TypeError: can't multiply sequence by non-int of type 'list'
square = lambda x : x*x
nums = [1,2,3,4,5,6,7,8,9,10]
square_nums = []
for x in nums:
    square(nums)
    square_nums.append(x)
print (square_nums)

A: You have wrong code :

square(nums) should be square(x) because you want to square x

and simplify your code into :
square = lambda x : x*x
nums = [1,2,3,4,5,6,7,8,9,10]
square_nums = [square(x) for x in nums]
print (square_nums)

Result:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Note from @wjandrea:
it's bad practice to name a lambda.
Use a def instead: def square(x): return x * x.
Also IMO writing x ** 2 is simpler. (x to the power of 2)
Final result:
def square(x): return x**2
nums = [1,2,3,4,5,6,7,8,9,10]
square_nums = [square(x) for x in nums]
print (square_nums)

A: How about
nums = [1,2,3,4,5,6,7,8,9,10]
square_nums = [x*x for x in nums]
print(square_nums)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

A: If you need to use lambda, it makes more sense to use map instead.  It is just weird to create a lambda but assign a name to it, as lambda is supposed to be an anonymous block of code.
nums = [1, 2, 3]
square_nums = list( map(lambda x: x*x, nums) )
# square_nums contains [1, 4, 9]


text:
Q: Phoenix on Heroku: error R10 Running into an odd error with Phoenix on Heroku, where it doesn't seem to bind to the port properly.
Running into a situation where phoenix is not binding to $PORT. Heroku's log:

2016-03-25T22:22:54.716907+00:00 heroku[web.1]: State changed from crashed to starting
2016-03-25T22:23:03.156662+00:00 heroku[web.1]: Starting process with command mix phoenix.server
2016-03-25T22:23:07.985368+00:00 app[web.1]: [info] Running AppName.Endpoint with Cowboy using http on port 4000
2016-03-25T22:23:10.027386+00:00 app[web.1]: 25 Mar 22:23:10 - info: compiled 5 files into 2 files, copied 3 in 1.5 sec
2016-03-25T22:24:03.442109+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2016-03-25T22:24:03.442109+00:00 heroku[web.1]: Stopping process with SIGKILL
2016-03-25T22:24:04.195291+00:00 heroku[web.1]: Process exited with status 137
2016-03-25T22:24:04.211713+00:00 heroku[web.1]: State changed from starting to crashed

My prod.exs:
config :appname, AppName.Endpoint,
  http: [port: {:system, "PORT"}],
  url: [scheme: "https", host: "AppName.herokuapp.com", port: 443],
  force_ssl: [rewrite_on: [:x_forwarded_proto]],
  cache_static_manifest: "priv/static/manifest.json",
  secret_key_base: System.get_env("SECRET_KEY_BASE")

It looks like it's going to port 4000 instead of whatever port Heroku wants, and I'm not sure why.

A: The fix is twofold:

*

*to use the phoenix buildpack config and export the PORT as well, like so: config_vars_to_export=(DATABASE_URL PORT)

*Avoid changing the MIX_ENV without recompiling the app, as that behavior is unsupported, as explained here.


text:
Q: R Is it possible to use Generalised Additive Models for Location Scale and Shape (GAMLSS) in a multilevel dataset and plot percentiles? Im trying to plot continuous percentiles of a variable against another variable. Ive found the package gamlss which lets me do pretty much that.
data(iris)
(gamlss)
(gamm4)
r1<-gamlss(Sepal.Length~cs(Sepal.Width, 3), sigma.formula=~cs(Sepal.Width, 3), data=iris, family=BCT)

centiles(r1,cent = c(2.5, 5, 10, 50, 90, 95, 97.5),
         pch=1,cex=0.5,col="black",
         main="Centile curves for sepal width",
         iris$Sepal.Width)

However, I have multilevel data, and id like to account for that, since the upper limit in this model primarily represents the group with the highest distribution.
Ive found the package gamm4, which seems to account for multilevel data, however im not sure about the output.
r2 <- gamm4(Sepal.Length~s(Sepal.Width),data=iris,random=~(1|Species), family= "poisson")
plot.gam(r2$gam)

I was wondering if there is a way to add percentile lines, or is that not possible in a multilevel GAMLSS?
Also, it seems the output only gives an association line/curve, is it possible to show absolute values?
Thanks in advance


text:
Q: how I can get some elements of a column with respect of another column? How I can modify the following code:
c1_arr = F.col('col1')
c2_arr = F.split(F.trim('col2'), '\s+')
arr_of_struct = F.transform(
    c1_arr,
    lambda x: F.struct(
        F.size(F.array_intersect(c2_arr, F.split(F.trim(x), '\s+'))).alias('cnt'),
        x.alias('val'),
    )
)
top_val = F.sort_array(arr_of_struct, False)[0]

top_val gives me an element of col1 where it has the most common token with col2's element.
Then I use the following code to get my desired result:
df = df.select(
    '*',
    F.when(((top_val['cnt'] > 0)),top_val['val']).alias('match'))

For example consider the following data:
col1                                                       col2
["come and get", "computer", "come and get more" ]       "come for good"
["summer is hot", "summer is too hot", "hot weather"]       "hot tea"
["summer is hot", "summer is too hot", "hot weather"]       "hot summer"

Desired output:
col1              col2                                                          match
["come and get", "computer", come and get more" ]       "come for good"         "come and get"
["summer is hot", "summer is too hot", "hot weather"]       "hot tea"           "hot weather"
["summer is hot", "summer is too hot", "hot weather"]       "hot summer"       "summer is hot"

Now suppose I have a third column col3. For each element in col2 there is a corresponding element in col3. How I can make a new column with corresponding elements in col3?  For example:
col3
["this is one","useful device" , "sure things"]
["about season" ,"oh yea", "tempters"]
["about season","oh yea","tempters"]

output will be:
  match               match_col3
"come and get"          "this is one"
    "hot weather"       "tempters"
 "summer is hot"         "about season"


text:
Q: Text rotation Flex How to rotate text (s:label)? I've tried using rotationZ but instead of rotating text it rotates each letter with some weird effect... How to change text angle?

A: if effects:
http://www.eonflex.com/flex/4.1/langref/spark/effects/Rotate.html#includeExamplesSummary
if properties:
http://docs.huihoo.com/flex/4/spark/components/Label.html#propertySummary look for rotation
and for samples:
http://flex.gormagon.org/2007/04/12/text-rotation/
http://creative-geeks.com/blog/2009/05/26/rotate-text-using-embedded-fonts/

A: <s:Label rotation="270" text="Your Text"/> reads down to up
<s:Label rotation="90" text="Your Text"/> reads up to down
If you want to align it vertically, wrap it in a VGroup with spacers:
<s:VGroup height="100%">
    <s:Spacer height="50%" />
    <s:Label rotation="270" text="Your Text"/>
    <s:Spacer height="50%" />
</s:VGroup>


text:
Q: Can a black hole be magnetic if the mass used to form it came from magnetic elements? By magnetic, I mean that it would react strongly to the presence of an external magnetic field. The concept of a spinning black hole creating a magnetic field is unrelated to this question.
My guess is no, because:

*

*the extreme forces compressing the atoms destabilizes and destroys their structure to the point that matter inside a black hole cannot even manifest the emergent properties of combining quarks.

*information inside the black hole cannot leave it, so it would be impossible to emit a magnetic field due to the matter inside the black hole, even if the matter magic-physics-ally could stay in the form of the atoms used to create it.

A: Not Sure what you mean by 'react strongly'. As quoted by StephenG, Kerr-Newman black holes have charges beyond angular momentum and interact with other possible external magnetic fields.
The Ernst black hole, or rotating Ernst black hole has a magnetic field in the very structure of the spacetime, and as well as the Reissner-Nordström, Kerr and Kerr-Newman, etc, it is expected all of these have different kinds of fields as background fields via metric tensor. This occurs mathematically (look at the metric tensor) and physically I think the picture should be seen in two fashions, one, the event horizon, once formed has the measurable properties for the external observer associated with the presence of the fields, second, thinking in the black hole as the physical remnant of a star or so-like object, the spacetime if magnetic in the original star spacetime (Ernst-like) will remain so after the star collapse, being again the event horizon responsible for some of the associated properties of this spacetime like the thermodynamics descending from it.

A: First of all your first point, namely that

the extreme forces compressing the atoms destabilizes and destroys their structure to the point that matter inside a black hole cannot even manifest the emergent properties of combining quarks.

is somewhat incorrect. Matter entering black hole would encounter such "extreme forces" only after it crosses horizon, while before that the effects of gravity would not be that extreme. In fact, the larger the black hole, the less severe conditions at the horizon crossing would be. Moreover, there are several variations of general relativity where the matter falling into a black hole would encounter some sort of "Big Bounce" rather than "Big Crunch". But precise fate of the matter under horizon does not, uh, matter because of your second point, which is essentially correct.
Specifically, as the black hole forms in the collapse (or grows by absorbing matter) most of parameters with which we can characterize the system (stationary fields, including magnetic, various types of radiation) disappear as black hole stabilizes, with their sources being absorbed by black hole or radiated away. What parameters are left is given by the no-hair theorem which states that isolated black hole sheds through radiation all those characteristic that radiation can remove. Radiation of spin $s$ field could change the system's multipole moment $l$, but only if $l\ge s$. Since gravitons have spin $s = 2$, moments with $l = 0$ and $l=1$ survive and so the black hole is characterized  by mass ($l=0$ moment) and angular momentum ($l=1$ moment). Electromagnetic field has spin $s=1$, and so a black hole formed from electromagnetically interacting matter can also have electric charge $Q$ ($l=0$ moment of EM field), but not higher moments and so a black hole could not have a magnetic moment. Note, that since stars are to a high degree of precision electrically neutral, charges of real black holes would be rather small.
Another possible $l=0$ electromagnetic moment potentially observable in black holes is the monopole charge from hypothesized magnetic monopoles. While many grand unification theories predict this kind of particle, so far there is no experimental evidence that magnetic monopoles exist. But if they do, black holes can carry magnetic monopole charge.
Finally, even without electric or magnetic charges black holes can still 'react strongly to the presence of an external magnetic field'. If magnetic field lines (from external currents) are threaded through the rotating black hole then an electric potential difference can occur, possibly large enough for production of electron-positron pairs. This would allow extraction of energy from the black hole. This Blandford–Znajek process is most likely the mechanism with which quazars are powered.


text:
Q: How to calculate a percentage on different values from same column with different criteria I'm trying to write a query in SSRS (using SQL) to calculate an income statement percentage of sales for each month (the year is a parameter chosen by the user at runtime).  However, the table I have to use for the data lists all of the years, months, accounts, dollars, etc together and looks like this:

ACCT_YEAR
ACCT_PERIOD
ACCOUNT_ID
CREDIT_AMOUNT

2021
1
4000
20000

2021
2
4000
25000

2021
1
5000
5000

2021
2
5000
7500

2021
1
6000
4000

2021
2
6000
8000

etc, etc  (ACCOUNT_ID =4000 happens to be the sales account)
As an example,
I need to calculate
CREDIT_AMOUNT when ACCT_YEAR = 2021, ACCT_PERIOD=1, and ACCOUNT_ID=5000
/
CREDIT_AMOUNT when ACCT_YEAR = 2021, ACCT_PERIOD=1, and ACCOUNT_ID=4000

* 100

I would then do that for each ACCT_PERIOD in the ACCT_YEAR.
Hope that makes sense...What I want would look like this:

ACCT_YEAR
ACCT_PERIOD
ACCOUNT_ID
PERCENTAGE

2021
1
5000
0.25

2021
2
5000
0.30

2021
1
6000
0.20

2021
2
6000
0.32

I'm trying to create a graph that shows the percentage of sales of roughly 10 different accounts (I know their specific account_ID's and will filter by those ID's) and use the line chart  widget to show the trends by month.
I've tried CASE scenarios, OVER scenarios, and nested subqueries.  I feel like this should be simple but I'm being hardheaded and not seeing the obvious solution.
Any suggestions?
Thank you!

A: You just to use a matrix with a parent column group for ACCT_YEAR and a child column group for ACCT_PERIOD. Then you can use your calculation. If you format the textbox for percentage, you won't need to multiply it by 100.
Textbox value: =IIF(ACCOUNT_ID=4000, Sum(CREDIT_AMOUNT), 0) = 0, 0, IIF(ACCOUNT_ID=5000, Sum(CREDIT_AMOUNT), 0) / IIF(ACCOUNT_ID=4000, Sum(CREDIT_AMOUNT), 0)

A: One important behaviour to note is that window functions are applied after the where clause.
Because you need the window functions to be applied before any where clause (which would filter account 4000 out), they need to be used in one scope, and the where clause in another scope.
WITH
  perc AS
(
  SELECT
    *,
    credit_amount * 100.0
    /
    SUM(
      CASE WHEN account_id = 4000 THEN credit_amount END
    )
    OVER (
      PARTITION BY acct_year, accr_period
    )
      AS credit_percentage
  FROM
    your_table
)
SELECT
  *
FROM
  perc
WHERE
  account_id IN (5000,6000)


text:
Q: How to check whehter rows of a file within the rows of another file I am fresh to Shell or Bash. I have file1 with one column and about 5000 rows and file2 have five columns with 240k rows. How can I check whether the values of the 5000 rows in file1 within or not the second column of file2?
$wc -l file1
$5188
$wc -l file2
$240,888

A: You can do this with awk, something like this:
awk 'NR == FNR {a[$2] = $1; next} {if ($2 in a){print(a[$2], $1)}}' file1 file2

Basically you read the first file in and store its contents in an array "a". Then you read the second file and check if the second field of each line is contained within array "a" and print it if it is.
My answer assumes your fields are separated by white space, if they are not you will have to change the separator. So, if your fields are separated by commas, you will need:
awk -F,       .....

A: The above syntax does work, and it can be further simplified as:
awk 'FNR==NR{a[$1]=$2; next} {print $1, a[$1]}' file2 file1


text:
Q: My C# Assembly or my code? Hello i have this code:
private void button1_Click(object sender, EventArgs e)
    {
        if (radioButton1.Checked)
        {
            UDP.startflood(textBox1.Text, Convert.ToInt32(textBox3.Text), int.Parse(textBox4.Text), int.Parse(textBox2.Text), int.Parse(textBox5.Text));

        }
    }

I get the error "The type or namespace name startflood does not exist in the namespace UDP(Are you missing an assembly reference?)"
Here i part of my UDP.cs:
public Thread[] Sockets;
        public string _Host;
        public int _Delay;
        public int _Sockets;
        public int _Port;
        public int _Timeout;

    public void startflood(string Host, Int32 Delay, int Socketss, int Port, int Timeout)
    {
        _Host = Host;
        _Delay = Delay;
        _Sockets = Socketss;
        _Port = Port;
        _Timeout = Timeout;

        Sockets = new Thread[_Sockets];
        for (int i = 0; i < _Sockets; i++)
        {
            Sockets[i] = new Thread(this.flood);
            Sockets[i].IsBackground = true;
            Sockets[i].Start();
        }

    }
    public void flood()
    {
    i have some code here
    }

Please may someone help me with this? thank you.

A: You're calling startflood as if it were a static method, which it is not.
You'll need to create an instance of your UDP class:
var udp = new UDP();
udp.startflood(textBox1.Text, Convert.ToInt32(textBox3.Text), int.Parse(textBox4.Text), int.Parse(textBox2.Text), int.Parse(textBox5.Text));


text:
Q: react native use Expo to take piciure and save the image to the phone I tried many times to save pictures on the mobile phone after taking pictures through MidiaLibrary, but it kept showing that I could not get permission, so the saving function could not be realized. The version of EXPO I use is SDK44. Could you please help me?
import React, {useState,useEffect} from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Button, Image } from 'react-native';
import {Camera} from 'expo-camera';
import * as MediaLibrary from 'expo-media-library';
import * as ImagePicker from 'expo-image-picker';

export default function App(){
  const [hasCameraPermission, setHasCameraPermission] = useState(null);
  const [hasSavePermission, setHasSavePermission] = useState(null);
  const [camera, setCamera] = useState(null);
  const [status, requestPermission] = MediaLibrary.usePermissions(null);
  const [image,setImage] = useState(null);
  const [type, setType] = useState(Camera.Constants.Type.back);

  useEffect(() => {
    (async () => {
      const  CameraStatus = await Camera.requestCameraPermissionsAsync();
      setHasCameraPermission(CameraStatus.status === 'granted');

      const  SaveStatus = await MediaLibrary.requestPermissionsAsync();
      requestPermission(SaveStatus.status === 'granted');

    })();
  }, []);

  const takePicture = async () => {
    if (camera){
      const options = {quality: 0.5, skipProcessing:true}
      let data = await camera.takePictureAsync(options);
      console.log(data.uri)
      setImage(data.uri);
      console.log("111")
      const {status} = await MediaLibrary.getPermissionsAsync();
      console.log("222")
      if (status === 'granted'){
        const assert = await MediaLibrary.saveToLibraryAsync(data.uri);
        console.log("piciure:",assert)
      }else{
        console.log("miss a permission")
      }
    }

  }


text:
Q: Timeout an HTTTP request properly in angular with a service worker As part of a new feature my team is adding, I was asked that when a specific HTTP Post request fails (When there is slow to no internet available), I will retry the request every X seconds over a total span period of Y seconds. For example, every 1 second in a period of 8 seconds.
This is the code I came out with:
    return this.carService.saveCar(car)
      .pipe(this.isRetryable() ? retryWhen(errors => {
        return errors.pipe(mergeMap(response => {
          if (response.status === TIMEOUT_EXCEPTION_CODE || response.status === UNKNOWN_EXCEPTION_CODE) {
            return of(response).pipe(delay(this.saveCarRetryTimeout)) // X seconds
          }

          return throwError(response);
      }));
    }) : tap(),
    this.isRetryable() ? timeout(this.saveCarProccessTime) : tap(), // Y Seconds
    tap((carId: number) => {
      this.logger.info(saveCarBaseLog.setStatus(LogStatus.COMPLETE));
    }),
    catchError((err) => {
      this.logger.error(saveCarBaseLog).setStatus(LogStatus.FAILED));
      return throwError(err);
    }));

The isRetryable() function just checks if we have both X and Y configurations set, so it won't affect the process.
After doing so and seeing that it works good both local and in the development environment, we uploaded the version. The next day we encountered a problem - In the preprod and prod environments, some cars are saved twice.
After an investigation I made, it looks like this problem comes from the service worker we have - whenever a full timeout occurs, the request itself timeouts, although the FETCH request associated with it is never cancelled, which causes a problem when the internet is just slow (the FETCH request eventually succeeds, and we don't get any indication about it).
I'm really lost on what to do here so any help is welcome!
I can't upload a screenshot of the network since it's a private network,
But in the network section in chrome it looks like this:
POST request - saveCar - XHR - 504 Timeout
POST request - (ServiceWorker) saveCar - FETCH - 504 Timeout
POST request - saveCar - XHR - 504 Timeout
POST request - (ServiceWorker) saveCar - FETCH - 504 Timeout
POST request - saveCar - XHR - 504 Timeout
POST request - (ServiceWorker) saveCar - FETCH - 200 Success (The problematic one)

A: The Problem
After simplifying a bit, here is how I understand the logic you've implemented so far:
class arbitraryClass{

  /* ... arbitrary code ... */

  arbitraryMethod(){
    return this.carService.saveCar(car).pipe(
      this.retryTimeoutLogic(),
      tap({
        complete: () => this.logger.info(saveCarBaseLog.setStatus(LogStatus.COMPLETE)),
        error: err => this.logger.error(saveCarBaseLog.setStatus(LogStatus.FAILED))
      })
    );
  }

  retryTimeoutLogic<T>(): MonoTypeOperatorFunction<T> {
    return s => !this.isRetryable() ? s : s.pipe(
      retryWhen(errors => errors.pipe(
        filter(response => {
          if (response.status !== TIMEOUT_EXCEPTION_CODE ||
              response.status !== UNKNOWN_EXCEPTION_CODE
          ) {
            throw response;
          }
          return true;

        }),
        delay(this.saveCarRetryTimeout) // retry after X seconds
      )),
      timeout(this.saveCarProccessTime) // error after Y Seconds
    );
  }
}

The issue is what happens when timeout(this.saveCarProccessTime) throws an error. It calls unsubscribe on the source then emits an error downstream.
This means that this.carService.saveCar(car) needs an unsubscribe method that can cancel mid-flight or even recently completed requests (due to how async stuff might order itself).
You need to look there.
... or
Another possible solution
Never cancel in-flight requests. The server holds the single source of truth, always assume saveCar may still succeed if you've not been told upstream (by the server), that it has failed.
Just stop retrying after y seconds. You'll get another 504 Timeout and you can throw that to the consumer directly to handle however they decide (presumably the same way they would if this.isRetryable() returned false).
retryTimeoutLogic<T>(): MonoTypeOperatorFunction<T> {
  return s => !this.isRetryable() ? s : defer(() => {

    // The time when we stop retrying on TIMEOUT_EXCEPTION_CODE &
    // UNKNOWN_EXCEPTION_CODE. After this time we rethrow instead
    const timeoutDate = new Date().getMilliseconds() +  this.saveCarProccessTime

    return s.pipe(
      retryWhen(errors => errors.pipe(
        filter(response => {
          if (response.status !== TIMEOUT_EXCEPTION_CODE ||
              response.status !== UNKNOWN_EXCEPTION_CODE ||
              new Date().getMilliseconds() > timeoutDate
          ) {
            throw response;
          }
          return true;
        }),
        delay(this.saveCarRetryTimeout) // retry after X seconds
      ))
    );
  })
}


text: Q: Collector ArcGIS I published a feature service from ArcMap 10.1 to ArcGIS Server 10.7.1 preparing the data for their offline uses. At the ArcGIS portal level, the offline functionality is present and checked. On the web map settings on the portal part of the work area management takes a long time and does not open. On Collector the download button is present but when we define the area of interest for its use in offline mode I receive the following error message: The map '...' failed to download with the message: Parameters cannot be null in ArcGIS Collector.


text:
Q: Debug errors are not detailed enough I am trying to debug an error I receive inside an APEX function.
Even if I use the finest filter on the debug logs, I don't get enough details, and that makes me go to the code, instead of seen the needed object.
The error I get is a NullPointer - that's ok, but I would like to know which field is the error one.

I don't have a problem going to the code, but if I can see the "field" in the call of the function, that's a great time saver.
Part of the corresponding code is:
    .....
    jsGen.writeStringField('PO', getStringValueIfNull(m_opp.PO_Number__c));
    jsGen.writeStringField('SF_oppty_id', m_opp.Id);

    // If the oppty owner is dummy dlr: apacdlr, eurodlr, latamdlr
    // need to set the NS owner as the Bill to Account (accound dealer)
    jsGen.writeNumberField('Owner ID', getNSEmployeeID(m_opp.owner.NS_Employee_Id__c));
    jsGen.writeStringField('Opportunity Name', m_opp.Name );
    jsGen.writeNumberField('Location', getLocationId(m_opp.owner.Sales_Person_Region__c));

    // Get the correct SalesOrder Form to use in NS
    jsGen.writeStringField('Custom Form', getSalesOrderForm(m_opp.owner.NS_Subsidiary__c));

    //Custom Form": " Optitex Sales Order" for Israel and US, "Optitex Sales Order - India Subsidiary" for India
    // Select the correct Sales Order Form
/* * Change to call method
    if (m_opp.owner.NS_Subsidiary__c == 'Parent Company : Consolidated ILS : India Adjustment : Optitex India pvt Ltd')
    {
        jsGen.writeStringField('Custom Form', 'Optitex Sales Order - India Subsidiary');
    } else if (m_opp.owner.NS_Subsidiary__c == 'Parent Company : Consolidated ILS : Optitex USA Inc')
    {
        jsGen.writeStringField('Custom Form', 'Optitex Sales Order - Invoice - USA');
    } else jsGen.writeStringField('Custom Form', 'Optitex Sales Order - No');
*/
 ......

Any ideas ?
BTW: I don't check ALL fields for NULL, since some fields CAN not have a null today, and the data is probably old.

A: I won't argue with you that the logging isn't as helpful as it might be when debugging Apex code. But going to the code is going to be necessary to fix the problem, so personally I don't see that as a big deal.
The stack trace reported when a NullPointerException happens usually contains all the information you need to track down the problem field.
Here is an example (different flavour of NullPointerException):
05:34:59.520 (3520734174)|FATAL_ERROR|System.NullPointerException: Attempt to
de-reference a null object

Class.cve.PaymentCalculator.doCalculate: line 1122, column 1
Class.cve.PaymentCalculator.calculate: line 1095, column 1
Class.cve.PaymentCalculationController.doCalculate: line 1365, column 1
Class.cve.PaymentCalculationController.calculatePayments: line 1245, column 1

where the first line number (and class name) is exactly the line of code the exception occurred in and so generally identifies the field that the problem is with. If it is a piece of code where various values are passed in, where the code is called from (the next line number and class name) is available and so on up the call stack so you can usually figure out the field in that case too.
The bottom line is that the stack trace and its line numbers are hugely helpful in diagnosing problems and it is a pity that problems are often posted on this site without that information.


text:
Q: Somar colunas Vue.js Eu preciso somar as duas colunas quando uma delas for alterada, por exemplo: se avaliação for alterado a maior nota fica em nota final, a mesma coisa para estudos orientados.

var vm = new Vue({
  el: '#vue-instance',
  data: {
    tablenotas: [
       {
          avaliacao: 1,
          estudos_orientados: 2,
          nota_final: 3,
      },
       {
          avaliacao: 4,
          estudos_orientados: 5,
          nota_final: 9,
    }
    ]
  },
  methods: {
  nota: function (avaliacao, estudos_orientados) {
    if (avaliacao >= estudos_orientados) {
      return avaliacao
    }
    else if (estudos_orientados > avaliacao) {
      return estudos_orientados
    }
  }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

    Avaliação
    Estudos Orientados
    Nota Final

        <input type="text" v-model="item.avaliacao">
        <input type="text" v-model="item.estudos_orientados">
        <input type="text">{{nota(item.avaliacao, item.estudos_orientados)}}

Também coloquei no jsfiddle

A: Creio que na sua resposta o problema é que você está utilizando a interpolação, e como está utilizando um <input> dentro da , pode-se utilizar um v-bind:value ou apenas :value para realizar um bind do valor que está sendo retornado do método ao input.
Outro ponto é que modifiquei o método utilizando algo que, não tenho certeza da nomenclatura correta mas creio que o nome é early return, onde você evita trabalhar com else, e sim priorizando o return.
Verifique no exemplo abaixo:
EDIT: Faltou colocar os parseInt na comparação da nota, logo estava ocorrendo problemas em conversão de string para integer.
EDIT#2: Adicionado validações para em casos de apagar todo o campo e o mesmo ficar vazio. Neste caso mostrará no último campo o que estiver preenchido. Se ambos estiverem vazios colocará 0.

var vm = new Vue({
  el: '#vue-instance',
  data: {
    tablenotas: [
       {
          avaliacao: 1,
          estudos_orientados: 2,
          nota_final: 3,
      },
       {
          avaliacao: 4,
          estudos_orientados: 5,
          nota_final: 9,
    }
    ]
  },
  methods: {
    nota (avaliacao, estudos_orientados) {
      if ((avaliacao !== '') && (estudos_orientados !== '')) {

        if (parseInt(avaliacao) > parseInt(estudos_orientados)) {
          return avaliacao
        }

        return estudos_orientados
      }

      if (avaliacao === '') {
        if (estudos_orientados === '') {
          return 0
        }

        return estudos_orientados
      }

      return avaliacao
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

    Avaliação
    Estudos Orientados
    Nota Final

        <input type="text" v-model="item.avaliacao">
        <input type="text" v-model="item.estudos_orientados">
        <input type="text" :value="nota(item.avaliacao, item.estudos_orientados)">

A: Complementando a resposta do guastallaigor, seu código tem um problema, ao editar os campos os valores são convertidos para string, o que acaba fazendo seu código parar de funcionar.
Então recomendo converter para inteiro antes de verificar qual é maior.
avaliacao = parseInt(avaliacao);
estudos_orientados = parseInt(estudos_orientados);

Mas eu faria o seguinte, em vez de passar como parâmetro as propriedades item.avaliacao e item.estudos_orientados eu passaria apenas o índice, para isso tem que modificar o atributo v-for para:
v-for="(item, index) in tablenotas"

e no template o campo:
<input type="text" :value="nota(index)">

o método, ficaria assim:
nota(index) {
  // parseInt converte a string para inteiro
  var avaliacao = parseInt(this.tablenotas[index].avaliacao),
      estudos_orientados = parseInt(this.tablenotas[index].estudos_orientados);
  if (!avaliacao) avaliacao = 0;
  if (!estudos_orientados) estudos_orientados = 0;
  // Abaixo é feita a soma e atribuido a propriedade "nota_final" do
  // índice "index"
  this.tablenotas[index].nota_final = avaliacao + estudos_orientados;
  return (avaliacao >= estudos_orientados) ? avaliacao : estudos_orientados;
}

Veja funcionando:

var vm = new Vue({
  el: '#vue-instance',
  data: {
    tablenotas: [
      {
        avaliacao: 1,
        estudos_orientados: 2,
        nota_final: 3,
      },
      {
        avaliacao: 4,
        estudos_orientados: 5,
        nota_final: 9,
      }
    ]
  },
  methods: {
    nota(index) {
      // parseInt converte a string para inteiro
      var avaliacao = parseInt(this.tablenotas[index].avaliacao),
          estudos_orientados = parseInt(this.tablenotas[index].estudos_orientados);
      if (!avaliacao) avaliacao = 0;
      if (!estudos_orientados) estudos_orientados = 0;
      // Abaixo é feita a soma e atribuido a propriedade "nota_final" do
      // índice "index"
      this.tablenotas[index].nota_final = avaliacao + estudos_orientados;
      return (avaliacao >= estudos_orientados) ? avaliacao : estudos_orientados;
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

      Avaliação
      Estudos Orientados
      Nota Final

        <input type="text" v-model="item.avaliacao">
        <input type="text" v-model="item.estudos_orientados">
        <input type="text" :value="nota(index)">

A: Podes simplificar isso e usar o Math.maxassim:
methods: {
    nota: function() {
        return Math.max(...arguments);
    }
}

dessa maneira não ficas preso a somente 2 valores. Podias ainda fazer uma nova array no computed e adicionar-lhe as notas já calculadas, a melhor solução depende do que procuras fazer com os dados depois.

var vm = new Vue({
  el: '#vue-instance',
  data: {
    tablenotas: [{
        avaliacao: 1,
        estudos_orientados: 2,
        nota_final: 3,
      },
      {
        avaliacao: 4,
        estudos_orientados: 5,
        nota_final: 9,
      }
    ]
  },
  methods: {
    nota: function() {
      return Math.max(...arguments);
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
  color: #ccc;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

      Avaliação
      Estudos Orientados
      Nota Final

        <input type="text" v-model="item.avaliacao">
        <input type="text" v-model="item.estudos_orientados">
        <input type="text" readonly :value="nota(item.avaliacao, item.estudos_orientados)">


text:
Q: Global Modules are not available in VirtualEnv I'm using WinPython to work with libraries such as Scipy. I can not install those inside my virtual environment because blas/lapack is not available. The solution was to use the modules (theano/scipy/numpy) which are already installed on my system inside my virtual environment.
Here is what I tried:
open console (cmd)
python
>>> import numpy

this works, now creating the virtual environment
set VIRTUALENV_PYTHON=C:\WinPython-64bit-3.5.1.1\python-3.5.1.amd64\python.exe
set VIRTUALENV_EXTRA_SEARCH_DIR="C:\WinPython-64bit-3.5.1.1\python-3.5.1.amd64\libs C:\WinPython-64bit-3.5.1.1\python-3.5.1.amd64\Lib C:\WinPython-64bit-3.5.1.1\python-3.5.1.amd64\DLLs C:\WinPython-64bit-3.5.1.1\python-3.5.1.amd64\ C:\WinPython-64bit-3.5.1.1\python-3.5.1.amd64\Scripts"
virtualenv --system-site-packages -v --always-copy venv

or simply:
virtualenv --system-site-packages venv

but no matter what I try I can't import numpy when entering the venv.
venv\Scripts\activate
python
>>> import numpy
ImportError: No module named 'numpy'

Strange. So I compared the sys.path inside the venv:
>>> sys.path
['', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\Scripts', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\DLLs', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\Lib', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\libs', 'C:\\Users\\user\\venv\\Scripts\\python35.zip', 'C:\\Users\\user\\venv\\DLLs', 'C:\\Users\\user\\venv\\lib', 'C:\\Users\\user\\venv\\Scripts', 'C:\\Users\\user\\venv', 'C:\\Users\\user\\venv\\lib\\site-pack
ages']

with the original one (outside):
>>> sys.path
['', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\Scripts', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\DLLs', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\Lib', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\libs', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\python35.zip', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\lib\\site-packages', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\lib\\site-packages\\win32', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\lib\\site-packages\\win32\\lib', 'C:\\WinPython-64bit-3.5.1.1\\python-3.5.1.amd64\\lib\\site-packages\\Pythonwin']

as you can see, not all the entries got copied over. Why is that and how can I fix it?
And yes I read virtualenv --system-site-packages not using system site packages and deleted my PYTHONPATH variable but the issue remains.

A: Figured it out eventually. I did not restart after removing my PYTHONPATH variable. So if you have the same issue:

*

*Delete your PYTHONPATH env. variable.

*Reboot!


text:
Q: From Bitmaps to Video Streaming I'm building a C# application that continuously takes screenshots of the screen. While I'm taking the screenshots, I want to stream them using vlc.
Any ideas of how can I send the bitmaps to vlc for streaming?
tks in advance
Jose

A: You don't want to do that, because the bandwith usage will be huge, vlc can't stream bitmap, and vlc can't decode streams of bitmap.
You can consider several solutions :
Jpeg compressing your snapshot, and do the streaming with VLC. From what I understand, VLC can only stream something it can read, a file or another stream, so you will need to stream your jpeg to VLC before VLC can stream them.
Jpeg compressing your snapshot, and doing the streaming yourself. It might be easier than it sounds. Streaming a continous stream of jpeg via http is a very crude protocol so it is quite easy to implement
Give up  reinventing the wheel and use some vnc program.