text:
Q: Reachability causes crash after no network situation -- how to properly use Reachability asynchronously I was encountering a very strange crash with my iPhone app in development.  It seemed that every time I'd show my app to a friend it would crash, but it would never crash otherwise.  After being generally mystified by the Murphy's Law aspect, I've determined the pattern of crashes -- the New York City subway.  My app crashes consistently after I use the subway.  I've traced the problem to my use of Reachability.  The app crashes the next time after it is used in a no network situation (not including airplane mode).  I'm following Apple's guidelines and checking for for a connection with Reachability before I do any other network operations, but I've found some conflicting documentation about how to call it.
Currently I'm doing something like this:
-(BOOL)reachable {
    Reachability *r = [Reachability reachabilityWithHostName:@"www.stackoverflow.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    if(internetStatus == NotReachable) {
        return NO;
    }
    return YES;

}
which I'm calling synchronously with a method called from viewDidAppear.
    if ([self reachable]== YES) {
        ... do network stuff ...

which is based on the code from Reachability Guide for iOS 4
My question: is there proper use of Reachability that will take care of this error and handle the absence of a 3G or Wifi network?  Do I need to be spawning another thread or do something to remove a synchronous call?
Here, by the way, is the crash log that I see when my app crashes, which leads me to think that it's a synchronous/asynchronous problem.

Application Specific Information:
(app name) failed to resume in time

Elapsed total CPU time (seconds): 3.280 (user 1.770, system 1.510), 33% CPU
Elapsed application CPU time (seconds): 0.040, 0% CPU

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0:
0   libsystem_kernel.dylib          0x30747fbc kevent + 24
1   libsystem_info.dylib            0x30abec4e _mdns_search + 586
2   libsystem_info.dylib            0x30abfb72 mdns_addrinfo + 370
3   libsystem_info.dylib            0x30abfd68 search_addrinfo + 76
4   libsystem_info.dylib            0x30ac1bcc si_addrinfo + 1080
5   libsystem_info.dylib            0x30abd0b2 getaddrinfo + 78
6   SystemConfiguration             0x311b4256 __SCNetworkReachabilityGetFlags + 962
7   SystemConfiguration             0x311b4f1e SCNetworkReachabilityGetFlags + 98

A: In the synchronous case, you're probably being killed by the iOS Application Watchdog.  That's because to do the reachability check, the SCNetworkReachability functionality needs to do a DNS lookup which can take up to 30 seconds.  If check reachability on the main thread (i.e., in viewDidAppear) you block the main thread for a potentially long time, iOS thinks your app is hung and the application watchdog kills it after 20 seconds.
Apple even warns about this in the Reacahbility sample code:
Apple Reachability Sample Code README
Just use notifications like in the Reachability sample app --- it works well and is pretty straightforward once you grok the NSNotificationCenter design pattern.
Good luck!

A: I solved my problem by setting it up to be asynchronous.  I call a method like this
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSTimer *timer = [NSTimer timerWithTimeInterval:0 target:self selector:@selector(loadData) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[pool release];

and the method called looks something like this
- (void)loadData {
    // check for reachability first before starting data load
    if ([self reachable]== NO) {
        // display error message that there is no internet connection, e.g.
        UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:@"Cannot load data.  There is no internet connection." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Retry",nil];
        [errorAlert show];
        [errorAlert release];
    } else {
        // do something to load data from internet ...
    }

}

using the same reachable code as above.
I would say always use Reachability like this -- the example that Apple gives is incomplete.  I've had this code running on a completed app for a few months and it's been very stable.
EDIT:
This code is no longer stable as of iOS 5 -- it now can sometimes crash due to "active assertions beyond permitted time".  Apple has updated their documentation and example code since I wrote this question, so I suggest following the link in another answer.


text:
Q: RF ground plane and pour question Is it a good practice to make a separate RF ground for a part of the board consisting of the RF module and antenna connector?
The PCB is 4 layer board, with 2 internal planes. The top and bottom layer ground pours around the RF parts are completely separated from the digital ground pour (rest of the board). The GND internal plane is connected to the rest of the plane in a single slot, and that is the only connection between RF ground and digital ground.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use has_secure_password with field_with_errors I am using has_secure_password to verify my user password and its confirmation. The problem I have is that when there are any errors, the fields are not being wrapped with a field_with_errors div. I know that I can add
validates_presence_of :password, :on => :create
validates_presence_of :password_confirmation, :on => :create

but that creates the following error message:

Password digest can't be blank.
  Password can't be blank.
  Password confirmation can't be blank

I would like to either make the has_secure_password wrap the fields with errors with a field_with_errors div or remove the "Password digest can't be blank." error altogether.
Thanks.

A: The SecurePassword module which has this functionality is quite simple and worth a look. Good news is that in the master branch (Rails 4) it does validates_presence_of :password, :on => :create which will solve your problem, but in the meantime you might want to mimic the has_secure_password method on the User model yourself.
class User < ActiveRecord::Base
  attr_reader :password
  attr_accessible :password # ...
  validates_confirmation_of :password
  validates_presence_of :password, on: :create
  include ActiveModel::SecurePassword::InstanceMethodsOnActivation
end

Also make sure bcrypt is loaded in Gemfile.
gem 'bcrypt-ruby', '~> 3.0.0', require: 'bcrypt'

Hope that helps.

A: As @ryanb stated, the validates_presence_of :password is fixed in master, but won't be backported. That fix also clears up the Password digest can't be blank. message.
So, in the model, you still need to add:
validates :password, presence: true, on: :create

As @henrique-zambon stated, there's no need to add a validates_presence_of :password_confirmation. To highlight the password confirmation field, without displaying that additional message, add an error on that field after you've displayed the errors.
Then, to hide the extra Password digest can't be blank. message, you can just remove it in the top of your form.
= form_for @user do |f|
  - if @user.errors.any?
    - @user.errors.delete(:password_digest)
    #error_explanation
      %h2= "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:"
      %ul
        - @user.errors.full_messages.each do |msg|
          %li= msg
    - @user.errors.add(:password_confirmation) if @user.errors.include?(:password)

A: There's no need to validate the presence of :password_confirmation, has_secure_password does that for you.
You may want to check this RailsCast: Authentication in Rails 3.1


text:
Q: Converting LREAL to binary and interpreting it as base 10 LINT Running "CODESYS V3.5 SP16" here, I am trying to implement the hashcode algorithm mentioned in
Best implementation for hashCode method for a collection
and had to built my own solution to replicate Java's Float.floatToIntBits(f) which resulted in the following function
FUNCTION F_lrealToLintBits : LINT
VAR_INPUT
  lrVal : LREAL;
END_VAR
VAR
  arrBytes : ARRAY[0..7] OF BYTE; // LREAL contains 64 bits and each byte contains 8 bits
  pVal     : POINTER TO LREAL := ADR(arrBytes);
  diIndx   : DINT;
  uiExpt   : UINT := 0; // exponent goes from 0 to 63
END_VAR

pVal^ := lrVal; // maps LREAL to array of bytes

// little endian? cause it seems that least significant bit is at lowest address
FOR diIndx := LOWER_BOUND(arrBytes, 1) TO UPPER_BOUND(arrBytes, 1) BY 1 DO
  // bit access seems to be manual only so no loops
  IF arrBytes[diIndx].0 THEN
    F_lrealToLintBits := F_lrealToLintBits + LREAL_TO_LINT(EXPT(2, uiExpt));
  END_IF

  uiExpt := uiExpt + 1; // have to increment exponent after every bit

  IF arrBytes[diIndx].1 THEN
    F_lrealToLintBits := F_lrealToLintBits + LREAL_TO_LINT(EXPT(2, uiExpt));
  END_IF

  uiExpt := uiExpt + 1; // have to increment exponent after every bit

  IF arrBytes[diIndx].2 THEN
    F_lrealToLintBits := F_lrealToLintBits + LREAL_TO_LINT(EXPT(2, uiExpt));
  END_IF

  uiExpt := uiExpt + 1; // have to increment exponent after every bit

  IF arrBytes[diIndx].3 THEN
    F_lrealToLintBits := F_lrealToLintBits + LREAL_TO_LINT(EXPT(2, uiExpt));
  END_IF

  uiExpt := uiExpt + 1; // have to increment exponent after every bit

  IF arrBytes[diIndx].4 THEN
    F_lrealToLintBits := F_lrealToLintBits + LREAL_TO_LINT(EXPT(2, uiExpt));
  END_IF

  uiExpt := uiExpt + 1; // have to increment exponent after every bit

  IF arrBytes[diIndx].5 THEN
    F_lrealToLintBits := F_lrealToLintBits + LREAL_TO_LINT(EXPT(2, uiExpt));
  END_IF

  uiExpt := uiExpt + 1; // have to increment exponent after every bit

  IF arrBytes[diIndx].6 THEN
    F_lrealToLintBits := F_lrealToLintBits + LREAL_TO_LINT(EXPT(2, uiExpt));
  END_IF

  uiExpt := uiExpt + 1; // have to increment exponent after every bit

  IF arrBytes[diIndx].7 THEN
    F_lrealToLintBits := F_lrealToLintBits + LREAL_TO_LINT(EXPT(2, uiExpt));
  END_IF

  uiExpt := uiExpt + 1; // have to increment exponent after every bit
END_FOR

Firstly, I would like to know if there is an existing function in some library that does this already?
I looked in many places including in the OSCAT "Basic, 3.31" library but could not find anything similar (even a set of functions that I could chain together would be OK).
Secondly, can bit access only be done manually?
I would prefer to use a loop but it seems that is not possible? Is there a less copy-and-paste method of accessing the bits that would involve automatically detecting the number of bits if the data type in the array changes from BYTE to something else (e.g. DWORD)?
Potential alternative
Seems like this is where unions come in handy, as mentioned in https://forge.codesys.com/forge/talk/Engineering/thread/02a65a50b2/#e5f4/1911/c524 where if the value does not come from an external source (i.e. no need to check for endian-ness), Float.floatToIntBits(f) would be as simple as
TYPE
  U_lrealToRawLintBits :
  UNION
    lrVal : LREAL;
    liVal : LINT;
  END_UNION
END_TYPE

// supposed to replicate floatToIntBits() in Java at
// https://github.com/openjdk/jdk/blob/739769c8fc4b496f08a92225a12d07414537b6c0/src/java.base/share/classes/java/lang/Float.java#L775
FUNCTION F_lrealToLintBits : LINT
VAR_INPUT
    lrVal : LREAL;
END_VAR
VAR
    uLrealToLintBits : U_lrealToRawLintBits; // for interpreting LREAL as base 10 LINT
END_VAR

IF FPU.IsLRealPosInfinity(lrVal) THEN
  F_lrealToLintBits := 2139095040; // corresponds to 0x7f800000
ELSIF FPU.IsLRealNegInfinity(lrVal) THEN
  F_lrealToLintBits := 4286578688; // corresponds to 0xff800000
ELSIF FPU.IsLRealNaN(lrVal) THEN
  F_lrealToLintBits := 2143289344; // corresponds to 0x7fc00000
ELSE
  uLrealToLintBits.lrVal := lrVal;
  F_lrealToLintBits := uLrealToLintBits.liVal;
END_IF

A: I think what you are trying to achieve is to take as input an LREAL but with the bits inside really being those of a LINT, but byte-swapped.
If so, there should be a more straightforward solution.  Here is an example :
FUNCTION lreal_to_int64 : LINT
VAR_INPUT
  value: LREAL;
  value_is_little_endian: BOOL;
END_VAR
VAR
  no_swap: BOOL;
  source_bytes, target_bytes: POINTER TO BYTE;
  value_as_lint: POINTER TO LINT;
END_VAR

{IF defined (IsLittleEndian)}
  no_swap := value_is_little_endian;
{ELSE}
  no_swap := NOT value_is_little_endian;
{END_IF}

IF
  no_swap
THEN
  value_as_lint := ADR(value);
  lreal_to_int64 := value_as_lint^;
  RETURN;
END_IF

target_bytes := ADR(lreal_to_int64);
source_bytes := ADR(value);
target_bytes[0] := source_bytes[7];
target_bytes[1] := source_bytes[6];
target_bytes[2] := source_bytes[5];
target_bytes[3] := source_bytes[4];
target_bytes[4] := source_bytes[3];
target_bytes[5] := source_bytes[2];
target_bytes[6] := source_bytes[1];
target_bytes[7] := source_bytes[0];

Programmatic access to bits is certainly possible using bitwise operators.  Try something like this.
FUNCTION get_bit : BOOL
VAR_INPUT
  value: LWORD;
  bit_position: USINT;
END_VAR
VAR
 shifted: LWORD;
END_VAR

shifted := SHR(value, bit_position);
get_bit := shifted.0;


text:
Q: How do I make kapt gradle task showing errors in Kotlin code instead of generated Java code? I'm using kapt for hilt and room. Whenever there is an error related to those libraries, kapt show me all errors in the generated Java code. How do I make it to show errors in Kotlin code instead?
This is what it looks like in Android studio.
Just to clarify. It works fine for a valid code. But when there is a mistake (like a missing @Entity annotation on an actual entity class) I want it to point the error in Kotlin code, not in generated Java code.
Here is my project's build.gradle:
plugins {
    id 'com.android.application' version '7.4.1' apply false
    id 'com.android.library' version '7.4.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
    id 'com.google.dagger.hilt.android' version '2.44' apply false
    id 'org.jetbrains.kotlin.kapt' version "1.6.10" apply false
}

And the app's build.gradle:
plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'org.jetbrains.kotlin.kapt'
    id 'com.google.dagger.hilt.android'
}

android {
    namespace 'org.acanthite.upc'
    compileSdk 33

    defaultConfig {
        applicationId "org.acanthite.upc"
        minSdk 22
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
        coreLibraryDesugaringEnabled true
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion '1.1.1'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}
kapt {
    correctErrorTypes = true
}
ext {
    compose_ui_version = '1.3.3'
    room_version = '2.5.0'
    hilt_version = '2.45'
}
dependencies {
    implementation 'androidx.core:core-ktx:1.9.0'
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1'
    implementation 'androidx.activity:activity-compose:1.6.1'
    implementation "androidx.compose.ui:ui:$compose_ui_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_ui_version"
    implementation 'androidx.compose.material:material:1.3.1'
    implementation "androidx.room:room-runtime:$room_version"
    implementation "androidx.room:room-paging:$room_version"
    implementation "androidx.room:room-ktx:$room_version"
    kapt "androidx.room:room-compiler:$room_version"

    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-compiler:$hilt_version"

    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_ui_version"

    debugImplementation "androidx.compose.ui:ui-tooling:$compose_ui_version"
    debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_ui_version"

    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.2'
}

I've tried clearing Android Studio caches, rebuild and sync it a ton of times, lovered rooms version, but still no luck. It's basicaly just a project generated from Compose template. Plus I added room and hilt dependencies that I've added on top of it.

A: Looks like it's just the way KAPT works. Migrating to KSP helped, but I digged tons of google pages to find how to do it properly. The official doc (https://kotlinlang.org/docs/ksp-overview.html) only explains how to use it if you're a library developer. There is nothing there for mere mortals who just want to use KSP plugin for gradle. At least I could not find it there.
Anyway, here is project's build.gradle after migration to KSP (and to Kotlin 1.8.10):
plugins {
    id 'com.android.application' version '7.4.1' apply false
    id 'com.android.library' version '7.4.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.8.10' apply false
    id 'com.google.devtools.ksp' version '1.8.10-1.0.9' apply false
    id 'com.google.dagger.hilt.android' version '2.45' apply false
}

App's build.gradle after migration:
plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'com.google.devtools.ksp'
    id 'kotlin-kapt'
    id 'com.google.dagger.hilt.android'
}

android {
    namespace 'org.acanthite.upc'
    compileSdk 33

    defaultConfig {
        applicationId "org.acanthite.upc"
        minSdk 22
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
        coreLibraryDesugaringEnabled true
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion '1.4.2'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}
kapt {
    correctErrorTypes = true
}
ext {
    compose_ui_version = '1.3.3'
    room_version = '2.5.0'
    hilt_version = '2.45'
}
dependencies {
    implementation 'androidx.core:core-ktx:1.9.0'
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1'
    implementation 'androidx.activity:activity-compose:1.6.1'
    implementation "androidx.compose.ui:ui:$compose_ui_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_ui_version"
    implementation 'androidx.compose.material:material:1.3.1'
    implementation "androidx.room:room-runtime:$room_version"
    implementation "androidx.room:room-paging:$room_version"
    implementation "androidx.room:room-ktx:$room_version"
    ksp "androidx.room:room-compiler:$room_version"

    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-compiler:$hilt_version"

    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_ui_version"

    debugImplementation "androidx.compose.ui:ui-tooling:$compose_ui_version"
    debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_ui_version"

    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.2'
}

Pay attention to these line in project's build.gradle:
id 'org.jetbrains.kotlin.android' version '1.8.10' apply false
id 'com.google.devtools.ksp' version '1.8.10-1.0.9' apply false

You must find matching ksp version here: https://github.com/google/ksp/releases
For example, if your kotlin-android plugin is 1.8.10, then you need to find ksp release that has first part matching 1.8.10 and the second part as high, as possible. In my case it's 1.8.10-1.0.9.
If you're using compose
You also need to pay attention to this one (app's build.gradle):
composeOptions {
    kotlinCompilerExtensionVersion '1.4.2'
}

Go to here https://developer.android.com/jetpack/androidx/releases/compose-kotlin#pre-release_kotlin_compatibility
and find the version that matches your kotlin version. In my case 1.4.2 is for kotlin 1.8.10.
That's how you do it, except...
This does not work for Dagger/Hilt becase they don't have support for KSP yet. Here is the issue: https://github.com/google/dagger/issues/2349
So you're basically stuck with Dagger/Hilt untill they add support for KSP.
Have fun.


text:
Q: Why is my php code bypassing a few if statements? As I was working with my program, I had come up with an unknown error. What happens is that my code is bypassing two if statements. Here's my code:
<?
session_start();
if ($_POST){
  $ao = trim($_POST['amountof']);
  $continue = true;
  if (strlen($ao) < 1){  ####First If-Statement Bypassed####
    $continue = false;
    $_SESSION['error'] = "Please enter in a value!";
  }
  if (strlen($ao) > 20){  ####Second If-Statement Bypassed####
    $continue = false;
    $_SESSION['error'] = "Your value has exceeded 20!";
  }
  if (!is_numeric($ao)){
    $continue = false;
    $_SESSION['error'] = "Value is not numeric!";
  }
}

?>
<form method="post">
<?
if (isset($_SESSION['error'])){
  print "" . $_SESSION['error'] . "
";
}
?>
How many letters are you planning to process?

You may not exceed 20

<input type="text" name="amountof" style="width:25px;" maxlength="2"/>
<input type="submit" value="Continue" />
</form>

<? unset($_SESSION['error']); ?>

The if statements that are bypassed are marked in the code.
Thank you!

A: Try that:
<?php

 session_start();
 $_SESSION['error']='';

  if (isset($_POST['amountof'])){
  $ao = trim($_POST['amountof']);
  $continue = true;
  if (strlen($ao) < 1){
    $continue = false;
    $_SESSION['error'].= "Please enter in a value!
";
  }

  if (!is_numeric($ao)){
    $continue = false;
    $_SESSION['error'].= "Value is not numeric!
";
  }
  elseif ($ao > 20){
    $continue = false;
    $_SESSION['error'].= "Your value has exceeded 20!";
  }
}
?>
<form method="post">
<?php
 if (!empty($_SESSION['error'])){

 //......

or simplified(note that the user may type negative values or 0 what currently will pass the test)
if (!is_numeric($ao) || $ao<1 || $ao>20){
        $continue = false;
        $_SESSION['error']= "Please enter in a numeric value between 1 and 20";
      }

A: Without seeing some sample data, I believe you are simply overwriting the error variable, not bypassing the if statements. Let's run through the code with the case where nothing is entered.
The code inside the first if statement runs, since the strlen($ao) would be less than one. $_SESSION['error'] would be "Please enter in a value!"
Now the code in the second if statement doesn't run, since strlen($ao) is obviously not over 20.
The code in the third if statement runs, since an empty string is not numeric. Since you are overwriting $_SESSION['error'], the variable would simply be "Value is not numeric!". Thus it would appear the first if statement is bypassed.
Try concatenating the error string instead of overwriting.
EDIT: By using the code snippet posted by Dr Molle just before I answered.

A: You need to use
if(isset($_POST)) {

on line two, instead of what you're using, because $_POST behaves like an array.


text:
Q: Adobe Illustrator open a file in browser shortcut Is there a way I can have a shortcut to open a file I'm working on in an internet browser (specifically Chrome) from Adobe Illustrator?

A: OK, here's one way of doing it with AppleScript. Paste the following into the AppleScript Editor and save it as "View SVG in Chrome.scpt" inside the /Applications/Adobe Illustrator/Presets/Scripts folder.
set tmpfile to "/tmp/ai-temp-" & ((random number) as string) & ".svg"
tell application "Adobe Illustrator"
    activate
    save the current document
    set openDoc to file path of current document as alias
    export current document to tmpfile as SVG
end tell
tell application "Google Chrome"
    activate
    open location "file://" & tmpfile
end tell
tell application "Adobe Illustrator"
    close current document
    open openDoc
end tell

Restart Illustrator and the script should appear in the File»Scripts menu.
A few caveats:

*

*This works with Illustrator CS2, which is the most recent version I own. Things may have moved around a bit in later versions, although it should be possible to get this script working without too much trouble. I think scripting is a low priority at Adobe, so I wouldn't be surprised if nothing's changed at all.

*The script saves the current file, exports the image to Chrome, and then reopens the file you were working on. This faffing about is unavoidable because Illustrator's AppleScript API doesn't allow you to save a copy of a file in a different location.

*I'm assuming here that you want to export the file as an SVG image, but other formats are possible; just replace SVG in the above script with one of Flash, GIF, JPEG, Photoshop, PNG24 or PNG8.

*I'm not checking for errors, so unexpected things might happen if, for example, Illustrator doesn't have any files currently open when you run the script.


text:
Q: Manually adding current_page_parent to wp_list_pages() I'm using wp_list_pages() like so:
<?php wp_list_pages('title_li=&include=1714'); ?>
But would like it so that the link has a current_page_parent class under the following conditions:
if (is_singular('work')) {
Is this achievable with this function?

A: By default wp_list_pages() uses the Walker_Page class to create the HTML list, and there's a filter in there—page_css_class—for the CSS classes.
You should be able to do something like this:
/**
 * Filters the CSS classes.
 *
 * @param  array   $css_class    The current CSS classes. Array of strings.
 * @param  WP_Post $page         The current page object.
 * @param  int     $depth        Depth of the page.
 * @param  array   $args         Array of arguments.
 * @param  int     $current_page ID of the current page.
 * @return array                 The filtered array of classes.
 */
function wpse_378686_page_classes( $css_class, $page, $depth, $args, $current_page ) {
    if ( is_singular( 'work' ) && 1703 == $page->ID ) {
        $css_class[] = 'current_page_parent';
    }
    return $css_class;
}
add_filter( 'page_css_class', 'wpse_378686_page_classes', 10, 5 );

Add that code snippet to your active theme's functions.php file, or to a plugin that you would then activate.
Notes

*

*is_singular( 'work' ) should be true on any single work custom post.

*I've changed the code to use $page->ID instead of $current_page, as I think the $page variable contains the page that the page list is currently processing.

(Edited to reflect the comment re: page ID 1714. Edited again after clarification in the comments (and a change to page ID 1703 instead of 1714).)


text:
Q: Show title bar on hover in VB6 How can I show the title bar of a form only if the mouse is at the top of the form like on Windows Media Player 9? I already implemented this but it is awkward and the controls/elements and the window moves down a little if I use my code while WMP 9/10's window stays at the current position.
Private Sub Timer1_Timer()
    Dim pos as coord  'my type, has x as long and y as long
    GetCursorPos pos
    If pos.y * 15 > Me.Top - 500 And pos.y * 15 < Me.Top + 300 And pos.x * 15 > Me.Left And pos.x * 15 < Me.Left + Me.Width Then
        Me.BorderStyle = 2
        Me.Caption = Me.Caption
    Else
        Me.BorderStyle = 0
        Me.Caption = Me.Caption
    End If
End Sub


text:
Q: Basics of 3d to draw Rubik's Cube I'd like to draw a Rubik's Cube on html canvas element with some perspective, but I've never had any experience with 3d graphics, perspective etc. so I'm looking for all helpful resources to achieve this. The only helpful link I've found is for this demo :
http://oos.moxiecode.com/js_canvas/3d_cube/index.html

A: You can certainly create 3-d models with canvas using webGL or 3-d javascript libraries, but I would personally use CSS3 transforms and translations instead if you're wanting to create a rubix cube (I promise, it would be MUCH LESS code).  Check this out and you'll be inspired:
http://www.paulrhayes.com/2009-07/animated-css3-cube-interface-using-3d-transforms/
This demo is using linear rotations, but if you use ease-in-out rotations, the rotations will look much more natural.

A: I wrote this awhile back
http://www.pascarello.com/canvas/rubikscube/
It has issues when you start to mix up colors, but you can play with the code.


text:
Q: Computing Euler angles between two 3D points from Cartesian coordinates We are given the three-dimensional cartesian coordinates of a point $A$, a point $B$ and a point $C$. The distance from $A$ to $B$ is the same as the distance from $A$ to $C$ ($|\vec{AB}| = |\vec{AC}|)$.
The goal is to compute the Euler angle triplet ($\phi$, $\theta$, $\psi$) which rotates the vector $\vec{AB}$ such that it aligns with $\vec{AC}$. These Euler angles describe a rotation around the $z$-axis followed by the $y$-axis and then finally the $x$-axis.
One approach would be to compute a rotation matrix $R$ that encompasses this rotation, and then compute the Euler angles by using $R$. This last step is described here: http://eecs.qmul.ac.uk/~gslabaugh/publications/euler.pdf and here https://web.mit.edu/2.05/www/Handout/HO2.PDF.
Then the question remains: how we do compute this general rotation matrix $R$ by only using the cartesian coordinates of $A$, $B$ and $C$?
If we had the Euler angles, we could compute $R = R_z(\phi)R_y(\theta)R_x(\psi)$.
The question is similar to this one: Reaching a point B in Cartesian coordinate via Euler angles knows its initial point A Euler angles and Cartesian coordinates. However, I do not understand how the answer of the question leads to the general rotation matrix $R$. Instead, it describes how one can compute rotation matrices which map the axis unit vectors $\hat{x}$, $\hat{y}$, $\hat{z}$ onto the normalised vector $\hat{AB}$.
Any help will be greatly appreciated!

A: Project $\vec{AB}$ onto the $x,y$ plane.
Find the angle the projected vector makes with the $x$ axis.
Construct a vector in the $x,y$ plane of the same length as the projected vector,
but whose $y$ component is the same as the $y$ component of $\vec{AC}.$
For example, if the length of the projected vector is $r_1$ and the $y$ component of $\vec{AC}$ is $y_2,$ then a vector of length $r_1$ at angle $\arcsin(y_2/r_1)$ with the $x$ axis will do.
The $z$ rotation angle will be the difference between the angles these two vectors make with the $x$ axis. You will need to pay attention to the signs of angles in order to find a rotation angle of the correct magnitude and direction.
After performing the $z$ rotation on $\vec{AB},$ you will have a vector $v$ with the same $y$ coordinate as $\vec{AC}.$ Project both vectors onto the $x,z$ plane, measure their angles with the $x$ axis, and determine the rotation angle around the $y$ axis that rotates $v$ onto $\vec{AC}.$
You do not need a rotation around the $x$ axis.

A: You can find a nice simple formula for computing the rotation matrix from the two given vectors here.
Then the two references you cited tell you how to obtain Euler angles from any given rotation matrix. But you need to read carefully, because there are numerous different definitions of Euler angles.


text:
Q: Why isn't this pointer dereferenced? I've noticed that when printing a string via a pointer that the pointer should not be dereferenced. Why?
$ cat c.c
#include <stdio.h>

int main(){
    char foo[] = "Meirav";
    char *bar = foo;

    printf("%s\n", foo);
    printf("%s\n", bar); // Why isn't this dereferenced?
    printf("%p\n", bar);

    return 0;
}

$ gcc -Wextra c.c
$ ./a.out
Meirav
Meirav
0x7fffda789ae0

This is the result of dereferencing the pointer, I receive both a compiler warning and a runtime error:

$ vim c.c
$ grep '&bar' c.c
        printf("%s\n", &bar);
$ gcc -Wextra c.c
c.c: In function 'main':
c.c:8:2: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char **' [-Wformat=]
  printf("%s\n", &bar);
  ^
$ ./a.out
Meirav
��~|�
0x7fff7c7eafa0

Why shouldn't the pointer dereferenced?
This is my environment:
$ uname -a
Linux melancholy 3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
$ cat /proc/version
Linux version 3.13.0-48-generic (buildd@orlo) (gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) ) #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015
$ cat /etc/issue
Ubuntu 14.04.2 LTS \n \l

A: I think you have a confusion, the & is the address of operator, so suppose you had this
char  string[] = "Meirav";
char *foo      = string;
char **bar     = &foo;

then you would need to dereference the pointer to a pointer, to get the char pointer that must be passed to printf() when you use the "%s" specifier, like this
printf("%s\n", *bar); /* Why isn't this dereferenced? */
/*             ^ dereference operator                 */

Note that the & operator, creates a pointer with the address of the variable, in this case the variable is a pointer, hence it's the address of the pointer, so you need to dereference the pointer with the * dereference operator, in order to pass it to printf().


text:
Q: access the entire column of a 2D matrix implemented using std::vector Is it possible to get an entire column of a 2D matrix which is implemented as std::vector<std::vector<int32_t>>. We all know we can access an entire row using range for loop like for(const auto& row : matrix). Is there a similar way to access an entire column using range for loop like for(const auto& col : matrix)

A: It is possible using range based for loops, to access the column values, you just have a fixed index:
 for(const auto& row : matrix) {
      cout << row[5] << endl; // 5 is the fixed column index
 }

From knowing that it's possible to write a little helper function which extracts a complete column into another std::vector<>:
 std::vector<int> extract_column(const std::vector<std::vector<int>>& matrix, int col_idx) {
      std::vector<int> result;
      for(const auto& row : matrix) {
          result.push_back(row[col_idx]);
 }

Here's a complete example:
#include <iostream>
#include <vector>

 std::vector<int> extract_column(const std::vector<std::vector<int>>& matrix, int col_idx) {
      std::vector<int> result;
      for(const auto& row : matrix) {
          result.push_back(row[col_idx]);
      }
      return result;
 }

int main() {
    std::vector<std::vector<int>> matrix =
        { { 1, 2, 3 } ,
          { 4, 5, 6 } ,
          { 7, 8, 9 }
        };

    // print the middle row
    for(auto elem : extract_column(matrix,1)) {
        std::cout << elem << std::endl;
    }
}

Output
2
5
8

See the online demo

That said, it should be noted that a std::vector<std::vector<T>> as solution for a matrix representation is suboptimal.
The better fit would be to represent all the matrix elements (for arbitrary dimensions) as a contiguous array, and apply some basic math, to access certain (groups) of matrix elements. The std::vector<std::vector<T>> uses separate allocations for the row elements
To illustrate:
      +-+-+-+
row 1 |1|2|3|
      +-+-+-+
      +-+-+-+    +-+-+-++-+-+-++-+-+-+
row 2 |4|5|6| => |1|2|3||4|5|6||7|8|9|
      +-+-+-+    +-+-+-++-+-+-++-+-+-+
      +-+-+-+
row 3 |7|8|9|     row 1  row 2  row 3
      +-+-+-+

But how to this exactly would lead too far here, and was already answered in other questions at SO, and realized by a number of math frameworks.

A: While I see no way to do this with the actual std::vector, what you could do would be to implement your own class Matrix which stores a 2D vector (or which even inherits from one, which I don't recommend though - especially I'd make sure that my matrix class never contains a jagged array).
If you have done that, you could then create another class Column, which looks somewhat like this:
class Column
{
    private:
        Matrix* target; // << consider rather using smart pointers here
        size_t column_index;
    public:
        int32_t& operator[](size_t index)             { return (*target)[column_index][index]; }
        const int32_t& operator[](size_t index) const { return (*target)[column_index][index];  }
};

So far so good, you now have a column class that accesses some matrix. Simplest approach would now be to also have some method for the size (that again accesses the matrix class) and then do a old fashioned for loop, for(size_t i=0; i<size; i++)...
If you now want a range based loop instead, what you'd have to do is to give Column an inner class Iterator that behaves as iterator and give Column two methods begin() and end() which each return a fitting Iterator.
class Column
{
    ...
    public:
     ...

        size_t size(); // I omit the details here

        class Iterator
        {
            ...
        };

        Iterator begin() { return Iterator(this, 0); }
        Iterator end()   { return Iterator(this, size()); }
};

This would be the base structure of such an iterator being used. Note that you'd had to actually write two such classes, one being constant.
Inside the iterator would look somewhat like this:
class Column::Iterator
{
    private:
        Column* father;
        size_t index;
    public:
        Iterator(Column* father, size_t index) : father(father), index(index { }
        Iterator operator++()    { Iterator i = *this; i.index++; return i; }
        Iterator operator++(int) { index++; return *this; }
        int32_t& operator*()     { return (*father)[index]; }
        int32_t* operator->()    { return &((*father)[index]); }
        bool operator==(const Iterator& other) { return father == other.father and index == other.index; }
        bool operator!=(const Iterator& other) { return not operator==(other); }
};

Note that I haven't tested the code.
More on this topic:
How to make the for each loop function in C++ work with a custom class
https://codereview.stackexchange.com/questions/74609/custom-iterator-for-a-linked-list-class
https://gist.github.com/jeetsukumaran/307264

A: You need a column access facet.  Your facet will have:

*

*a reference to the matrix, e.g. m_matrix

*the column number, e.g. m_column
You specify the matrix and the column number to construct the facet.  Then you need to define operator[] (row) { return this ->m_vector [row] [this ->m_column]; }.  HTH.


text:
Q: List of integers to Float in F# I just started working with FSharp and have this homework, hope anyone can help me.
I have to write a program that takes a list of integers and returns a float. It should be calculated by continued fraction.
So if the int list is [4; 5; 6]
The float will be calculated by: 4 + (1 / (5 + 1/6) )
The function has to be recursive.
I have written the following:
let rec fractionDecimal (numberlist : int list) : float =
  match numberList with
    |[] -> 0.0
    | x :: y -> x + 1.0 / fractionDecimal y

it doesn't work because (fractionDecimal y) float doesn't match the type int.
Do you have any suggestions how to solve the problem or what to do to get my code to work?
thanks in advance

A: The problem is that you're trying to add the value of 1.0 / fractionDecimal tail, a float, to head, an int.
You can remedy this situation with the float function.
let rec fractionDecimal (numberList : int list) : float =
    match numberList with
    | [] -> 0.0
    | head :: tail -> float head + 1.0 / fractionDecimal tail

This Microsoft documentation provides a pretty good description of what's happening here: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/compiler-messages/fs0001


text:
Q: FB open graph api, publishing like spotify to explain simply, my site let users to listen music from youtube (totally programmed using client side approach). What i need to implement is a spotify like function in ticker specially when the person is listening to a track.
I have defined
Action: Catch
Object: Music
What i would like to do is,
A. publish this in ticker.
Example:

ABC caught {Sample Music} on Mysite [Box with the link]

B. timeline in the activity block!!
is it possible to redirect the user to Mysite, rather than just to my FB app.
Also when the user clicks on {sample music}, i would like to redirect it to a particular page .?? is it possible?
As of now, when I click on sample Music, I get redirected to a page a like this:

http://mysite.com?fb_action_ids=502866955644&fb_action_types=fatslave%3Acatch&fb_source=other_multiline

and actually i need to pass three variables to my site (or my redirected site), lets say Artist, track, videoID, any idea how to go about it.

A: Got it working with help of Cbroe!!
step 1: create custom action properties (in my case propa,  propb , propc - mark as required)
step 2: when user redirects to ur site with action ID, use action Id to retrieve the custom action properties using GET.

more info here


text:
Q: DRF serializer change field to read_only for some model instances I have this model:
class Task(MPTTModel, TimeStampedModel, StartFinishModel):
    name = models.CharField(max_length=256)
    parent = TreeForeignKey('self',
                            on_delete=models.CASCADE,
                            related_name='children')
    start_date = models.DateField()
    finish_date = models.DateField()
    @property
    def is_stage(self):
        if self.get_children():
            return True
        return False

And serializer:
class TaskBaseSerializer(StartFinishSerializer, TimeStampedSerializer):
    class Meta:
        model = Task
        fields = ('id', 'name', 'parent', 'start_date', 'finish_date', 'is_stage')
        read_only_fields = ('is_stage')

I want to make fields 'start_date' and 'finish_date' to become read_only if is_stage property is True. How can I do that?

A: Try to override __init__() method like this:
class TaskBaseSerializer(StartFinishSerializer, TimeStampedSerializer):
    class Meta:
        model = Task
        fields = ('id', 'name', 'parent', 'start_date', 'finish_date', 'is_stage')
        read_only_fields = ('is_stage')

    def __init__(self, *args, **kwargs):
        super(TaskBaseSerializer, self).__init__(*args, **kwargs)
        if self.instance and getattr(self.instance, 'is_stage', None):
            self.fields['start_date'].read_only = True
            self.fields['finish_date'].read_only = True

A: Also the same result can be achieved with:
def get_fields(self):
    fields = super(TaskBaseSerializer, self).get_fields()
    if self.instance and getattr(self.instance, 'is_stage', None):
        fields['start_date'].read_only = True
        fields['finish_date'].read_only = True
    return fields


text:
Q: OSM, Query for POIs in a building How can I construct a query (for example for Overpass) for getting all buildings where inside the building is a node (for example a shop)?

A: Please see this link, which gives some important background information on this question with regards to Overpass API.
Assuming you want to find buildings with amenity nodes inside, you could use the following query in Overpass Turbo:
node({{bbox}})[amenity];is_in;
(way[building](pivot);>;);out;

It first checks for all nodes having an amenity tag in the current bbox and determines all areas containing those nodes. In the second line we convert areas back to actual ways and filter on ways with building tag.
With the Overpass API instance on overpass-api.de this only works for buildings having a name tag.  Reason being that the server side area creation process uses some specific extraction rules. Unless the objects matches any of those rules, no area will be created, as in the case for buildings without a name tag.
If you need all buildings, you would have to set up your own Overpass API instance and adjust rules/areas_osm3s to your needs.

A: AFAIK there is currently no API that offers such operator. You can use planet dumps and process it on your own by testing each POI node (or each building way) for checking the boundaries. Due to the amount of data, this can be pretty timeconsuming.


text:
Q: Proof verification: Diffeomorphism is an isometry if and only if it preserves the arclength of a parametrised curve. I am trying to show that a diffeomorphism $\phi : S \rightarrow \overline{S}$ is an isometry if and only if the arc length of any parametrized curve in S is equal to the arc length of the image curve by $\phi$.
$"\Rightarrow"$
We know that if the diffeomorphism $\phi$ is an isometry, then $$\left< \alpha '(t) , \alpha'(t) \right>_p = \left <d\phi_p(\alpha'(t)), d\phi_p(\alpha'(t)) \right>_{\phi(p)},$$ and since $\lvert \alpha'(t) \rvert = \left< \alpha'(t), \alpha'(t) \right >_p = \left <d\phi_p(\alpha'(t)), d\phi_p(\alpha'(t)) \right>_{\phi(p)}=\lvert d\phi_p (\alpha'(t)) \rvert = \lvert (\phi \circ \alpha)'(t) \rvert$, we conclude that arc length of $\alpha\left(t\right)$, $s(t) = \int_{0}^{t_0} \mid \alpha'(t) \mid dt = \int_{0}^{t_0} \lvert(\phi \circ \alpha)'\left(t\right)\rvert dt$ = length of image curve by $\phi$.
$\therefore$ If $\phi$ is an isometry, then the arclength under $\phi$ is preserved.
"$\Leftarrow$"
NTS: If arclength under the map $\phi$ is preserved, then $\phi$ is an isometry.
Since arc length of $\alpha$ is preserved under the diffeomorphism $\phi$, $$s(t) = \int_{0}^{t_0} \lvert \alpha'(t) \rvert dt = \int_{0}^{t_0} \lvert (\phi \circ \alpha)'(t) \rvert dt.$$ Differentiating both sides, we get:
$\frac{ds}{dt} = \lvert \alpha'(t) \rvert = \lvert (\phi \circ \alpha)'(t) \rvert$. Hence $$\left< \alpha'(t) , \alpha'(t) \right>_p = \left< d\phi (\alpha'(t), d\phi(\alpha'(t)) \right>_{\phi(p)}.$$
Since $\phi$ is a diffeomorphic map, and the differential $d\phi$ preserves the inner product, we conclude that $\phi : S \rightarrow \overline{S} $ is an isometry.
$\therefore$ diffeomorphism $\phi$ is an isometry if and only if the arc length of any parametrised curve in $S$ is equal to the arc length of the image curve by $\phi$.
Is this correct? Thanks

A: It is good. If you want to nitpick, note that you have proven that $\langle d\phi_p(v), d\phi_p(v)\rangle_{\phi(p)} = \langle v,v\rangle_p$ for all $v \in T_pS$, and it follows that $\langle d\phi_p(v), d\phi_p(\color{red}{w})\rangle_{\phi(p)} = \langle v,\color{red}{w}\rangle_p$ for all $v,w \in T_pS$ by polarization (you might mention that word somewhere).
The same argument shows that a diffeomorphism between pseudo-Riemannian manifolds is an isometry if and only if it preserves the energy of all curves, where by energy of a curve $\alpha: I \to M$ in $(M,\langle\cdot,\cdot\rangle)$ I mean $$E[\alpha] = \frac{1}{2} \int_I \langle \alpha'(t),\alpha'(t)\rangle_{\alpha(t)}\,{\rm d}t.$$


text:
Q: lack of equivalency of 1 norm and infinity norm on continous functions
Show that $\|\cdot\|_1$ and $\|\cdot\|_{\infty}$ are not equivalent on $\phi \in C([a,b])$.

The hint given is that you can find the upper bound, but you cant find the lower bound required for the norms to be equivalent basically there doesn't exist a $\alpha$ such that $\alpha \|\phi\|_{\infty} \leq \|\phi\|_1$ for all $\phi$.
However I'm questioning this since it seems trivially true to me that
$\|\phi\|_{\infty} \leq \|\phi\|_1$
since $\|\phi\|_1 = \int_{a}^{b} |\phi(s)|ds$ and $\|\phi\|_{\infty} = \max\{\phi(x):\ x \in [a,b]\}$, so $\alpha$ is just $1$ in this case.
I've missed something small here. Anyone help me in proving this result?

A: There's a typo in the question - you want to show that the two norms are not equivalent.
Indeed, there is no $\alpha$ so that $||\phi||_\infty\le\alpha||\phi||_1$ for all $\phi$. So yes, you're missing something. Hard to say what you're missing, exactly. You give the definitions of the two norms and then say it follows trivially that $||\phi||_\infty\le||\phi||_1$. This is not true, and it doesn't follow - to say what you're missing we need to know why you think it does follow...
Edit In fact the inequality $||\phi||_1\le(b-a)||\phi||_\infty$ is immediate from the definitions. Possibly you can find the error in your reasoning regarding the other inequality by considering a specific example.  Take $[a,b]=[0,1]$ and let $\phi(t)=t^n$. What are $||\phi||_\infty$ and $||\phi||_1$?


text:
Q: Python data manipulation to delete rows based on condition I have three columns, one with different Text, another column represents the category they belong to, third column is the department
Example
department Category  Text

1          a7        great school
1          a7        Enjoy classes
1          a7        Social studies
1          a8        JOHN
1          a8        RONIE
1          a8        Amazing lecturer
1          a8        walking to school
1          a9        Effective tomorrow
1          a9        marie kate
1          a9        math
2          a8        lissie
2          a8        lovely
2          a5        Ronie

If any Text in the category contains JOHN, the entire category has to be removed.
For example, since There JOHN is in category a8 for department1, all rows of the category a8 has to be removed for department 1 alone. Since there is no JOHN in category a8 of department 2, nothing needs to be done here
indexNames = df[(df['Text'] == 'JOHN').index

desired output:
 department Category  Text
    1          a7        great school
    1          a7        Enjoy classes
    1          a7        Social studies
    1          a9        Effective tomorrow
    1          a9        marie kate
    1          a9        math
    2          a8        lissie
    2          a8        lovely
    2          a5        Ronie

I am new to python. Can anyone help me with this

A: The problem is harder than it looks at the first glance :)
First, find the categories and departments to be removed:
to_be_removed = df.loc[df.Text == 'JOHN', ['department', 'Category']]

Next, select all rows that are in those categories by merging the original data frame and the one obtained at the previous step. We need only the indexes of those rows:
bad_indexes = df.reset_index().merge(to_be_removed)['index']

Finally, extract the "good" rows:
df.loc[~df.index.isin(bad_indexes)]

#    department Category                Text
#0            1       a7        great school
#1            1       a7       Enjoy classes
#2            1       a7      Social studies
#7            1       a9  Effective tomorrow
#8            1       a9          marie kate
#9            1       a9                math
#10           2       a8              lissie
#11           2       a8              lovely
#12           2       a5               Ronie

A: I believe you can filter df as such:

*

*Get the departments that have 'JOHN' as the Text value

*Filter out the records that are have department in the list from (1) above

tmp = df[(df['Text'] == 'JOHN')]

df = df[~(df['Category'].isin(tmp['Category']))]

A: Hope this question is for pandas. If you are not using pandas, try pandas.I created the dataframe using below codes in pandas.
import pandas as pd
df = pd.DataFrame()
df['department']=department
df['category']=category
df['text']=text

You can remove the rows from dataframe by specifying the column and the condition as shown below.
cdn1 = df['text']=='JOHN'
cdn2 = df['category'] == df.loc[cdn1]['category'].values[0]
cdn3 = df['department'] == df.loc[cdn1]['department'].values[0]

Then drop the corresponding indexes
df.drop(np.where(cdn2 & cdn3)[0], inplace=True)

Result:
department  category    text
    1           a7          great school
    1           a7          Enjoy classes
    1           a7          Social studies
    1           a9          Effective tomorrow
    1           a9          marie kate
    1           a9          math
    2           a8          lissie
    2           a8          lovely
    2           a5          Ronie


text:
Q: Call methods in C# asynchronously I have 6 service hits in a page which are called in Dashboard page load event
In these methods I have to bind ASP chart methods.
By performance wise the page is loading slow. Here I don't have another option to get all the details in one method
So how can I bind asynchronous for these methods?
Thanks in advance
Here is my code
 protected void Page_Load(object sender, EventArgs e)
        {
                BindTransactionCountDetails();
                BindTransactionAmountDetails();
                BindCustomerInfo();
                BindBalanceInfo();
                BindTasCount();
                BindTagReadersCount();
        }

Calling these methods one by one, so time is taking to load the page. So I want to call above methods asynchronously.

A: Give this a try (this requires .NET 4 or newer):
List<Task> tasks = new List<Task>();
tasks.Add(Task.Factory.StartNew(BindTransactionCountDetails));
tasks.Add(Task.Factory.StartNew(BindTransactionAmountDetails));
tasks.Add(Task.Factory.StartNew(BindCustomerInfo));
tasks.Add(Task.Factory.StartNew(BindBalanceInfo));
tasks.Add(Task.Factory.StartNew(BindTasCount));
tasks.Add(Task.Factory.StartNew(BindTagReadersCount));

Task.WaitAll(tasks.ToArray());


text:
Q: Azure ADB2C - Web APIs authentication for SPA and Daemon App I have an API project written in .NET which can be called from a Daemon App (desktop client) and also can be called from an Angular Website.  I have the Daemon App setup in Azure B2C with a client secret.  I have the SPA setup in Azure and also the API.
In the Startup.cs file of the API - I can secure the APIs for the Daemon App by doing the following:
 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(opt =>
                {
                    opt.Audience = Configuration["AAD:ResourceId"];
                    opt.Authority = $"{Configuration["AAD:Instance"]}{Configuration["AAD:TenantId"]}";
                });

The settings in appsettings.json are:
"AAD": {
    "ResourceId": "https://xxxx.onmicrosoft.com/xxxxx",
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "xxxx"
  }

I can secure the SPA by doing the following in the API startup.cs:
 //Adds Microsoft Identity platform(AAD v2.0) support to protect this Api
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddMicrosoftIdentityWebApi(options =>
                    {
                        Configuration.Bind("AzureAdB2C", options);
                        options.TokenValidationParameters.NameClaimType = "name";
                    },
                    options => { Configuration.Bind("AzureAdB2C", options); });

The appsettings.json file contains the following:
  "AzureAdB2C": {
    "Instance": "https://xxxxxx.b2clogin.com",
    "ClientId": "xxxxxx",
    "Domain": "xxxx.onmicrosoft.com",
    "SignUpSignInPolicyId": "b2c_1_susi",
    "EditProfilePolicyId": "b2c_1_edit"
  }

I cannot figure out how to combine these two different authentication methods or even if this is possible.
Any help much appreciated.
Thanks

A: I've been at this for nearly two days and just after posting this question, I found the solution.  So, I'll post here just in case anyone spends as long as me!!
In Azure for the API - add this into the manifest.

Then in API Permissions - add in this as a delegated permission.

For the startup.cs file - use this
 //Adds Microsoft Identity platform(AAD v2.0) support to protect this Api
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddMicrosoftIdentityWebApi(options =>
                    {
                        Configuration.Bind("AzureAdB2C", options);
                        options.TokenValidationParameters.NameClaimType = "name";
                    },
                    options => { Configuration.Bind("AzureAdB2C", options); });

And now my two apps can communicate securely with my API. A website I found useful was: https://yourazurecoach.com/2021/01/05/api-security-for-dummies-retrieve-more-user-information/


text:
Q: Parsing json with php and javascript I'm pretty confused and every way I've tried I keep getting internal error 500.
I'm trying to parse THIS json using PHP and return it to the client side.
inventory.php
/**
* Fetches users inventory.
*/
$userId = $_GET['userId'];
$inventoryUrl = 'http://steamcommunity.com/id/' . $userId . '/inventory/json/730/2/';

if ($userId) {
    $url = file_get_contents($inventoryUrl);
    $json = json_decode($url);
    print_r($json);
}

And with jQuery I'm trying to fetch that object and parse it so I can insert it into html.
$.when(getUserInventory('koraktor')).done(function(data){
    var inventory = data;
    var selectItemsElem = $('#select-items');
    console.log(inventory);

    //console.log(inventory);
});

function getUserInventory(userId) {
    var inventoryUrl = 'inventory.php';
    return $.ajax({
        url: 'inventory.php',
        data: {userId: userId},
    })
    .done(function(data) {
        return data;
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });

}

});

In console it shows:

I need to parse $object->rgInventory->rgDescriptions
I'm just not sure how though.
SO my question is, how do I correctly parse this object so I can use a for loop and how would I use the for loop so I can insert each item into html?

A: You can enumerate the properties of the rgInventory part of your object. These are your items.
for(var item in inventory.rgInventory) {

   if (inventory.rgInventory.hasOwnPrioperty(item) )
      console.log(item.id)

}


text:
Q: Return Two Highest Values in List, in Javascript I can't figure this one out, I wrote a messy code for it, and now I am don't know how to fix it or what to do next.
In this kata, your job is to return the two distinct highest values in a list. If there're less than 2 unique values, return as many of them, as possible.
The result should also be ordered from highest to lowest.
Example
[4, 10, 10, 9]  =>  [10, 9]
[1, 1, 1]  =>  [1]
[]  =>  []

Source
https://www.codewars.com/kata/57ab3c09bb994429df000a4a/train/javascript
This is my incorrect code
function twoHighest (arr) {
let max1 = Math.max(...arr);

var i = 0;
  while (i < arr.length) {
    if (arr[i] === max1) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  var array2 = arr;
  var maxone = [max1];
  let max2 = [Math.max(...array2)];
  return maxone.concat(max2);
};

A: Step 1: Unique array by Array.filter
Step 2: Sort by DESC by Array.sort
Step 3: Get first 2 element of sorted array by Array.slice

function twoHighest(arr) {
  return arr
    .filter((v, i, a) => a.indexOf(v) === i)  // Unique array
    .sort((a, b) => b - a)  // Sort by DESC
    .slice(0, 2);  // Get first 2 element of sorted array
};

const demoArray = [15, 20, 20, 17];
const result = twoHighest(demoArray);
console.log(result);


text:
Q: How do I quickly change the current calendar being used for new events in Lion? I have different calendars for various types of things that I use to schedule my days.  This involves switching between the different calendars for different kinds of events when doing the scheduling.  In Snow Leopard, I could just select the calendar I wanted by clicking on it on the left.  With Lion, it looked like I might be able to get the same functionality with the little "Calendar" button in the upper left, but that just seems to allow me to rename the Calendars, without actually setting one as being currently active for creating new events.
I can edit each event individually, but that is rather tedious.  (Though Going into advanced preferences, and clicking the "Open events in a separate window" reduces the pain somewhat)
I can also set the default calendar in preferences, but that is even more tedious than editing the events.
So, how do I quickly change the current calendar being used for new events in Lion?

A: Change the default calendar to "last selected calendar" then clicking a calendar via the "Calendar" button pop-over will actually set the currently active calendar for new events.


text:
Q: What happens when you change the Account currency of an Account from EUR to GBP? What happens when you change the Account currency of an Account from EUR to GBP?
Does making any changes to the standard currency field impact on any other areas?

A: If you change the Currency field to other currency value(Like from Euro to GBP) if there is any amount value of the record you have to adjust that value to corresponding currency. Because if you change the currency type salesforce wont convert the value in the amount to corresponding values.
Also there will be mismatch between the related records currency(Opportunity) and parent record currency(Account). If there are any roll up calculations on it this may impact.


text:
Q: MVVM - pass info from MainWindow ViewModel to WinForms based child UserControl I'm working on a WPF/MVVM application that will host a WinForms graphical control for the display of CAD-type geometry.
First, a little background.
Basically, I have a MainWindow with a TreeView on the left and a TabControl on the right.  The TreeView simply renders an Observable collection of TreeNode objects.  Based on the type of node that's clicked in the tree, the main window's ViewModel creates an instance of an appropriate child ViewModel for the selected tree node (a "workspace").  The new workspace is added to another Observable collection that's bound to the TabControl - which creates a new tab item.  This is very similar to the well-known Josh Smith example.
In the XAML of the main window, I'm using <DataTemplate DataType...>
to instantiate an appropriate View for the just created ViewModel.
So far, so good.  That all works well.  Now, here's where I'm stuck...
One "type" of tree node represents a CAD model.  When a node of that type is selected, the view that's instantiated contains the WinForms graphical control (wrapped in a WinFormsHost UserControl).  The underlying WinForms control has a "LoadFile()" method that simply requires a filename as input.
The object that's rendered as a tree node in the MainWindow contains the name of the file I need to load.  So, I'm trying to figure out the best way to get the filename from the tree node object and pass it to the "LoadFile()" method in the underlying WinForms control.
I have the filename in the MainWindow's ViewModel at the time I create the ViewModel for the CAD control (which, in turn, creates the View containing the WinForms control via the XAML DataTemplate).
Every attempt I've made so far feels like I'm painting myself into a corner.  So, am I already too far in the weeds, or does this sound salvageable?
Edited to post code as requested below...
Relevant code-behind of User Control
public string MSIFile
{
    get { return (String)GetValue(MSIFileProperty); }
    set { SetValue(MSIFileProperty, value); }
}

public static readonly DependencyProperty MSIFileProperty =
    DependencyProperty.Register("MSIFIle", typeof(string), typeof(ViewportUserControl),
    new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnMSIFileChanged)));

private static void OnMSIFileChanged(
   DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    Console.WriteLine(e);
}

User Control XAML
<UserControl x:Class="TruNest.UserControls.ViewportUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:vp="clr-namespace:CustomControls;assembly=Winforms"
             d:DesignHeight="300"
             d:DesignWidth="300"
             mc:Ignorable="d" Loaded="UserControl_Loaded">
    <Grid>
        <WindowsFormsHost HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <vp:ViewportCustomUC x:Name="Wrapper" />
        </WindowsFormsHost>
    </Grid>
</UserControl>

Code from MainWindow ViewModel - triggered when new TreeNode is selected
else if (_selectedTreeViewItem is ViewportNode)
{
    ViewportNode node = _selectedTreeViewItem as ViewportNode;
    ViewportViewModel workspace = new ViewportViewModel();
    workspace.TreeNode = _selectedTreeViewItem;
    workspace.Name = String.Format("{0}", node.Name);
    Workspaces.Add(workspace);
    this.SetActiveWorkspace(workspace);
}


text:
Q: MVVM+ WPF PopUp not opening XAML

<Popup Name="popUpProgress" Width="225" Height="85"
           IsOpen="{Binding PopUpIsOpen,Mode=OneWay}"
           Placement="Center" PlacementTarget="{Binding ElementName=stkListview}"
           VerticalAlignment="Top">
    <Border BorderThickness="1" Background="Blue"  >
        <Grid   Width="225" Height="85">
            <Grid.RowDefinitions>
                <RowDefinition Height="30" />
                <RowDefinition Height="30" />
            </Grid.RowDefinitions>
            <Label x:Name="lblProgress" Content="Please Wait ...." Margin="10,5,0,0" HorizontalAlignment="Left" Grid.Row="1" />
        </Grid>
    </Border>
</Popup>

In view Model:
private bool _PopUpIsOpen;

public bool PopUpIsOpen
{
    get { return _PopUpIsOpen; }
    set
    {
        _PopUpIsOpen = value;
        RaisePropertyChanged(() => this.PopUpIsOpen);
    }
}

public RelayCommand SubmitCommand { get; private set; }

private bool SubmitCommandCanExecute()
{
    return true;
}

private void SubmitCommandExecute()
{

    PopUpIsOpen = true;

    dsStandardListbyMarket = marketBL.StandardListbyMarketBL(Convert.ToInt32(SelectdMarketId), Convert.ToInt32(Users.UserId));
    GetComboboxMappingCollections(Convert.ToInt32(this.SelectdMarketId), Users.UserId);
    FItems = new ObservableCollection<MarketRecord.FItem>();
    FItems.CollectionChanged += OnUICollectionChanged;
    marketBL.FetchMarketRecords(Convert.ToInt32(this.SelectdMarketId));
    IsSubmitButtonVisible = true;

    PopUpIsOpen = false;
}

When I click on submit button control comes to SubmitCommandExecute but Popup window is not showing. I am bit new to WPF, scratching my head over it. Finally raising this question here. What might be wrong.

A: I think the problem is in the way you are testing the code. SInce you are sleeping in the UI thread, the UI does not feel the change from true to false on the bound property.
Try to use a timer instead of a Sleep in the thread.

A: Given the RaisePropertyChanged syntaxe on msdn :
protected internal void RaisePropertyChanged (
   string propertyName
)

You should try RaisePropertyChanged("PopUpIsOpen"); instead of RaisePropertyChanged(() => this.PopUpIsOpen);


text:
Q: Today Extension with UICollectionView different behaviour compared to Single View Application I try to add a collection view to a Today Extension with specifying the items per row of 3 items and also with setting the section insets for with 20 for top, left, bottom and right. When I do this in a Single View Application everything is like expected, but when I do the same programmatically for the Today Extension the collection view looks different, especially the space of the right and bottom seems not to be like in the Single View Application. What's the reason why there is this difference? I expected the same behaviour for the Today Extension like in the Single View Application.
To understand my problem better below is the code of the Single View Application and the Today Extension, both with Screenshots:
ViewController of the Single View Application:
import UIKit

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    var collectionView: UICollectionView!
    let sectionInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
    let itemsPerRow: CGFloat = 3

    override func viewDidLoad() {
        super.viewDidLoad()

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = sectionInsets

        collectionView = UICollectionView(frame: view.frame, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
        collectionView.backgroundColor = .white
        view.addSubview(collectionView)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 6
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
        cell.backgroundColor = .blue

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
        let availableWidth = view.frame.width - paddingSpace
        let widthPerItem = availableWidth / itemsPerRow

        return CGSize(width: widthPerItem, height: widthPerItem)
    }
}

Screenshot of the Single View Application:

TodayViewController of the Today Extension:
import UIKit
import NotificationCenter

class TodayViewController: UIViewController, NCWidgetProviding, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    var collectionView: UICollectionView!
    let sectionInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
    let itemsPerRow: CGFloat = 3

    override func viewDidLoad() {
        super.viewDidLoad()

        extensionContext?.widgetLargestAvailableDisplayMode = .expanded

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = sectionInsets

        collectionView = UICollectionView(frame: view.frame, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
        collectionView.backgroundColor = .white
        view.addSubview(collectionView)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 6
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
        cell.backgroundColor = .blue

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
        let availableWidth = view.frame.width - paddingSpace
        let widthPerItem = availableWidth / itemsPerRow

        return CGSize(width: widthPerItem, height: widthPerItem)
    }

    func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
        // toggle height in case of more/less button event
        if activeDisplayMode == .compact {
            self.preferredContentSize = CGSize(width: 0, height: 110)
        } else {
            self.preferredContentSize = CGSize(width: 0, height: 220)
        }
    }
}

Screenshot of the Today Extension:

A: I solved my own problem with the help of this answer. The solution so far is that I just setup the collection view in viewDidAppear(_:) instead of viewDidLoad() in the TodayViewController of the Today Extension (The space to the bottom currently looks like that, because I set a fix height of 220):
import UIKit
import NotificationCenter

class TodayViewController: UIViewController, NCWidgetProviding, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    var collectionView: UICollectionView!
    let sectionInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
    let itemsPerRow: CGFloat = 3

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        extensionContext?.widgetLargestAvailableDisplayMode = .expanded

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = sectionInsets

        collectionView = UICollectionView(frame: view.frame, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
        collectionView.backgroundColor = .white
        view.addSubview(collectionView)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 6
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
        cell.backgroundColor = .blue

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
        let availableWidth = view.frame.width - paddingSpace
        let widthPerItem = availableWidth / itemsPerRow

        return CGSize(width: widthPerItem, height: widthPerItem)
    }

    func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
        // toggle height in case of more/less button event
        if activeDisplayMode == .compact {
            self.preferredContentSize = CGSize(width: 0, height: 110)
        } else {
            self.preferredContentSize = CGSize(width: 0, height: 220)
        }
    }
}

Now I get the same result as in the Single View Application:

Update:
Unfortunately the solution from above had still a not expected behaviour. When the Today Extension was in an expanded state before the build, it looks like the screenshot from above, like expected. The problem is when it's in a collapsed state before the build and I want to expand the extension, the result looks like this (the expanded part of the collection view is just cutted off):

The solution for this problem is so far to set the initial frame of the collection view to .zero and set the frame in viewWillLayoutSubviews() like this:
import UIKit
import NotificationCenter

class TodayViewController: UIViewController, NCWidgetProviding, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    var collectionView: UICollectionView!
    let sectionInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
    let itemsPerRow: CGFloat = 3

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        extensionContext?.widgetLargestAvailableDisplayMode = .expanded

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = sectionInsets

        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
        collectionView.backgroundColor = .white
        view.addSubview(collectionView)
    }

    override func viewWillLayoutSubviews() {
        let frame = view.frame
        collectionView?.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: frame.size.height)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 6
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
        cell.backgroundColor = .blue

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
        let availableWidth = view.frame.width - paddingSpace
        let widthPerItem = availableWidth / itemsPerRow

        return CGSize(width: widthPerItem, height: widthPerItem)
    }

    func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
        // toggle height in case of more/less button event
        if activeDisplayMode == .compact {
            self.preferredContentSize = CGSize(width: 0, height: 110)
        } else {
            self.preferredContentSize = CGSize(width: 0, height: 220)
        }
    }
}

Now the behaviour is like expected, like shown in the first result screenshot even if the Today Extension was first collapsed.


text:
Q: Flake8 check ok I recently got a problem: I did a fresh ubuntu 22.04 setup, installed vim and flake8. After opening my .py file, flake8 doesn't show any errors (even of there are some, I did them on purpose). Is there anything I could do?
Other plugins work, there is no problem with them, it's just flake8.
When I run flake8 xyz.py in my terminal it works and also shows the errors.
I am using vim 8.2 on ubuntu 22.04
I also installed the vim-flake8 plugin from github

A: Ok I got it fixed, I did a mistake because my $PATH in vim was set to zsh which is not installed anymore. After changing the shell to /bin/sh it's working again.
If anybody needs help:
set shell=/bin/sh


text:
Q: Add values with key and value pair in the list in Java I have this list
  "DailyQuantity": [0,0,0,0,0,0,0,1,3,4,4,4]
So I want to add like
"DailyQuantity": [{"one" , 0},{"two" , 0},{"three" , 0},{"four" , 0},{"five" , 0},{"six" , 0},{"seven" , 0},{"eight" , 1},{"nine" , 3},{"ten" , 4},{"eleven" , 4},{"twelve" , 4}]

A: I'm not sure if this answers your question, but you could try using a map:
Map<String,Integer> DailyQuantity = new HashMap<String, Integer>();
DailyQuantity.put("one",0);
DailyQuantity.put("two",0);
...

A: It would be better to provide a list/array of numeral words (and/or generator method for numbers > 20) and use it to create a map.
If you need to keep the order of insertion, you should use LinkedHashMap.
final List<String> numeralsTo20 = Arrays.asList(
    "zero", "one", "two", "three", "four",
    "five", "six", "seven", "eight", "nine",
    "ten", "eleven", "twelve"// etc..
);

// should be retrieved from JSON
List<Integer> dailyQuantity = Arrays.asList(0,0,0,0,0,0,0,1,3,4,4,4);

Map<String, Integer> quantityMap = IntStream.range(0, dailyQuantity.size()) // get stream of int indexes
     .boxed()                      // convert to Integer objects
     .collect(Collectors.toMap(
         i -> numeralsTo20.get(i + 1), // key
         i -> dailyQuantity.get(i),    // quantity value
         (o1, o2) -> o2,               // merge function to add new entry
         LinkedHashMap::new));         // LinkedHashMap maintains insertion order

quantityMap.entrySet().forEach(System.out::println);

// quantityMap should be serialized back to JSON

output:
one=0
two=0
three=0
four=0
five=0
six=0
seven=0
eight=1
nine=3
ten=4
eleven=4
twelve=4


text:
Q: ASP.NET: Call function in MasterPage through UserControl Calling a function from the MasterPage in a Page is quite straigt forward but how do I call it for a UserControl:
Adding <%@ MasterType VirtualPath="~/MasterPage.master" %>, doesn't work on UserControls.
So this.Page.Master.MyFunction() fails :(

A: Niels,
Leverage reflection (as suggested by JDunkerley) is one approach to the problem.  Another you might consider is implementing an interface:

*

*Create an interface that includes your method.

*Implement the interface in your master page

*From your control, reference this.Page.Master via the interface type.

*Call your method.

This is a better OO approach, leads to less coupling, and will certainly perform better than runtime reflection.
I hope this helps!

A: You are couppling your code very thighly if you call a function on the masterpage from within your user control.
The Control can only be used on pages that are based on that master. I think this is usually a bad design, and it will violate at least the law of demeter.
What exactly do you want to accomplish in your control?

A: You have to cast the this.Page.Master first as the Master property of the Page is of type System.Web.UI.MasterPage.
e.g.
((MyMaster)this.Page.Master).MyFunction();

You could check the type of the underlying master page by adding a property to the code behind of the user control:
    public string MType
    {
        get { return this.Page.Master.GetType().FullName; }
    }

and print the result out in the User control markup, e.g. add this line to make it print out as a comment in the source code:
<!-- <%= MType %> //-->

A: JDunkerley has it right.  But allow me to explain how to decouple it using MVP so you can work toward avoiding the design issue Heiko Hatzfeld is talking about.
Basically, implement the MVP pattern for both your control and your master page.  See here for instructions on how to do that.  Declare the method you want to call in the master's interface (IMasterView).  Next create a class that will control the relationship between the two components; we'll call it the PageController class.  Place an instance of this class in request state for each request by adding the following line to global.asax.cs:
/* global.asax.cs */
protected void Application_BeginRequest(object sender, EventArgs e)
{
    // ...
    HttpContext.Current.Items["Controller"] = new PageController();
    // ...
}

You can then access this instance from each of the presenters (master and control) via the following line of code:
var controller = HttpContext.Current.Items["Controller"] as PageController;

You can then implement an event or some other mechanism to allow the control to invoke the method on the master in a decoupled manner through this shared object.  For example:
/* PageController.cs */
public event EventHandler SomeEvent;

protected virtual void OnSomeEvent(EventArgs e)
{
    Debug.Assert(null != e);

    var handler = this.SomeEvent;
    if (null != handler)
        handler(this, e);
}

public void FireSomeEvent()
{
   this.OnSomeEvent(EventArgs.Empty);
}

/* ControlPresenter.cs */
public ControlPresenter(IControlView view)
    : base()
{
    view.EventFired += (sender, e) =>
    {
        var controller = HttpContext.Current.Items["Controller"] as PageController;
        controller.FireSomeEvent();
    };
}

/* MasterPresenter.cs */
public MasterPresenter (IMasterView view)
    : base()
{
    var controller = HttpContext.Current.Items["Controller"] as PageController;
    controller.SomeEvent += (sender, e) => view.MyFunction();
}

Make sure the "EventFired" event is declared in your control's interface (IControlView) and implemented in the control.  Then all you have to do to affect the master (call its method), is fire this event and the MVP + the PageContoller will take care of the rest.
Cheers

A: I couldn't get the above answers to work, so here is what worked for me:
You want to reference a master page property from a user control.
Firstly, your master page will have a public property like so :
public string BodyClass
{
    set
    {
        this.masterBody.Attributes.Add("class", value);
    }
}

Now add a reference to the master page in the user control ASCX file like so :
<%@ Register Src="~/Source/MasterPages/Main.master" TagPrefix="MSTR" TagName="MasterPage" %>

Then in the code behind (C# in my case) you have this code :
Main masterPage = (Main)this.Page.Master;
masterPage.BodyClass = "container";

Without the reference to the master page above your user control will not be able to find the master page class.


text:
Q: functions.php cause white-screen and media-library issues I disable all plugins, all white-space and php comments in the function.php.
but problem not solved.
when i remove all code in the function.php the problem is solved but if write <?php ?> in the file the problem return
functions.php cause white-screen and media-library not loaded.Here the function.php:
<?php
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);
add_action('woocommerce_before_main_content', 'my_theme_wrapper_start', 10);
add_action('woocommerce_after_main_content', 'my_theme_wrapper_end', 10);
function my_theme_wrapper_start() { echo '
'; }
function my_theme_wrapper_end() { echo '
'; }
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 70, 150 );
function register_my_menu() {
  register_nav_menu('header-menu',__( 'Header Menu' ));
}
add_action( 'init', 'register_my_menu' );
add_filter( 'add_to_cart_text', 'woo_custom_cart_button_text' );
add_filter( 'woocommerce_product_add_to_cart_text', 'woo_custom_cart_button_text' );
function arphabet_widgets() {
    register_sidebar( array(
        'name' => 'sidebar',
        'id' => 'right-panel',
        'before_widget' => '
',
        'after_widget' => '
',
        'before_title' => '
',
        'after_title' => '
',
    ) );
}
add_action( 'widgets_init', 'arphabet_widgets' );
function search() {

    register_sidebar( array(
        'name' => 'search',
        'id' => 'search-panel',
        'before_widget' => '
',
        'after_widget' => '
',
        'before_title' => '
',
        'after_title' => '
',
    ) );
}
add_action( 'widgets_init', 'search' );
add_theme_support( 'woocommerce' );
?>

how to fix it?!

A: Try removing the PHP-ending tag ?> from the file functions.php. It is unneccessary and I've encountered situations where whitespace / line breaks that come after "?>"-tag cause WordPress to throw a blank screen, because headers are sent too early / multiple times (Headers already sent).


text:
Q: Speed difference MS SQL Server 2019 to PostgreSQL/PostGIS 12 for spatial data I imported a shapefile with 3000 polygons in UTM 25832 into both databases MS SQL Server 2019 and PostgreSQL/PostGIS. Then I calculated a buffer of 1000 meters around these geometries and transferred the result to a new table. (Again in both databases with their integrated STBuffer() functions)
Result:
PostGIS: 9 seconds
MS SQL 2019: 1 minute
MS SQL 2017: 1:09 minutes
All databases are running on the same PC and both MSSQL Server and PostgreSQL/PostGIS have been freshly set up. No optimizations were deliberately carried out and no spatial indices were used.
Is it really possible that PostgreSQL/PostGIS is so much faster than MS SQL Server 2019 as far as geodata is concerned?

A: Spatial algorithms such as buffer are complex, with a lot of moving parts.  It only takes one inefficient design decision or data structure to reduce performance.  Conversely, sometimes it's possible to find a different approach that can improve performance dramatically.
The PostGIS buffer code (which originates in JTS/GEOS) has some optimizations which really help to improve performance.  For example, since buffers tend to "blur out" fine detail along boundaries, the algorithm simplifies boundaries before running the actual buffer.  This can dramatically reduce the number of points being computed, and hence increase performance.

A: My take on the spatial data component of MSSQL Server echoes the documentation - basic spatial capabilities, and anything more complex is handled by 3rd parties.
What this means to us is that MSSQL Server can handle some basic Spatial SQL functions that get a bit of information from an overlapping polygon, a quick distance or area of few features, etc.
It isn't built and doesn't perform well for doing massive spatial operations on thousands or millions of features - what is otherwise called "geoprocessing". This is where ESRI has picked up and said 'if you're going to store spatial data in a database, it is best managed/edited/analysed by our GUI'.
PostGIS, on the other hand, has been built not just for the simple stuff, but for the complex bulk processing of spatial and non-spatial data in the database, and as such, performs much faster. This has been true for all student/boundary/demographic analysis we perform in our system using postgis.
To its credit, however, MSSQL Server was a great 'gateway' into SQL and spatial data. PostgreSQL with PostGIS is just the best.


text:
Q: how to separate Array of single element by comma `["275/55R20, 275/60R20"]` this into ["275/55R20", "275/60R20"] in ruby My array is sizes = ["275/55R20,  275/60R20"]
I want to convert it into sizes = ["275/55R20",  "275/60R20"]
please someone help to do it in ruby

A: Use the split method on the desired array element:
sizes = ["275/55R20,  275/60R20"]
sizes = sizes[0].split(",  ")
#=>  ["275/55R20", "275/60R20"]


text:
Q: Defining composite of piecewise function Let $$f(x) = \begin{cases}
x+2, -3\leq x \lt-1 \\
x-1,-1\leq x \lt3
\end{cases}$$
I had to find $f(f(x)$
I defined $f(f(x)$ to be:
$$f(f(x)) = \begin{cases}
f(x)+2, -3\leq f(x) \lt-1 \\
f(x)-1,-1\leq f(x) \lt3
\end{cases}$$
Finally it evaluated to be
$$f(f(x)) = \begin{cases}
x+1, -3\leq f(x) \lt0 \\
x-2,0\leq f(x) \lt3
\end{cases}$$
But by graphing on a graphing application Desmos, I got the following graph:
(purple lines indicate $f(f(x))$)

Link: https://www.desmos.com/calculator/knrx71as8b
Isn't the graph wrong? How can $f(f(x))$ return $x+2$ ?

A: You typed it in wrong: you defined $f(x)$ as $x+1$ on the interval $-3\le x\le -1$ in Desmos, where you meant $x+2$. When you fix this typo, the graph is correct.
In your post above, your final evaluation should read
$$f(f(x)) = \begin{cases}
x+1, &\text{if } {-}3\leq x \lt0 \\
x-2, &\text{if }0\leq x \lt3
\end{cases}$$
(you had $f(x)$ in place of $x$ on the right-hand side).


text:
Q: Spring boot: SSE Server Sent Events not working In Spring Boot, when we try to send a Server Sent Event, it only sends an error event containing data: {"timeout":-1} when we try to connect, and the connection closes. The Spring Boot class is as follows
@RestController
@CrossOrigin(origins = "*")
public class SsePushNotificationRestController {
    private static final Logger log = LoggerFactory.getLogger(SsePushNotificationRestController.class);
    private SseEmitter emitter;

    @GetMapping("/test")
    public String getString(){
        try {
            emitter.send("User connected");
            log.info("User connected");
            emitter.complete();
        } catch (Exception e) {
            log.info("Error while sending message to client: " + e.getMessage());
        }
        return "placeholder";
    }

    @GetMapping("/emitter")
    public SseEmitter eventEmitter(@RequestParam String userId) {
        emitter = new SseEmitter(-1L);
        return emitter;
    }
}

And our client code is as follows:
const eventSource = new EventSource('http://localhost:8080/emitter?userId=testUser');

eventSource.addEventListener("message", (event) => {
    console.log(event);
});

eventSource.addEventListener("open", (event) => {
    console.log("connection opened");
});

eventSource.addEventListener("error", (e) => {
    if (e.readyState === EventSource.CLOSED) {
        console.log('closed');
    }
    else {
        console.log(e);
    }
    e.target.close();
});

document.getElementById("btn").onclick = e => {
    fetch('http://localhost:8080/test').then( data => console.log(data)).catch(data => console.log(data));
};

Immediately, an error is created before we can click the button to generate an event.

What could be wrong?

A: What does your Spring boot terminal say? I think I need that information to address your program's error. By the way allowing cross origin resources sharing for requests from any sources (using wildcard) is a very very bad practice.
One possible reason of error is something's wrong when you create an instance of SSEemitter. (new SSeEmitter(-1L))
SSeEmitter(Long timeout) is creating server side event with set timeout it says. So if timeout is -1, I guess it would immediately be timed out and return timeout response. So it wouldn't be error, just working as written


text:
Q: Tweenmax.to is defined in code, but in browers i got error messages which isn't defined I am trying to make particle with Tweenmax.to which is introduced here : https://youtu.be/eD3qUfc5r5k ( 9:02 )
I just followed this and I think it is defined but for some reason, I got message : it isn't defined.
Since these coding is too complicated and nested in many lines, I hardly recognize what a problem is.
What I've tried is to pull out tweenmax.to and var particle outside of "if" statement, but it didn't work and I don't think it is a problem.
                TweenMax.to(particle, particle.speed, {
                    x1: particle.x0,
                    y1: particle.y0,
                    delay: y / 30,
                    ease: Elastic.easeOut

                });

                particles.push(particle);
            }
        }
    }
    requestAnimationFrame(render);
}

What I expected is just showing up the images like the youtube video. Other than replay button, nothing shows up ;/