text:
Q: System.ArgumentException: 'No mapping exists from object type System.Windows.Forms.DateTimePicker to a known managed provider native type.' con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=N:\ASI report\asiemp.mdf;Integrated Security=True;Connect Timeout=30;");
con.Open();
cmd = new SqlCommand("INSERT INTO salestable (salesid,empid,salesdate,revenu,gp,shipping) values(next value for MyFirstSequence, @empid, @salesdate, @revenu, @gp, @shipping) ", con);
cmd.Parameters.Add("@empid", txtempid.Text);
cmd.Parameters.Add("@salesdate", datep1);
cmd.Parameters.Add("@revenu", txtrev.Text);
cmd.Parameters.Add("@gp", txtgp.Text);
cmd.Parameters.Add("@shipping", txtship.Text);
cmd.ExecuteNonQuery();

A: This line
cmd.Parameters.Add("@salesdate", datep1);

tries to create a parameter whose value is a DateTimePicker. The Sql Server doesn't know what a DateTimePicker is. You need the DateTime value of the DateTimePicker
cmd.Parameters.Add("@salesdate", datep1.Value);

Also I recommend you to use the overload of Parameters.Add where you can specify the datatype of the parameter
cmd.Parameters.Add("@salesdate", SqlDbType.DateTime).Value = datep1.Value;


text:
Q: Changing position of axes in Axes3D I am using mplot3d from the mpl_toolkits library. When displaying the 3D surface on the figure I'm realized the axis were not positioned as I wished they would.
Let me show, I have added to the following screenshot the position of each axis:

Is there a way to change the position of the axes in order to get this result:

Here's the working code:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

ax = Axes3D(plt.figure())
def f(x,y) :
    return -x**2 - y**2

X = np.arange(-1, 1, 0.02)
Y = np.arange(-1, 1, 0.02)
X, Y = np.meshgrid(X, Y)
Z = f(X, Y)
ax.plot_surface(X, Y, Z, alpha=0.5)

# Hide axes ticks
ax.set_xticks([-1,1])
ax.set_yticks([-1,1])
ax.set_zticks([-2,0])

ax.set_yticklabels([-1,1],rotation=-15, va='center', ha='right')

plt.show()

I have tried using xaxis.set_ticks_position('left') statement, but it doesn't work.

A: No documented methods, but with some hacking ideas from https://stackoverflow.com/a/15048653/1149007 you can.
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = ax = fig.add_subplot(111, projection='3d')
ax.view_init(30, 30)

def f(x,y) :
    return -x**2 - y**2

X = np.arange(-1, 1, 0.02)
Y = np.arange(-1, 1, 0.02)
X, Y = np.meshgrid(X, Y)
Z = f(X, Y)
ax.plot_surface(X, Y, Z, alpha=0.5)

# Hide axes ticks
ax.set_xticks([-1,1])
ax.set_yticks([-1,1])
ax.set_zticks([-2,0])

ax.xaxis._axinfo['juggled'] = (0,0,0)
ax.yaxis._axinfo['juggled'] = (1,1,1)
ax.zaxis._axinfo['juggled'] = (2,2,2)

plt.show()

I can no idea of the meaning of the third number in triples. If set zeros nothing changes in the figure. So should look in the code for further tuning.
You can also look at related question Changing position of vertical (z) axis of 3D plot (Matplotlib)? with low level hacking of _PLANES property.

A: Something changed, code blow doesn't work, all axis hide...
ax.xaxis._axinfo['juggled'] = (0,0,0)
ax.yaxis._axinfo['juggled'] = (1,1,1)
ax.zaxis._axinfo['juggled'] = (2,2,2)

I suggest using the plot function to create a graph

redpajama_set_name: RedPajamaStackExchange


text:
Q: trace a route avoiding a street ¿is't possible to trace a route with GPS location from point A (the GPS location of user) to point B (a marker given by the user), ¡¡but!!, avoiding a street on google maps API?
i have half of this, i know how to trace A to B with GPS location on google maps api doing a click on some button, but im not sure if i can avoid some street.
This is an example of what i want to do, assuming the blue marked street is the one that i cant cross


text:
Q: How to click few buttons with same xpath, class I have a problem clicking every button on the LinkedIn page. In some profiles which contain a lot of information about job experience, schools, license we have to expand this information by click on 'Show more button".
Sample profile 1
Sample profile 2
I try many things like searching for elements by Xpath and then looping them to click every button on the page but it didn't work - because every button class is the same as other elements that we can find using selenium. I figure it that first "show more" button is always for experiane section and that code make job to click it:
self.driver.execute_script("arguments[0].click();", WebDriverWait(
            self.driver, 3).until(EC.element_to_be_clickable((By.XPATH, "//li-icon[@class='pv-profile"
                                                                        "-section__toggle-detail-icon']"))))

Then we have the education section, license, and certification section - this makes me trouble. Temporary solution is to click at element that contain string:
self.driver.find_element_by_xpath("//*[contains(text(), 'Pokaż więcej')]").click()

OR
self.driver.find_element_by_xpath("//*[contains(text(), 'Pokaż 1 uczelnię więcej')]").click()

Sooner than later I know that code has a lot of limitations. Does anyone have a better idea of how to solve this problem?
Solution
containers = self.driver.find_elements_by_xpath("//li-icon[@class='pv-profile-section__toggle-detail-icon']")
    for button in containers:
        self.driver.execute_script('arguments[0].click()', button)

A: I tested page with own code and it seems you can get all buttons with
items = driver.find_elements(By.XPATH, '//div[@class="profile-detail"]//button')

for item in items:
    driver.execute_script("arguments[0].click();", item)

But there can be other problem. Page uses "lazy loading" and it may need to use JavaScript code which scrolls down to load all component.

Here is my full code with some ideas in comments.
I tried also select buttons in sections but not all methods work.
But maybe it will be useful for other ideas.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import time

USERNAME = 'XXXXX'
PASSWORD = 'YYYYY'

url = 'https://www.linkedin.com/in/jakub-bialoskorski/?miniProfileUrn=urn%3Ali%3Afs_miniProfile%3AACoAABp5UJ8BDpi5ZwNGebljqDlYx7OXIKgxH80'

driver = webdriver.Firefox()

# -------------------------------------

driver.get(url)
time.sleep(5)

#wait = WebDriverWait(driver, 10)

cookies = driver.find_element(By.XPATH, '//button[@action-type="ACCEPT"]')
cookies.click()
time.sleep(1)

link = driver.find_element(By.XPATH, '//p[@class="authwall-join-form__subtitle"]/button')
link.click()
time.sleep(1)

login_form = driver.find_element(By.XPATH, '//div[@class="authwall-sign-in-form"]')
time.sleep(1)

username = login_form.find_element(By.XPATH, '//input[@id="session_key"]')
username.send_keys(USERNAME)
password = login_form.find_element(By.XPATH, '//input[@id="session_password"]')
password.send_keys(PASSWORD)
time.sleep(1)

#button = login_form.find_element(By.XPATH, '//button[@type="submit"]')
button = login_form.find_element(By.XPATH, '//button[contains(text(), "Zaloguj się")]')
button.click()
time.sleep(5)

# -------------------------------------

url = 'https://www.linkedin.com/in/jakub-bialoskorski/?miniProfileUrn=urn%3Ali%3Afs_miniProfile%3AACoAABp5UJ8BDpi5ZwNGebljqDlYx7OXIKgxH80'

#from selenium.webdriver.common.action_chains import ActionChains

driver.get(url)
time.sleep(5)

# -----------

print('... scrolling for lazy loading ...')

last_height = 0
while True:

    driver.execute_script("window.scrollTo(0, window.scrollY + window.innerHeight);")
    time.sleep(2)

    new_height = driver.execute_script("return window.scrollY")
    if new_height == last_height:
        break
    last_height = new_height

# -----------

def click_items(items):
    for item in items:
        print('text:', item.text)

        #print(item.get_attribute('innerHTML'))

        #print('... scrolling ...')
        #ActionChains(driver).move_to_element(item).perform()

        print('... scrolling ...')
        driver.execute_script("arguments[0].scrollIntoView(true);", item)

        #print('... clicking ...')
        #item.click()
        #time.sleep(1)

        print('... clicking ...')
        driver.execute_script("arguments[0].click();", item)
        time.sleep(1)

        print('----')

print('\n>>> Pokaż <<<\n')

#items = driver.find_elements(By.XPATH, '//button[contains(text(), "Pokaż")]')
#click_items(items)

print('\n>>> Doświadczenie - Pokaż więcej <<<\n')

#section = driver.find_elements(By.XPATH, '//section[@id="experience-section"]')
#items = driver.find_elements(By.XPATH, '//button[contains(text(), "zobacz wi")]')
items = driver.find_elements(By.XPATH, '//button[contains(@class, "inline-show-more-text__button")]')
click_items(items)

print('\n>>> Umiejętności i potwierdzenia - Pokaż więcej  <<<\n')

#section = driver.find_elements(By.XPATH, '//section[@id="experience-section"]')
items = driver.find_elements(By.XPATH, '//button[@data-control-name="skill_details"]')
click_items(items)

print('\n>>> Wyświetl <<<\n')

items = driver.find_elements(By.XPATH, '//button[contains(text(), "Wyświetl")]')
click_items(items)

print('\n>>> Rekomendacje <<<\n')

items = driver.find_elements(By.XPATH, '//button[@aria-controls="recommendation-list"]')
click_items(items)

print('\n>>> Osiągnięcia <<<\n')

print('--- projects ---')
items = driver.find_elements(By.XPATH, '//button[@aria-controls="projects-expandable-content"]')
click_items(items)

print('--- languages ---')
items = driver.find_elements(By.XPATH, '//button[@aria-controls="languages-expandable-content"]')
click_items(items)

# --- all buttons ---
#items = driver.find_elements(By.XPATH, '//div[@class="profile-detail"]//button')
#click_items(items)


text:
Q: Cloud Foundry with 3 AZ without shared storage I am trying to install Cloud Foundry on three vSphere clusters (one node each) using Bosh without having shared storage. The nodes use their own local storages.
If I use scale-to-one-az.yml file, I can install CF and it works. If I deploy to three AZ, I am getting an error:
Error: CPI error 'Bosh::Clouds::CloudError' with message 'No valid placement found for VM compute and storage requirement' in 'create_vm' CPI method (CPI request ID: 'cpi-717770')

Can I deploy Cloud Foundry with 3 AZ without shared storage?
Additional information:

*

*Cloud Foundry manifest_version: v13.23.0

*Bosh version: version 6.3.1-c44e8a1d-2020-07-09T21:08:12Z

*bosh cloud-config output:

azs:
- cloud_properties:
    datacenters:
    - clusters:
      - AZ01:
          datastore_pattern: node1-datastore
          persistent_datastore_pattern: node1-datastore
          resource_pool: Pool01
      name: DC
  name: z1
- cloud_properties:
    datacenters:
    - clusters:
      - AZ02:
          datastore_pattern: node2-datastore
          persistent_datastore_pattern: node2-datastore
          resource_pool: Pool02
      name: DC
  name: z2
- cloud_properties:
    datacenters:
    - clusters:
      - AZ03:
          datastore_pattern: node3-datastore
          persistent_datastore_pattern: node3-datastore
          resource_pool: Pool03
      name: DC
  name: z3
compilation:
  az: z1
  network: default
  reuse_compilation_vms: true
  vm_type: small-highmem
  workers: 6
disk_types:
- disk_size: 5120
  name: 5GB
- disk_size: 10240
  name: 10GB
- disk_size: 102400
  name: 100GB
- disk_size: 1024000
  name: 1000GB
networks:
- name: default
  subnets:
  - az: z1
    cloud_properties:
      name: LS-Cloud01
    dns:
    - 8.8.8.8
    gateway: x.x.10.1
    range: x.x.10.0/24
    reserved:
    - x.x.10.1-x.x.10.49
    static:
    - x.x.10.50 - x.x.10.60
  - az: z2
    cloud_properties:
      name: LS-Cloud02
    dns:
    - 8.8.8.8
    gateway: x.x.40.1
    range: x.x.40.0/24
    reserved:
    - x.x.40.1 - x.x.40.49
    static:
    - x.x.40.50 - x.x.40.60
  - az: z3
    cloud_properties:
      name: LS-Cloud03
    dns:
    - 8.8.8.8
    gateway: x.x.50.1
    range: x.x.50.0/24
    reserved:
    - x.x.50.1 - x.x.50.49
    static:
    - x.x.50.50 - x.x.50.60
vm_extensions:
- name: cf-router-network-properties
- name: cf-tcp-router-network-properties
- name: diego-ssh-proxy-network-properties
- cloud_properties:
    disk: 51200
  name: 50GB_ephemeral_disk
- cloud_properties:
    disk: 102400
  name: 100GB_ephemeral_disk
vm_types:
- cloud_properties:
    cpu: 2
    disk: 10240
    ram: 4096
  name: minimal
- cloud_properties:
    cpu: 6
    disk: 10240
    ram: 16384
  name: small
- cloud_properties:
    cpu: 6
    disk: 10240
    ram: 65536
  name: small-highmem

Succeeded

A: yes, it can be done.
Storage configuration (node1-datastore, node2-datastore, node3-datastore) and information about the resource pools (Pool01, Pool02, Pool03) and AZ (AZ01, AZ02, AZ03)need to be provided to bosh. My cpi.yml (https://github.com/cloudfoundry/bosh-deployment/blob/master/vsphere/cpi.yml) can be found below:
- name: cpi
  path: /releases/-
  type: replace
  value:
    name: bosh-vsphere-cpi
    sha1: 25c53531bf9efeb86d093c2acded62f638e12f0f
    url: https://bosh.io/d/github.com/cloudfoundry/bosh-vsphere-cpi-release?v=54.1.0
    version: 54.1.0
- name: stemcell
  path: /resource_pools/name=vms/stemcell?
  type: replace
  value:
    sha1: 025432cad0600ee0c05d185bc64b88d250c65de4
    url: https://bosh-core-stemcells.s3-accelerate.amazonaws.com/621.85/bosh-stemcell-621.85-vsphere-esxi-ubuntu-xenial-go_agent.tgz
- path: /resource_pools/name=vms/cloud_properties?
  type: replace
  value:
    cpu: 2
    disk: 40000
    ram: 4096
- path: /networks/name=default/subnets/0/cloud_properties?
  type: replace
  value:
    name: ((network_name))
- path: /instance_groups/name=bosh/jobs/-
  type: replace
  value:
    name: vsphere_cpi
    release: bosh-vsphere-cpi
- path: /instance_groups/name=bosh/properties/director/cpi_job?
  type: replace
  value: vsphere_cpi
- path: /cloud_provider/template?
  type: replace
  value:
    name: vsphere_cpi
    release: bosh-vsphere-cpi
- path: /instance_groups/name=bosh/properties/vcenter?
  type: replace
  value:
    address: ((vcenter_ip))
    datacenters:
    - clusters:
      - ((vcenter_cluster)): {}
      - AZ01:
          resource_pool: Pool01
      - AZ02:
          resource_pool: Pool02
      - AZ03:
          resource_pool: Pool03
      datastore_pattern: ((vcenter_ds))
      disk_path: ((vcenter_disks))
      name: ((vcenter_dc))
      persistent_datastore_pattern: ((vcenter_ds))
      template_folder: ((vcenter_templates))
      vm_folder: ((vcenter_vms))
    password: ((vcenter_password))
    user: ((vcenter_user))
- path: /cloud_provider/properties/vcenter?
  type: replace
  value:
    address: ((vcenter_ip))
    datacenters:
    - clusters:
      - ((vcenter_cluster)): {}
      - AZ01:
          resource_pool: Pool01
      - AZ02:
          resource_pool: Pool02
      - AZ03:
          resource_pool: Pool03
      datastore_pattern: ((vcenter_ds))
      disk_path: ((vcenter_disks))
      name: ((vcenter_dc))
      persistent_datastore_pattern: ((vcenter_ds))
      template_folder: ((vcenter_templates))
      vm_folder: ((vcenter_vms))
    password: ((vcenter_password))
    user: ((vcenter_user))

where vcenter_ds: node1-datastore|node2-datastore|node3-datastore
bosh cloud-config looks following:
azs:
- cloud_properties:
    datacenters:
    - clusters:
      - AZ01:
          resource_pool: Pool01
      name: DC
  name: z1
- cloud_properties:
    datacenters:
    - clusters:
      - AZ02:
          resource_pool: Pool02
      name: DC
  name: z2
- cloud_properties:
    datacenters:
    - clusters:
      - AZ03:
          resource_pool: Pool03
      name: DC
  name: z3


text:
Q: AWS SSM Run Command without keeping in history I am trying to reset AD password of users using AWS SSM.
The only issue with this approach is that the SSM run command keeps a history of run. This history shows the parameters in clear text, which can be an issue with Security.
Is there any way I could trigger a runCommand without keeping a history ?
Or better, is there a way to delete the histoy ?

A: It's not possible to run commands without keeping the history.
You also can't delete historical executions, see AWS docs here: https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-best-practices-delete-resources.htm:
After a command finishes processing, information about it is stored in the Command history tab. You can't delete information from the Command history tab.
I would recommend to put the new password in SSM parameter store as a secure string and fetch the secret from SSM parameter store as a command in the script.
That's AWS recommendation.
https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-param-runcommand.html


text:
Q: Count duplicates and display order of occurence I am attempting to count the number of occurrences of each value within a column and then output the order in which it was found (top to bottom) with unsorted data. I have been unable to find a suitable formula to accomplish this task. Any assistance is greatly appreciated.
Example:
Number     DuplicateIndex
50               1
20               1
30               1
10               1
30               2
40               1
30               3
50               2

A: Try,
=countif(A$2:A2, A2)

, in B2 and fill down.

A: Try,
In B2 and fill down
=unique(A2:A9)

In C2 and fill down
=countif(A$2:A9, B2)


text:
Q: Add user to RDS instance - MySQL DB I'm not used to AWS and how some services actually work but in this exact moment I need to add some users to a MySQL database (RDS service) and allow some IPs to access it, and if someone can help me I really appreciate.
I did some research and found that I can connect to the EC2 instance and access the CLI and that would be enough, but I can't find any running instance in any region.
Thanks for your time.

A: *

*Connect to your RDS instance as the root user, and add an account just like you would with a MySQL database running anywhere else. There is no special AWS procedure here.

*If the database has the "publicly accessible" flag enabled, then you just need to add the IP address to the inbound rules in the Security Group assigned to the RDS instance. If the database is not "publicly accessible" then you won't be able to give access to external IP addresses.


text:
Q: How to set image as wallpaper using Android Phonegap? I'm using Phonegap and Jquery Mobile on an Android app. I need to save an image from URL and set it as a wallpaper.
I found the Phonegap Downloader plugin that can handle the downloading part. Is there a plugin that implemanets "set as wallpaper" functionality?

A: You can create Phonegap Plugin
package com.android.test;
import java.io.IOException;

import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.api.PluginResult.Status;
import org.json.JSONArray;

import android.app.WallpaperManager;
import android.content.Context;

public class testPlugin extends Plugin {
    public final String ACTION_SET_WALLPAPER = "setWallPaper";
    @Override
    public PluginResult execute(String action, JSONArray arg1, String callbackId) {
        PluginResult result = new PluginResult(Status.INVALID_ACTION);
        if (action.equals(ACTION_SET_WALLPAPER)) {
            WallpaperManager wallpaperManager = WallpaperManager.getInstance((Context) this.ctx);
            try {
                wallpaperManager.setResource(R.drawable.ic_launcher);
                result = new PluginResult(Status.OK);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                result = new PluginResult(Status.ERROR, e.getMessage());
            }
        }
        return result;
    }
}

this is javascript file test.js
var TestPlugin = function () {};

TestPlugin.prototype.set = function (ms, successCallback, failureCallback) {
//  navigator.notification.alert("OMG");
    return cordova.exec(successCallback, failureCallback, 'testPlugin', "setWallPaper", [ms]);
};

PhoneGap.addConstructor(function() {
    PhoneGap.addPlugin("test", new TestPlugin());
})

and main file call Plugin
window.plugins.test.set("kaka",
        function () {
            navigator.notification.alert("Set Success");
        },
        function (e) {
            navigator.notification.alert("Set Fail: " + e);
        }
    );

;

with android device permission
<uses-permission android:name="android.permission.SET_WALLPAPER" />

and plugin.xml
 <plugin name="testPlugin" value="com.android.test.testPlugin"/>

while you download image with downloader plugin and save with bitmap. you just call
wallpaperManager.setBitmap(bitmap)

A: Here is how I fixed testPlugin.java. Changes are in bold below.
package com.wizeideas.ImageEvolverApp;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.api.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class testPlugin extends CordovaPlugin {
    public final String ACTION_SET_WALLPAPER = "setWallPaper";
    @Override
    public boolean execute(String action, JSONArray arg1, CallbackContext callbackContext) {
        PluginResult result = new PluginResult(Status.INVALID_ACTION);
        if (action.equals(ACTION_SET_WALLPAPER)) {
            Context ctx = this.cordova.getActivity().getApplicationContext();
            WallpaperManager wallpaperManager = WallpaperManager.getInstance(ctx);
            try {
                InputStream bitmap=null;
                try {
                    bitmap=this.cordova.getActivity().getAssets().open("www/img/" + arg1.getString(0));
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } //reference to image folder

                Bitmap bit=BitmapFactory.decodeStream(bitmap);
                wallpaperManager.setBitmap(bit);
                result = new PluginResult(Status.OK);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                result = new PluginResult(Status.ERROR, e.getMessage());
            }
        }
        callbackContext.sendPluginResult(result);
        return true;
    }
}

You also need to change config.xml file under res/xml to include:
<feature name="testPlugin">
  <param name="android-package" value="com.companyname.yourappname.testPlugin"/>
</feature>


text:
Q: Rails Tutorial: NameError in sessions_helper I am developing a simple application which re-used some of the code of the Sample application of the famous Rail Tutorial of Michael Hartl. More specifically, I am re-using the User model but have re-named it as "Account". I think I have replaced all the references to the User model but somehow can't make my code work. Here is my code:
class Account < ActiveRecord::Base
include Person
include Contact
has_many :coworkers, :class_name => 'Coworker'
has_many :customers, :class_name => 'Customer'
has_many :locations, :class_name => 'Location'
has_many :appointment_types, :class_name => 'AppointmentType'
before_save { self.email = email.downcase }
has_secure_password
attr_accessor :remember_token
validates :password, length: { minimum: 6 }
# rem_notice_hrs
validates :rem_notice_hrs, presence: true
validates :rem_notice_hrs, numericality: true
# rem_text
validates :rem_text, presence: true
# mandatory email:
validates :email, presence: true, length: { maximum: 255 },
        format: { with: VALID_EMAIL_REGEX }

after_initialize :init

private

def init
  if self.new_record?
    if self.rem_notice_hrs.nil?
      self.rem_notice_hrs = 24
    end
    if self.rem_text.nil?
      if self.company.nil?
        self.rem_text = "Dear [customer title: automatic] [customer family name: automatic], this is a reminder of your appointment with %{title} %{family_name} on [date/time]."
      else
        self.rem_text = "Dear [title] [customer family name], this is a reminder of your appointment with %{company} on [date/time]."
      end
    end
    if self.start_day.nil?
      self.start_day = Time.now
    end
  end
end
end

Here is the Session helper:
module SessionsHelper

# Logs in the given user.
def log_in(account)
session[:account_id] = account.id
end

# Returns the current logged-in user (if any).
def current_account
@current_account ||= Аccount.find_by(id: session[:account_id])
end

# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_account.nil?
end
end

Here is the header partial:

<a class="navbar-brand" href=<%= root_path %>>Sample Application®

    <% if logged_in? %>
    <% else %>

<a href=<%= root_path %>>Home

<a href=<%= demo_path %>>Try Demo

<a href=<%= pricing_path %>>Pricing & Sign up

Login

    <% end %>

When I run the code I am getting
NameError in StaticPages#home
Showing /Users/nnikolo/Documents/private/rails_projects/appmate/app/views/layouts/_header.html.erb where line   #6 raised:

undefined local variable or method `Аccount' for #<#<Class:0x007fbc1ede96f8>:0x007fbc1ede8b18>
app/helpers/sessions_helper.rb:10:in `current_account'
app/helpers/sessions_helper.rb:15:in `logged_in?'
app/views/layouts/_header.html.erb:6:in `_app_views_layouts__header_html_erb___3728230762564015047_70222988074560'
app/views/layouts/application.html.erb:20:in `_app_views_layouts_application_html_erb___3720454973504965845_70222923917160'

In other words, for some reason the Session helper cannot recognise the Account class. The same code in the Tutorial works when Account is replaced by User.
Interestingly, when I decided to include the Account model in the SessionsHelper (which I should not need do but I did it just as an experiment) I am getting
wrong argument type Class (expected Module)

You can find more details in this screenshot:

What's the problem? Why can't SessionsHelper see the Account model? In fact, it cannot see any of the models - I replaced "include Account" with "include Reminder" (another ActiveRecord model I have) and I get the same error message. All the models shall be visible to the helper - why is this not the case here?
P.S. I did run migration and I don't think the problem is there but here is the relevant section of the schema.rb:
  create_table "accounts", force: true do |t|
  t.string   "password_digest",                               null: false
  t.string   "remember_digest"
  t.string   "activation_digest"
  t.boolean  "activated",                     default: false
  t.datetime "activated_at"
  t.string   "title"
  t.string   "first_name"
  t.string   "last_name"
  t.string   "company"
  t.string   "email",             limit: 100,                 null: false
  t.integer  "phone",             limit: 8,                   null: false
  t.integer  "rem_notice_hrs",                                null: false
  t.string   "rem_text",          limit: 140,                 null: false
  t.datetime "start_day",                                     null: false
  t.datetime "end_day"
  t.datetime "created_at"
  t.datetime "updated_at"
  end

A: From what it seems, either you havent changed the migration to reflect Account or you havent run the migration for that file. Please share the contents of your schema.rb file.

A: I ended up naming 'Account' as 'User'. Everything works now. Still don't know what was wrong. Seems like there is some sort of rails 'magic' associated with the 'User' name.

A: Account is a class.
SessionsHelper is a Module.
You can't include Account into SessionsHelper because a Class can't be mixed-in a Module. It's the other way round.
That's why you're getting that TypeError at StaticPages#home.


text:
Q: how to update lastest equity when doing backtest in quantstrat I am trying to use quantstrate to do backest. But could not update the lastest equity using "tradeSize=quote(last(getEndEq(acct,Date = timestamp)))" to get the latest total asset. Hope someone could help. I'm search for this for a long time and tried many times but could not make it. Many many thanks!
# long entry
add.rule(strat,name = "ruleSignal",
         arguments = list(sigcol='EntryLongSig',
                          sigval=TRUE,
                          orderside='long',
                          ordertype='market',
                          osFUN=osDollarATR,
                          pctATR=pctATR,
                          TxnFees=-300,
                          replace=F,
                          prefer='Close',
                          tradeSize=quote(last(getEndEq(acct,Date = timestamp))),
                          atrMod='X'),
         type = 'enter',enabled = TRUE,
         label = "enterLong")

A: getEndEq(account.st, timestamp) already gives your total equity at specified datetime POSIXct or numerical timestamp object. Using "last" is unnecessary in this condition.
By the way, rules in quantstrat triggers the orders after the signal occurred(next bar). If you wonder your total equity at signal time (previous bar) to calculate order quantity, please try - for instance minutely bar- :
quote(getEndEq(account.st,timestamp-60))
P.S. Try to give reproducible examples in your next questions.


text:
Q: How to create a Linux executable file using python code For an example I have created welcomeGUI.py file with has a simple GUI as follows using Tkinter.
from Tkinter import *
import ttk

class Application():

    def __init__(self, master):
        frame = Create_widgets(master)
        frame.pack()

class Create_widgets(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)

        self.toplabel = Label(master, text="Welcome!", font=('cambria', 20, 'bold'),
                         fg="white", bg="Midnight Blue")
        self.toplabel.pack(fill=X, ipady=100)

        statuslabel = Label(master, bg="Midnight Blue")
        statuslabel.pack(fill=X)
        self.midlabel = Label(master, text="Device ready,connect a flash drive to continue...",
                         font=('Ubuntu-L', 12), fg= "white", bg="Midnight Blue", anchor="n")
        self.midlabel.pack(fill=X, ipady=5)

        bottomlabel = Label(master, bg="Gainsboro")
        bottomlabel.pack(side=BOTTOM, fill=X)

        button1 = ttk.Button(bottomlabel, text="Close")
        button1.pack(side=BOTTOM)

#**** Main ****

root = Tk()
root.title("Projector Plus")
root.configure(bg="Midnight Blue")
root.minsize(550, 550)

pro = Application(root)

root.mainloop()

Then I need to create this file that can be installed on Ubuntu(To create an executable file on Ubuntu). In Windows this is done very easily with .exe file(Using cx-Freeze). Really I have no idea about the file system of Ubuntu and  shell files.
Please help me to get an idea about this problem. I don't have any idea how to enter this matter.

A: Basically, to make a file executable in Unix systems, you just have to do one thing: allow it to be executed (very surprising ;) ). To do it, you must use the chmod command as follows: chmod +x youfile.py. The +x add the right to be executed.
Now, your system will allow you to execute the script, but for now it's just a simple text file... Ubuntu doesn't know that he must use the python command to run it, so you'll have undermined comportment. To resolve this, we use the sha-bang line (for more information, see the wikipedia page): at the first line of your script, you must write #! program_to_use, in your case it's python. Generally, we take benefit of the env variables, and use #! /usr/bin/env python, but you can also choose yourself the version of python you want, doing #! /usr/bin/pythonX.X where X.X is the version of python.

A: 1 - Add on the top of your file this line:
#!/bin/env python (This may differ depending on your ENV variable)
2 - make your file executable by:
a - In Unix system, run the following command:
      `chmod +x myfile.py`

b - In Windows System, you can use the utility py2exe found on
http://www.py2exe.org/
more on this can be found at:
https://docs.python.org/2/faq/windows.html#how-do-i-make-an-executable-from-a-python-script


text:
Q: what does this code block do in this program? Code:
temp = inp = int(input())
count = 0

while True:
    ten = temp//10
    one = temp%10
    result = ten + one
    count += 1
    temp = int(str(temp%10)+ str(result%10))

    if (inp == temp):
        break
print(count)

I was wondering what temp = int(str(temp%10) + str(result%10))is doing in this code.
This code gets an input from the user, and gets the value of from tens and ones place, adds them, increment count and cycles them by adding the result and the number from the ones place until they become original input.

A: In the line :
 temp = int(str(temp%10) + str(result%10))

First, you are calculating the modulo of temp and result by 10: this gives you 2 numbers. With the str command, you convert the number in string. With the + you are merging the two string one after the other. Then you convert your new string into an integer.
For example if temp = 10 and result = 50
temp % 10 = 1 --> in str '1'
result % 10 = 5 --> in str '5'
You merge the two str: '1'+'5' = '15' --> in int = 15

A: That specific line:

*

*converts two integers into strings

*concatenates the strings

*converts the resulting string back to integer again

Let's say that the user input is 1.

*

*temp would be equal to 1.

*temp % 10 would evaluate to 1.

*result would be equal to (1 // 10) + (1 % 10) = 1.

*result % 10 would be 1.

*If we convert the types of resulting integers from steps 3 and 4 into str, we can just concatenate them with +. The resulting string would be 11 (Because '1' + '1' is '11') An alternative approach to do that would be: f'{temp % 10}{result % 10}'

*Now, passing the resulting string into int() would just convert it into an integer.

Hope this helps.


text:
Q: process memory size solaris Running perl script in solaris 10 machine.  Know the RAM Size is 25 GB.  Have two queries.

*

*Normally How much RAM memory  a solaris process is allocated. Is it a default value assigned to any script or process. where it can be set?   How do i determine how much max  static array size can i have and how much dynamic memory can i allocate? what command i need to issue to find it out what memory allocated to a process in solaris? Is it configurable?

*When the script gives me outofmemory error. Does it mean it used the entire RAM and virtual memory?  Is there any way to know how memory was used when the script threw out ofmemory error?what command i need to issue to find it out in solaris?

A: 1) As much as it requests, up to the limit set by ulimit.   Commands such as pmap and ps can show how much a process has allocated at the current time.
2) It can mean that it used all virtual memory, or that it hit the process limit, or that it's a 32-bit process and hit the 4gb address space limit.  Solaris Application Memory Management provides some more details.


text:
Q: Filter array with multiple properties while catering to undefined terms I need to filter an array by 4 object properties based on user input but sometimes user can choose to enter only 1, 2 or 3 terms which gives undefined on properties the user did not enter.
const myTableData = [
    {
        'date': '2020-05-16',
        'duration': 247,
        'low_temp': 373.0,
        'high_temp': 388.0,
        'type': 'XD'
    },
    {
        'date': '2020-05-27',
        'duration': 246,
        'low_temp': 373.0,
        'high_temp': 388.0,
        'type': 'LB'
    },
    {
        'date': '2020-06-04',
        'duration': 247,
        'low_temp': 374.0,
        'high_temp': 388.0,
        'type': 'LB'
    }
];

export async function filter_click(event) {
    let newArray = myTableData.filter(function (el) {
        return el.duration === Number($w("#duration").value) && el.low_temp === Number($w("#lowtemp").value) && el.high_temp === Number($w("#hightemp").value) && el.type === $w("#type").value;
    });
    $w("#table1").rows = newArray;
}

See if even 1 of the user input elements are not filled it gives an undefined which returns an empty array.
Why I cannot use || instead of &&
If I use the OR '||' operator it doesn't narrow down to ALL the properties asked by the user. Example: If 'duration' is 350 & 'type' is 'LB' and the user types in both it will not return ONLY the objects which have both duration as 350 and type as LB, instead it will return objects having either.

A: It will probably help you a lot when you're trying to work through a problem, to make your code easier to read. Right now you have one massive return line that is super hard to read and understand.
A filter function just needs to return true (at any point) if the evaluated item should be included, and false (at any point) if it should be excluded. So you can evaluate each of your fields, one by one, to see if it fails any of the required conditions and should be excluded, whereupon you return false. Otherwise, at the end of the function, if it passes all the tests you know it should be included and return true (the "base case"). This kind of inverse filtering where you test for cases to exclude rather than cases to include can often be much easier to write, read, and reason about.
I would also write the filter function itself as a separate function to make it more clear, easier to read, and easier to maintain.
// Exclude compared item if it fails any of the "tests"
// Otherwise include it (return true)
function filterTable(el) {
  if (el.duration !== Number($w("#duration").value) || el.duration === undefined) {
    return false;
  }
  if (el.low_temp !== Number($w("#lowtemp").value) || el.low_temp === undefined) {
    return false;
  }
  // etc. for each field to be compared

  // Base case - by this point it has passed all tests and should be included
  return true;
}

export async function filter_click(event) {
    let newArray = myTableData.filter(filterTable);
    $w("#table1").rows = newArray;
}

A: Few points

*

*Cache your elements and don't do expensive dom lookups inside your Array.filter()

*Parse your params so you not doing unnecessary casting inside your Array.filter()

*Build up your params and pass them in the correct format to your filter function.

*If a param has been included - test against current filter item, otherwise ignore it

This way you are not doing expensive lookups and casting on every iteration in the filter. You don't need to consider properties unless the associated param has been included.
Snippet:

const myTableData = [{
    'date': '2020-05-16',
    'duration': 247,
    'low_temp': 373.0,
    'high_temp': 388.0,
    'type': 'XD'
  },
  {
    'date': '2020-05-27',
    'duration': 246,
    'low_temp': 373.0,
    'high_temp': 388.0,
    'type': 'LB'
  },
  {
    'date': '2020-06-04',
    'duration': 247,
    'low_temp': 374.0,
    'high_temp': 388.0,
    'type': 'LB'
  }
];

window.addEventListener('load', () => {
  // cache the elements to avoid expensive lookups in your filter
  const $duration = document.querySelector('#duration');
  const $lowtemp = document.querySelector('#lowtemp');
  const $hightemp = document.querySelector('#hightemp');
  const $type = document.querySelector('#type');

  const filterData = (params) => {
    return myTableData.filter((item) => {
      // if we have duration, check it
      if (params.duration && item.duration !== params.duration) {
        return false;
      }

      // if we have lowtemp, check it
      if (params.low_temp && item.low_temp !== params.low_temp) {
        return false;
      }

      // if we have hightemp, check it
      if (params.high_temp && item.high_temp !== params.high_temp) {
        return false;
      }

      // if we have type, check it
      if (params.type && item.type.toLowerCase() !== params.type) {
        return false;
      }

      // include this item
      return true;
    });
  }

  document.querySelector('#filter').addEventListener('click', (e) => {
    // build up the params to filter by
    const params = {};

    if ($duration.value) {
      // parse to int
      params.duration = parseInt($duration.value);
    }

    if ($lowtemp.value) {
      // parse to float
      params.low_temp = parseFloat($lowtemp.value);
    }

    if ($hightemp.value) {
      // parse to float
      params.high_temp = parseFloat($hightemp.value);
    }

    if ($type.value) {
      // convert to lowercase for comparison
      params.type = $type.value.toLowerCase();
    }

    console.info(filterData(params).length);
  });

  // few tests below
  let params = {};
  console.info(filterData(params).length === 3);

  params = {
    duration: 246
  };
  console.info(filterData(params).length === 1);

  params = {
    duration: 247
  };
  console.info(filterData(params).length === 2);

  params = {
    duration: 247,
    low_temp: 373.0
  };
  console.info(filterData(params).length === 1);

  params = {
    low_temp: 374.0,
    high_temp: 388.0
  };
  console.info(filterData(params).length === 1);

  params = {
    type: 'lb',
  };
  console.info(filterData(params).length === 2);

  params = {
    high_temp: 388.0,
  };
  console.info(filterData(params).length === 3);
});
<input id="duration" value="246" />
<input id="lowtemp" value="373.0" />
<input id="hightemp" value="388.0" />
<input id="type" value="LB" />
<button id="filter">filter</button>

A: how about a for loop and a bool array?
for (i = 0; i<array.length; i++)
     if thing != array[i]:
          bool[i] = false

for (each in bool):
    if each == false:
         do something;


text:
Q: Grouping with Linq only when all elements in a group have value in a column I try to create groupings of lastReadings, where I can create client's and competitor's prices. I try below code, but this approach does not eliminate the readings that are only Client's. With below table I need to eliminate the readingsId 5 and 6, for products C and D as there is no match and pass further only the comparable ones.
readingId   ProductId     Distributor   Price
1           A             Competitor    8.0
2           A             Client        8.1
3           B             Competitor    8.3
4           B             Client        8.4
5           C             Client        8.8
6           D             Client        8.9

Below is what I get so far:
    private IEnumerable<PriceComparison> getPriceComparisons(string competitor)
    {
        IEnumerable<IGrouping<string, LatestReading>> groupingsByProductId =
                            from latestReading in LatestReadings
                            group latestReading by latestReading.ProductId;

        IEnumerable<PriceComparison> priceComparisons
            = from grouping in groupingsByProductId
              select new PriceComparison
              {
                  ProductId = grouping.Key,
                  MyPrice = (from latestReading in grouping
                             where latestReading.Distributor == Client
                             select latestReading.Price).FirstOrDefault(),
                  CompetitorPrice = (from latestRading in grouping
                                     where latestRading.Distributor == competitor
                                     select latestRading.Price).FirstOrDefault()
              };
        return priceComparisons;
    }

Actually as I write this post, I concluded that for the additional created groupings with "no competitor", competitor price is there as 0, so later I can easily eliminate such groupings and the code works. But somehow this approach of creating "empty" groupings does not feel right, is there a better way to only focus on the groupings excluding products C and D?

A: I think the Join is more suitable for what you are trying to achieve, like this
var priceComparison =
    from a in LatestReadings.Where(r => r.Distributor == Client)
    join b in LatestReadings.Where(r => r.Distributor == Competitor)
        on a.ProductId equals b.ProductId
    select new PriceComparison
    {
        ProductId = a.ProductId,
        MyPrice = a.Price,
        CompetitorPrice = b.Price
    };

A: You can do something like this:
//...

IEnumerable<PriceComparison> priceComparisons =
              from grouping in groupingsByProductId
              where grouping.Any(p => p.Distributor == Client)
                  && grouping.Any(p => p.Distributor == competitor)
              select new PriceComparison
              {
                 //..
              };

This makes sure that you get only the groups that have a price for both Client and Competitor.


text:
Q: Cassandra says "InvalidQueryException: Invalid version for TimeUUID type" when saving java.util.UUID I'm trying to save java.util.UUID to Cassandra column of type timeuuid. For example, that is a default spring-data-cassandra mapping: http://docs.spring.io/spring-data/cassandra/docs/current/reference/html/#mapping-conversion .
Value of UUID is generated by java.util.UUID#randomUUID()
I get an exception:
"com.datastax.driver.core.exceptions.InvalidQueryException: Invalid version for TimeUUID type"
Studying code at https://svn.apache.org/repos/asf/cassandra/trunk/src/java/org/apache/cassandra/db/marshal/TimeUUIDType.java reveals the reason:
    @Override
    public void validate(byte[] bytes)
    {
        if (bytes.length != 16 && bytes.length != 0)
            throw new MarshalException(String.format("TimeUUID should be 16 or 0 bytes (%d)", bytes.length));
        // version is bits 4-7 of byte 6.
        if (bytes.length > 0)
            if ((bytes[6] & 0xf0) != 0x10)
                throw new MarshalException("Invalid version for TimeUUID type.");
    }

A: That means that Cassandra timeuuid type accepts only time-based UUIDs. Value that is generated by java.util.UUID#randomUUID() is type 4 (pseudo randomly generated) UUID and does not pass validation.
So TimeUUID class works as expected, but the exception cause is not so obvious.
Possible workarounds:

*

*
You should insert the timeuuid generated via datastax driver. In your case , since you are using version 1 timeuuid, you must use    UUIDs.timeBased() .

Source: https://stackoverflow.com/a/23198388

*Or if you are mapping entity through spring-data-cassandra and need to save UUIDs supplied by third-party, add to entity field the annotation @CassandraType(type = DataType.Name.UUID)


text:
Q: Microservice deployment in Kubernetes by node wise I am trying to deploy my set of microservices in different nodes. For installing kubeadm and creation of clusters I am following the below documentations.

*

*https://medium.com/@SystemMining/setup-kubenetes-cluster-on-ubuntu-16-04-with-kubeadm-336f4061d929

*https://medium.com/@Grigorkh/install-kubernetes-on-ubuntu-1ac2ef522a36

*https://www.youtube.com/watch?v=b_fOIELGMDY&t=108s
I need one master with 2 worker machines. I got clear idea about how to create the kubernetes clusters.
My requirements:  I have an application which has separate set of microservices. I need to deploy docker images for one set of microservices into one node1.And docker images for other set into node2. And 3 rd set of microservices in node3...etc...This is my planning of deployment. Please correct me if I am going in wrong direction, Since I only started exploration in docker, kubernetes and jenkins. Devop.
My confusions:

*

*According to my requirement region wise deployment by nodes , Is this deployment strategy is possible by Kubernetes ?  And is this one of the standard way ?

*If I am using Jenkins for implementing CI/CD pipeline , then Do I need to install Jenkins in each Vm? Means master machine and also in machine which resides nodes?

These all are my confusion about this Kubernetes deployment. Please correct me if my thoughts are wrong, since I am only a beginner in DevOp world. How can I clarify my doubts about deployment by using Kubernetes ?

A: To answer your first question - you basically need to allocate each node for a tenant. If there are compliance/regulatory reasons then you should do it (Though it won't be very efficient). Here is how you can do it:
On the node1 add a taint:
kubectl taint nodes node1.compute.companyname.com reservedfor=tenant1:NoSchedule

What above means is that the node1 will only schedule pods which have a matching toleration and not any other pod. For the microservice which you need to schedule on node1, you will have to add a toleration to the pod YAML file like:
tolerations:
- key: "reservedfor"
  operator: "Equal"
  value: "tenant1"
  effect: "NoSchedule"

The same logic can be extended - so that even if tenant1 needs 4 machines, then all the 4 machines can be tainted with above key value pair and then pods can be tolerated on those nodes. Check out the documentation here and blog with an example here
You can also use the pod/node affinity to achieve above.
Your second question on Jenkins - No, you don't need to install Jenkins on each node, but other than that more details are needed for that question.


text:
Q: toast output, float decimal formatting? the only way I know how to output float into 3 decimal places goes something like this...
DecimalFormat var = new DecimalFormat("#.###");
Toast.makeText(this,"number equals"+var.format(number),Toast.LENGTH_SHORT).show();

could i put something like the %.3f or %3f in Toast
i tried "number equals"+number%3f and "number equals"+number%.3f
which messes up the value

A: I think the only other real way you could do this is something like this:
float number = (float)Math.round(oldNumber * 1000) / 1000;
string formattedNumber = Float.toString(number);

That will round to 3 decimal places. However I can't see why this would help you, what you've got is more than adequate.

A: there is no notation like %.3f supported into android, so whereever, you need formatting you need to use DecimalFormat.


text:
Q: igraph edge between two vertices I'm new to R and igraph and I was wondering if anybody can help me with the following.
I want to find the edge weight between two vertices in a graph. My graph structure is defined by the normal  ego (node1), alter (node2) and the weight of the edge between them.
I know that I can get the weight for each of the edges in the list of edges that originate from node number 5 using E(igraph_friendship) [ from(5) ]$weight
And that I can find the weight for each of the edges in the list of edges that end onto node number 10 using E(igraph_friendship) [ to(10) ]$weight
But what if I simply want to find the weight of the edge that simple connects just node 5 and node 10?
Alternatively, if I can get the identifier of the edge that connects node 5 and 10 in the list of all edges, E(igraph_friendship), that would work too.
Thanks a lot for your help, I've been looking around a lot for it and I really appreciate your help!

A: This is actually quite easy in igraph 0.6 and above, because you can
treat the graph as if it was an adjacency matrix (or weighed adjacency
matrix in your case):
library(igraph)
g <- graph.ring(10)
g[1,2]
# [1] 1
E(g)$weight <- runif(ecount(g))
g[1,2]
# [1] 0.8115639

If you want to do this for the whole matrix, then you can simply do
g[]

Or, if you don't want sparse matrices, then
g[sparse=FALSE]

Please see ?"[.igraph" for more.

A: Gabor's use of the adjacency matrix helped. However, it took me a while to figure out how to get my edge lists with weights into an adjacency matrix. I tried to do it the usual way using graph.data.frame but then would get a weird error when I tried translating the igraph object to and adjacency matrix (error: Error in .M.kind(x) : not yet implemented for matrix w/ typeof character). This post helped do the trick: https://sites.google.com/site/daishizuka/toolkits/sna/weighted-edgelists.
However, what I found out from the R help email list help to work best was this simple operator directly on the igraph object: E(g)[5 %--% 10]$weight. See http://igraph.sourceforge.net/doc/R/iterators.html for details


text:
Q: Should there be some kind of consequence for users who incorrectly close a thread that is ultimately reopened? I just had a thread marked as a duplicate by a user, who didn't seem to have read the content of the post, and left a "Read the documentation." comment,  without even giving any additional explanation.
The post then got enough votes to be re-opened after other users pointed out that the proposed dupe wasn't the same problem.
My problem was eventually solved, but I couldn't help but wonder if users should get some sort of notice or warning for incorrectly closing a post that is eventually reopened?

A: No, there will never be a 'punishment' over closing a post that was subsequently reopened again.
There will always be controversial subjects, where not everyone agrees on wether something is a duplicate or not. And sometimes mistakes are made, but that doesn't mean those mistakes were malicious deserving of punishment. Note that voting to close doesn't gain you anything, other than a cleaner, tidier site!
This is why we have a reopen process too.

A: I'm a strong supporter of voting to close bad questions and duplicates.
The problem with punishment of users who voted to close a question and then is later reopened is that there really is not a programmatic way to judge the quality of the post when it was closed, and then when it was reopened.
For example, a question could be a duplicate of another question, but then the questioner could edit his question to be more specific and primarily about another issue rather than the duplicate question.
As another example, a user could ask a question but not show any relevant code for answerer to diagnose the problem. So the question should be closed. But then if the user edit's his question to include the necessary relevant code, then it should be reopened.
So as you can see, just because a question was closed then reopened, doesn't mean that voting to close in the first place was the wrong choice.

I do agree that there should be some query that mods run that let them know if a user has an extremely high percentage of closed questions being reopened, but they would have to go through them manually to see if maybe that user should receive a suspension or something.

A: Not at the moment.
People make mistakes from time to time and closing a question is not a permanent thing so it I don't think it would productive to "punish" users for this.
It might be worth looking at presenting the user with a warning if a certain proportion of the questions they had voted to close were reopened, but I don't think it would be worth the benefit.


text:
Q: Conditional routing in Angular I have a route:
    {
        path: 'business-rules',
        data: { routeName: _('Business rules') },
        component: BusinessRulesComponent,
    },

And I'm developing a new component that will replace the BusinessRulesComponent at some point. Users can opt in to the new NewBusinessRulesComponent by using a feature flag.
Now I'm wondering if it's possible to do conditional routing based on the selected feature flag.
I've added a guard CanAccessNewBusinessRules but as far as I know this can only stop a route from showing up:
    {
        path: 'business-rules',
        data: { routeName: _('Business rules') },
        component: BusinessRulesComponent,
        canActivate: [CanAccessNewBusinessRules]
    },

CanAccessNewBusinessRules:
        const new_business_rules_flagged = await this.companyFeatureFlagsService.getAllFeatureFlags(company.id)
            .then((flags) => flags.includes(possibleFlags.new_business_rules))

        if (new_business_rules_flagged) {
            // this.router.navigate(['new-business-rules'])
            return false;
        }

        return true;

Can I change the routing in the guard, or is it better to add another route that's only active when the flag is enabled?

A: No. you can't do it. A good way to handle situations like this is to return UrlTree from your guard so angular can route to another route.
app-routing.module.ts
  {
    path: 'page',
    loadChildren: () => import('./pages/home/home.module').then(m => m.HomeModule),
    canActivate: [ProfileGuard]
  },
  {
    path: 'page2',
    loadChildren: () => import('./pages/another/another.module').then(m => m.AnotherModule),
  }

and then in your guard decide that first route(page) can activate or you need to navigate to page2
profile.gurad.ts
 if (!condition) {
   return this.router.parseUrl('/page2');
 }
 return true;


text:
Q: Getting error on running a multi-module project in IntelliJ IDEA I am making a maven project in IntelliJ IDEA Ultimate edition 2020.2. It is a multi-module project. When I run a class from one of the module I get an error but it runs fine if I run from the packaged jar. Here is the Structure of application:
C:.
| pom.xml
|
+---DatabaseTier
|   |   pom.xml
|   |
|   +---src
|   |   \---main
|   |       +---java
|   |       |   |   module-info.java
|   |       |   |
|   |       |   \---org
|   |       |       \---Geek8080
|   |       |           |   DatabaseTest.java
|   |       |           |
|   |       |           \---service
|   |       |               \---database
|   |       |                   |   Database.java
|   |       |                   |
|   |       |                   \---entities
|   |       |                           JournalPage.java
|   |       |
|   |       \---resources
|   |               log4j2.xml
|   |               table.sql
|   |
|   \---target
|       +---classes
|       |   |   log4j2.xml
|       |   |   module-info.class
|       |   |   table.sql
|       |   |
|       |   \---org
|       |       \---Geek8080
|       |           |   DatabaseTest.class
|       |           |
|       |           \---service
|       |               \---database
|       |                   |   Database.class
|       |                   |
|       |                   \---entities
|       |                           JournalPage.class
|       |
|       \---generated-sources
|           \---annotations
\---Reports
    |   pom.xml
    |
    +---src
    |   +---main
    |   |   +---java
    |   |   |   |   module-info.java
    |   |   |   |
    |   |   |   \---org
    |   |   |       \---Geek8080
    |   |   |           |   ReportTest.java
    |   |   |           |
    |   |   |           \---service
    |   |   |               \---report
    |   |   |                       ExcelReports.java
    |   |   |                       PDFReports.java
    |   |   |
    |   |   \---resources
    |   |           log4j2.xml
    |   |           MTCORSVA.TTF
    |   |
    |   \---test
    |       \---java
    \---target
        +---classes
        |   |   log4j2.xml
        |   |   module-info.class
        |   |   MTCORSVA.TTF
        |   |
        |   \---org
        |       \---Geek8080
        |           |   ReportTest.class
        |           |
        |           \---service
        |               \---report
        |                       ExcelReports.class
        |                       PDFReports.class
        |
        \---generated-sources
            \---annotations

This is the main pom.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <groupId>org.Geek8080</groupId>
        <artifactId>Journal</artifactId>
        <packaging>pom</packaging>
        <version>1.0</version>

        <modules>
            <module>DatabaseTier</module>
            <module>Reports</module>
        </modules>

        <name>Journal Daily</name>

        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>11</maven.compiler.source>
            <maven.compiler.target>11</maven.compiler.target>
        </properties>

        <dependencies>
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-api</artifactId>
                <version>2.13.3</version>
            </dependency>
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
                <version>2.13.3</version>
            </dependency>
        </dependencies>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                    <configuration>
                        <source>11</source>
                        <target>11</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>3.1.1</version>
                    <executions>
                        <execution>
                            <id>copy-dependencies</id>
                            <phase>package</phase>
                            <goals>
                                <goal>copy-dependencies</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                                <overWriteReleases>false</overWriteReleases>
                                <overWriteSnapshots>false</overWriteSnapshots>
                                <overWriteIfNewer>true</overWriteIfNewer>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </project>

The pom.xml in DatabaseTier module:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>Journal</artifactId>
        <groupId>org.Geek8080</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>DatabaseTier</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.15.2.0</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>org.Geek8080.DatabaseTest</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id> <!-- this is used for inheritance merges -->
                        <phase>package</phase> <!-- bind to the packaging phase -->
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

The pom.xml in Reports module:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>Journal</artifactId>
        <groupId>org.Geek8080</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Reports</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.Geek8080</groupId>
            <artifactId>DatabaseTier</artifactId>
            <version>1.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.21</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>org.Geek8080.ReportTest</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id> <!-- this is used for inheritance merges -->
                        <phase>package</phase> <!-- bind to the packaging phase -->
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

This is the error I am getting:

Error occurred during initialization of boot layer
java.lang.LayerInstantiationException: Package org.Geek8080 in both
module Reports and module DatabaseTier
Process finished with exit code 1

A: It speaks for itself pretty much

Package org.Geek8080 in both module Reports and module DatabaseTier

such that with the module system in place and explicit modules on the modulepath, no two modules can export the same package. This change was brought in the light of moving towards reliable configuration and better accessibility. More to read about those concepts could be found in The State of the Module System.
As a solution, you can rename the packages to org.report.Geek8080 and org.database.Geek8080 respectively in those modules.


text:
Q: Reverting Git Stash Pop I executed git stash pop twice instead of once and am now getting the following warning.
Unmerged paths:
  (use "git restore --staged <file>..." to unstage)
  (use "git add <file>..." to mark resolution)
    both modified:   package-lock.json
    both modified:   static_compiled/img/about-bg.jpg
    both modified:   static_compiled/img/contact-bg.jpg
    both modified:   static_compiled/img/home-bg.jpg
    both modified:   static_compiled/img/logo.png
    both modified:   static_compiled/img/post-bg.jpg
    both modified:   static_compiled/img/post-sample-image.jpg

Is there a way to revert the second pop?

A: As a general rule: no.  This is one of my many objections to git stash (not just to git stash pop, which is a particularly egregious offender, but to the entire git stash subsystem).
For some specific cases, if you can find the second diff that was applied, you can reverse-apply it.  Unfortunately, you've hit a conflict case and that's one of the specific cases where this doesn't work.  You're thus squarely in the general "no" case.
In the future, consider using git stash apply.  That means do the apply step, but don't do the drop step yet.  The git stash pop command means do the apply, and then if you, Git, think the apply went well, do the drop too.  It's the drop step that "loses" the effect that you got from the "apply" step and makes it difficult to un-apply in those (not all that rare, but also not all that common either) special cases where a reverse-apply / un-apply would work.  But that doesn't help you with what you are stuck with now.


text:
Q: RoR + Paperclip - Have two objects reference same paperclip image I'm creating a demo portion to my website. Where each new demo account generates dummy data. The dummy data includes images. It takes way too long and takes up unnecessary space when creating these dummy images though. They are just copies of images that already exist in the database.
I have an Image object with the relationship has_attached_file :pc_image. I want a new image to reference the pc_image in an old image, not create a duplicate. I've been trying something like this (p statements added to show the difference), but it just won't work:
p old_image
=> images/001/original/old_image.jpg

new_image.pc_image = old_image.pc_image
new_image.save
p new_image
=> images/002/original/old_image.jpg

Notice the ID after images... 001 and 002. Paperclip seems to automatically create a new URL using the ID of its parent object instead of using the old URL. It doesn't duplicate the images though, which is what I want. But I'm getting a missing image in the view because the pc_image URL is pointing to an image that was never created instead of pointing to the old_image URL, which is what I want. Is this possible? Is there a good workaround?


text:
Q: How to show an empty row in BootstrapVue's b-table I am using a b-table from BootstrapVue. However, when the array of objects for my table is empty, i want to show the table headers + 1 empty row, without any text in the cells of the table.
On BoostrapVue's b-table page, there is some explanation about showing something for an empty table, but i'm not following the explanation. There is also no visual of the outcome.
When using show-empty, it gives a simple text 'no records ...', but i don't want the text. Or maybe i want a custom text (depending on the language when using i18n).
So the html is currently:

And in the vue data i have:
dogs: [], //because i want to mimic an empty table
dogHeaders: ['name','color','age'],

Can someone show me an example how to do this?
edit: i currently see only a workaround with populating my dogs array with an empty dog like so:
dogs: [{name:'',color:'',age:''}],

But i guess there should be a better way (+ this workaround gives a row that has less height than an actual filled row)

A: You could use b-table with show-empty attribute and slots. I prepared a code snippet to show this:

new Vue({
  el: '#app',
  data: {
    dogs: [],
    dogHeaders: ['name', 'color', 'age'],
  }
})
<link href="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" />

    <template #empty="scope">
        Empty row
    </template>

A: I think the example is right there in the docs. They provide slots for exactly this use case, where you can put anything you want:

    <template #empty="scope">
        Whatever HTML you put here will be shown when the table is empty
    </template>

A: Since you want to render actual cells, you can use the top-row slot instead of the standard empty slot.
You can then conditionally render the slot using a v-if, based on whether the dogs array is empty or not.
Then render empty cells () inside the slot for each element in your dogHeaders array.

new Vue({
  el: '#app',
  data() {
    return {
      dogs: [],
      dogHeaders: ['name', 'color', 'age']
    }
  },
  methods: {
    addRow() {
      this.dogs.push({
        name: 'Pence',
        color: 'Black',
        age: 53
      })
    }
  }
})
<link href="https://unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet" />

  Reset Table
  Add row

    <template #top-row v-if="dogs.length === 0">

    </template>


text:
Q: Retained variable not being retained I am trying to sum up a variable using retain based on certain conditions. I have these fields account_id, date, transaction, value and transaction_type.
The data is sorted by account_id and date
I want to sum up value until the first transaction_type not in ('A')
I have this
data dset;
    set dset;
    by account_id;
    retain sum_flag sum;
    if first.account_id then do;
        sum_flag = 1;
        sum=0;
    end;
    if transaction_type not in ('A') then sum_flag = 0;
    if sum_flag = 1 then sum=sum +value;
run;

My issue is if the first transaction_type in A then it works fine but if the next transaction_type is also A sum_flag is set to . instead of being kept as 1. Why is this happening?
I think it's something to do with
       if transaction_type not in ('A') then sum_flag = 0;
Without it the variable sum_flag is not being reset to missing if the transaction is in 'A' but I only want the value retained until the first non 'A' transaction.

A: Tom is probably correct that the inbound dset has extra variables from your earlier iterations at trying to solve this problem.
A DOW loop approach also works and does not require a retain or an initializing if.
data dset;
input group type $ value;
datalines;
1 A 1
1 A 2
1 A 3
1 A 4
1 B -5
1 A 8
2 A 0
2 A 9
2 A 33
3 B 9
;
run;

data dset;
  sum = .; _summing=1;
  do until (last.group);
    set dset;
    by group;

    _summing = _summing and (type = 'A');
    if _summing then sum + value;

    output;
  end;
  drop _:; * dont keep state variables;
run;

A: Two things could be happening here.

*

*You output dataset name is the same as your input dataset name (bad practice - don't do this).  If you ran it once with a mistake, it may have changed the values in the table to something unexpected, which are then making the corrected code look like it's failing.  To fix this simply re-run from the beginning and change the output dataset name to something else.

*Your value field may sometimes contain nulls?  If so the + operator is causing your problems.  The + operator will always return NULL if one of it's arguments are null.  Instead use the sum() function.  i.e. if sum_flag = 1 then sum=sum(sum,value);


text:
Q: Add a second language to a MFC project without using resource DLLs I have a really little application made with MFC with german menus. Now I was asked to make an english version too.
But the goal is to not use additional language DLLs. There should only be two .exe files (german and english) at the end.
Do you know any step by step manual how to add a second resource file for the english dialogues (if needed) and how to use them in my C++ code?
My idea is to use a preprocessor directive:
#ifdef APPLANG=EN
    m_wndRibbonBar.LoadFromResource(IDR_RIBBON_EN);
#else if
    m_wndRibbonBar.LoadFromResource(IDR_RIBBON);
#endif

Is it a good idea to do it this way?
And what are the right steps to simply copy the existing resource files and modify them to English?
I have tried several things like making a new resource file and copy the original german menu to the new file. But than I get several errors like "Enter a legal resource ID".

A: You can embed multiple language resources in a single .exe file without having to use resource DLLs. There is no support for this use case by the Visual Studio resource editor, so resource scripts must be edited manually, using a text editor.
To define the resources, use .rc2 files which the Visual Studio resource editor won't try to modify. Make sure to store the .rc2 files with Unicode (UTF-16 LE) encoding and always end them with a line break, otherwise the resource compiler will fail.
Steps

*

*A project created through the MFC application wizard already includes an empty .rc2 file, which we can use as our "main" .rc2 file. Otherwise follow the documentation or create a new MFC application using the wizard to dissect how the .rc2 file is included.

*In the main .rc2 file add an #include for each language-specific .rc2 file:
#include "lang_en.rc2"
#include "lang_de.rc2"

// Restore default language for resources included after current file
LANGUAGE LANG_ENGLISH, SUBLANG_NEUTRAL

*Create the language-specific .rc2 files. Each file must start with LANGUAGE <LANGID>, <SUBLANGID> to indicate the language of the following resources:
lang_en.rc2
LANGUAGE LANG_ENGLISH, SUBLANG_NEUTRAL
STRINGTABLE
BEGIN
    IDS_STRING1 "Stack Overflow"
    IDS_STRING2 "Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky."
END

lang_de.rc2
LANGUAGE LANG_GERMAN, SUBLANG_NEUTRAL
STRINGTABLE
BEGIN
    IDS_STRING1 "Stapelüberlauf"
    IDS_STRING2 "Stack Overflow (englisch für Stapelüberlauf) ist eine Internetplattform, auf der angemeldete Benutzer Fragen zum Thema Softwareentwicklung stellen können."
END

*Build the executable and examine it in a resource editor to see if the resources are actually included for multiple languages. Instead of using a resource editor, you can also open the .exe file in Visual Studio to examine its resources. For instance, the demo .exe I build for this answer, looks like this, when opened in Visual Studio:

In the code you can load resources as usual, Windows will automatically load the language resource that best matches the current user locale. If it doesn't find a match, it falls back to English.
If you want to explicitly load a resource for a given language, you can do this by using the resource functions that have a language parameter, e. g. FindResourceEx().
Including standard MFC resources
Without further ado, standard MFC resources will be included only in the "main" language that is configured in the resource properties of the project.
In the projects where I have used this approach, I had no need for the standard MFC resources. The following is just an untested idea how it could possibly be done.
In each language-specific .rc2 file that is not the "main" language, add #includes for the MFC standard resources after the LANGUAGE line, e. g.:
LANGUAGE LANG_GERMAN, SUBLANG_NEUTRAL

#ifdef __AFXRES_RC__
    #undef __AFXRES_RC__    // To be able to include multiple language versions of afxres.rc
#endif
#include "l.deu\afxres.rc"  // Standard MFC resources

STRINGTABLE
BEGIN
    IDS_STRING1 "Stapelüberlauf"
    IDS_STRING2 "Stack Overflow (englisch für Stapelüberlauf) ist eine Internetplattform, auf der angemeldete Benutzer Fragen zum Thema Softwareentwicklung stellen können."
END

The #undef is there to circumvent the include guard of the standard MFC resource file, which normally prevents multiple includes. In our case this is OK, because the resources will end up in different language resource sections of the executable.


text:
Q: combo box and xml I have a combo box set inside a xslt using the following code
<select name="combo">

            <xsl:for-each select="ConfId">
            </xsl:for-each>

          </select>

I wish the combo box to load all the values in the field ConfId of the XML file. Is the above lines of code correct? I am not able to get the combo box to display the details.

A: I am not sure but try this
<select name="demo">
 <xsl:for-each select="$currentPage/node">
  <option>
   <xsl:attribute name="value">
     <xsl:value-of select="./@id"/>
   </xsl:attribute>
   <xsl:value-of select="./@nodeName"/>
  </option>
 </xsl:for-each>
</select>


text:
Q: angular 8 Ngx-Webcam - webcam image upload to Firebase storage In Angular 8 application I am using  Ngx-Webcam to capture the webcam image.
and able to get the image by using imageAsDataUrl also able to display on page by using img tag
<img [src]="imgSrc">
I want to upload same image in firebase storage.please help me how to do it.
I tried
this.storage.upload(filePath, imgSrc).snapshotChanges().pipe().subscribe(...

but getting this error
FirebaseStorageError {code_: "storage/invalid-argument", message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.", serverResponse_: null, name_: "FirebaseError"}

A: you can use like this for JS/TS, to convert the ngx-webcam image to File type:
handleCapturedImage(webcamImage: WebcamImage) {
this.webcamImage = webcamImage;
const arr = this.webcamImage.imageAsDataUrl.split(",");
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
}
const file: File = new File([u8arr], this.imageName, { type: this.imageFormat })
console.log(file);  }


text:
Q: Docker - How to open a debug port for AEM I'm working with Docker to create AEM (Adobe Experience Manager) images on the basis of the following repository https://github.com/AdobeAtAdobe/aem_6-1_docker
I just can't figure out how to open a debug mode for AEM.
I have tried adding a port to EXPOSE EXPOSE 4502 30311 and adding a start file with the new JVM_OPTS CQ_JVM_OPTS="-debug -Xnoagent -Djava.compiler=none -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=30311,server=y,suspend=n ${CQ_JVM_OPTS}"
and I have also tried changing the START_OPTS START_OPTS="${START_OPTS} -debug 30311"
I'm not really comfortable with Docker yet so I'm not sure what I'm missing to startup the debug mode. Do I need to open a port in Docker via ENV or RUN?

A: You have to bind your host ports to container ports.
So, in your docker run add flag -p 4502:4502 -p 30311:30311


text:
Q: Firestore not sending link in its response to the client I am creating a new firestore document. where I am also adding an image URL as a field. Its also getting stored in the firestore database. But when I am reading data on the client the image URL is not in firestore's response.
Firestore Database Image Here
Code Image Here


text:
Q: Python Google-Earth-Engine: print list of Landsat scenes over ROI to export them on Drive I have a Java script on GEE that allows me to grab all the Landsat images over my ROI for a specific time-period. The issue is that transferring those images from the GEE code editor to my Google Drive takes a very long time (2h per image, and I have at least 50 of them), and I have to manually click on a button to do it.
I have been exploring the Python API for GEE and I use a code to transfer an image on my Google Drive (see code below):
# Download a specific Landsat Scene
landsat = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_123032_20140515')\
            .select(['B4', 'B3', 'B2'])

# Create a geometry representing an export region.
geometry = ee.Geometry.Rectangle([116.2621, 39.8412, 116.4849, 40.01236])
# Export the image, specifying scale and region.
task = ee.batch.Export.image.toDrive(**{
    'image': landsat,
    'description': 'Test',
    'folder':'Folder',
    'scale': 100,
    'region': geometry.getInfo()['coordinates']
})
task.start()

What I would like to do is create a list gathering all my Landsat images' names, then iterate over that list with the code above so I can automatically save and export the images to my drive.
My Java code to export the Landsat images from GEE code editor is below. Every example I found deals with names of images already found, but in my case I need to get the names of images depending on: the time at which they were taken, the cloud cover, their coverage over the ROI.
The Java script does all of that.
The way I look at it I have two solutions:

*

*Export a list gathering the names of my images from the Java script on GEE Editor, then open that list on Python and iterate through that

*Have the Java script working on Python that does the exact same thing.
I have no experience with Java and I can't manage to export a list as .csv or .ASCII or .txt.
The issue with the 2nd option is that I can't find any code that does what I do on Java.
How could I solve my problem ?
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var geometry =
    /* color: #98ff00 */
    /* shown: false */
    /* displayProperties: [
      {
        "type": "rectangle"
      }
    ] */
    ee.Geometry.Polygon(
        [[[-141.1474025430237, 60.163560184011736],
          [-141.1474025430237, 59.70120024412181],
          [-139.9938380898987, 59.70120024412181],
          [-139.9938380898987, 60.163560184011736]]], null, false),
    aoi = /* color: #d63000 */ee.Geometry.Point([-140.62080375708652, 59.944917067323274]);
/***** End of imports. If edited, may not auto-convert in the playground. *****/
var cloudMaskL457 = function(image) {
  var qa = image.select('pixel_qa');
  // If the cloud bit (5) is set and the cloud confidence (7) is high
  // or the cloud shadow bit is set (3), then it's a bad pixel.
  var cloud = qa.bitwiseAnd(1 << 5)
                  .and(qa.bitwiseAnd(1 << 7))
                  .or(qa.bitwiseAnd(1 << 3));
  // Remove edge pixels that don't occur in all bands
  var mask2 = image.mask().reduce(ee.Reducer.min());
  return image.updateMask(cloud.not()).updateMask(mask2);
};
function maskL8sr(image) {
  // Bits 3 and 5 are cloud shadow and cloud, respectively.
  var cloudShadowBitMask = (1 << 3);
  var cloudsBitMask = (1 << 5);
  // Get the pixel QA band.
  var qa = image.select('pixel_qa');
  // Both flags should be set to zero, indicating clear conditions.
  var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)
                 .and(qa.bitwiseAnd(cloudsBitMask).eq(0));
  return image.updateMask(mask);
}
var l5 = ee.ImageCollection('LANDSAT/LT05/C01/T1_SR')
                  .filterDate('1984-01-01', '2012-05-05')
                  .map(cloudMaskL457)
                  .filterBounds(aoi)
                  .map(function(a){
                    return a.set('year', ee.Image(a).date().get('year'))
                  })
/*
var l7 = ee.ImageCollection('LANDSAT/LE07/C01/T1_SR')
                  .filterDate('1997-01-01', '2021-05-12')
                  .map(cloudMaskL457)
                  .filterBounds(aoi)
                  .map(function(a){
                    return a.set('year', ee.Image(a).date().get('year'))
                  })
*/
var l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')
                  .filterDate('2013-04-11', '2021-05-05')
                  .map(maskL8sr)
                  .filterBounds(aoi)
                  .map(function(a){
                    return a.set('year', ee.Image(a).date().get('year'))
                  })
var list = ee.List([])
for (var a=1984; a < 2022; a++) {

  if(a < 2012) {
    var filL5 = l5.filterMetadata('year', 'equals', a).median()
    var l5final = filL5.set('year', a)
                       .set('product', 'L5')
    list = list.add(l5final)
  } else {
    var filL8 = l8.filterMetadata('year', 'equals', a).median()
    var l8final = filL8.set('year', a)
                       .set('product', 'L8')
    list = list.add(l8final)

  }
}
print(list)
var finalCol = ee.ImageCollection(list).map(function(a){
                return a.set('bands', ee.Image(a).bandNames().length())
                })
                .filterMetadata('bands','greater_than',10)

print(finalCol)
for(var a = 1984; a < 2022; a++){
  Map.addLayer(finalCol.filterMetadata('year', 'equals', a), {}, ' '+a, false)
}
var dataset = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')
                  .filterDate('2016-01-01', '2016-12-31')
                  .map(maskL8sr);
var visParams = {
  bands: ['B4', 'B3', 'B2'],
  min: 0,
  max: 3000,
  gamma: 1.4,
};
Map.addLayer(dataset.median(), visParams);
var n = finalCol.size().getInfo()
var i = 0
for(var a = 1984; a < 2022; a++){
  //put an actual angled bracket here
  var img = ee.Image(list.get(i))
  var i = i + 1
  var rgb = img.select('B3','B2', 'B1').float()
  Map.addLayer(img, {bands: ['B3', 'B2', 'B1'], max: 10000}, 'Image_'+a)
  //export
  Export.image.toDrive({
  image: rgb,
  description: 'Landsat5_NC'+ a,
  scale: 10,
  region: geometry,
  folder: 'Malaspina_Landsat5'

})
}


text:
Q: NHibernate Linq // FirstOrDefault with children objects // Possible? I have an Employee.
Employee has a single (parent) Department. 1:N, Department to Employee.
Employee has N EmployeeToJobTitleMatchLink(s).
Employee has N number of ParkingArea(s).
When using NHibernate and Linq, and "FirstOrDefault"..
            EmployeeNHEntity firstOrDefaultEmp = session.Query<EmployeeNHEntity>()
                .Fetch(e => e.MyEmployeeToJobTitleMatchLinks)
                .Fetch(e => e.ParentDepartment)
                .Fetch(e => e.MyParkingAreas)
                .Where(e => e.EmployeeUUID == employeeUuid)
                .FirstOrDefault();

I get this sql.  (the most important part is the "Top 1".
exec sp_executesql N'select TOP (1)  employeenh0_.EmployeeUUID as Employee1_1_0_, myemployee1_.LinkSurrogateUUID as LinkSurr1_3_1_, department2_.DepartmentUUID as Departme1_0_2_, parkingare4_.ParkingAreaUUID as ParkingA1_5_3_, employeenh0_.MyVersionColumn as MyVersio2_1_0_, employeenh0_.SSN as SSN1_0_, employeenh0_.LastName as LastName1_0_, employeenh0_.FirstName as FirstName1_0_, employeenh0_.CreateDate as CreateDate1_0_, employeenh0_.HireDate as HireDate1_0_, employeenh0_.ParentDepartmentUUID as ParentDe8_1_0_, myemployee1_.PriorityRank as Priority2_3_1_, myemployee1_.JobStartedOnDate as JobStart3_3_1_, myemployee1_.TheEmployeeUUID as TheEmplo4_3_1_, myemployee1_.TheJobTitleUUID as TheJobTi5_3_1_, myemployee1_.TheEmployeeUUID as TheEmplo4_0__, myemployee1_.LinkSurrogateUUID as LinkSurr1_0__, department2_.MyVersionColumn as MyVersio2_0_2_, department2_.DepartmentName as Departme3_0_2_, department2_.CreateDate as CreateDate0_2_, parkingare4_.ParkingAreaName as ParkingA2_5_3_, parkingare4_.CreateDate as CreateDate5_3_, myparkinga3_.AbcEmployeeUUID as AbcEmplo1_1__, myparkinga3_.AbcParkingAreaUUID as AbcParki2_1__ from dbo.Employee employeenh0_ left outer join dbo.EmployeeToJobTitleMatchLink myemployee1_ on employeenh0_.EmployeeUUID=myemployee1_.TheEmployeeUUID left outer join dbo.Department department2_ on employeenh0_.ParentDepartmentUUID=department2_.DepartmentUUID left outer join EmployeeToParkingAreaLink myparkinga3_ on employeenh0_.EmployeeUUID=myparkinga3_.AbcEmployeeUUID left outer join dbo.ParkingArea parkingare4_ on myparkinga3_.AbcParkingAreaUUID=parkingare4_.ParkingAreaUUID where employeenh0_.EmployeeUUID=@p0',N'@p0 uniqueidentifier',@p0='64409648-15C5-4B67-BCE2-A265012E0926'

The issue is that I get 1 row (top 1).  While I have 1 Employee, I (should) have many rows in the resultset.
Now, if I use the below, I get the desired result. (A single employee with the children objects populated)....if there is a match on the surrogate-key (EmployeeUUID), there is one item in the collection.
            IList<EmployeeNHEntity> emps = session.Query<EmployeeNHEntity>()
                .Fetch(e => e.MyEmployeeToJobTitleMatchLinks)
                .Fetch(e => e.ParentDepartment)
                .Fetch(e => e.MyParkingAreas)
                .Where(e => e.EmployeeUUID == employeeUuid)
                .ToList();

            EmployeeNHEntity emp = null;
            if(null!=emps)
            {
                if (emps.Count > 0)
                {
                    emp = emps[0];
                }
            }

which generates this sql
exec sp_executesql N'select employeenh0_.EmployeeUUID as Employee1_1_0_, myemployee1_.LinkSurrogateUUID as LinkSurr1_3_1_, department2_.DepartmentUUID as Departme1_0_2_, parkingare4_.ParkingAreaUUID as ParkingA1_5_3_, employeenh0_.MyVersionColumn as MyVersio2_1_0_, employeenh0_.SSN as SSN1_0_, employeenh0_.LastName as LastName1_0_, employeenh0_.FirstName as FirstName1_0_, employeenh0_.CreateDate as CreateDate1_0_, employeenh0_.HireDate as HireDate1_0_, employeenh0_.ParentDepartmentUUID as ParentDe8_1_0_, myemployee1_.PriorityRank as Priority2_3_1_, myemployee1_.JobStartedOnDate as JobStart3_3_1_, myemployee1_.TheEmployeeUUID as TheEmplo4_3_1_, myemployee1_.TheJobTitleUUID as TheJobTi5_3_1_, myemployee1_.TheEmployeeUUID as TheEmplo4_0__, myemployee1_.LinkSurrogateUUID as LinkSurr1_0__, department2_.MyVersionColumn as MyVersio2_0_2_, department2_.DepartmentName as Departme3_0_2_, department2_.CreateDate as CreateDate0_2_, parkingare4_.ParkingAreaName as ParkingA2_5_3_, parkingare4_.CreateDate as CreateDate5_3_, myparkinga3_.AbcEmployeeUUID as AbcEmplo1_1__, myparkinga3_.AbcParkingAreaUUID as AbcParki2_1__ from dbo.Employee employeenh0_ left outer join dbo.EmployeeToJobTitleMatchLink myemployee1_ on employeenh0_.EmployeeUUID=myemployee1_.TheEmployeeUUID left outer join dbo.Department department2_ on employeenh0_.ParentDepartmentUUID=department2_.DepartmentUUID left outer join EmployeeToParkingAreaLink myparkinga3_ on employeenh0_.EmployeeUUID=myparkinga3_.AbcEmployeeUUID left outer join dbo.ParkingArea parkingare4_ on myparkinga3_.AbcParkingAreaUUID=parkingare4_.ParkingAreaUUID where employeenh0_.EmployeeUUID=@p0',N'@p0 uniqueidentifier',@p0='64409648-15C5-4B67-BCE2-A265012E0926'

The [0] indexer trick is ok.  But just isn't as clean as I'd like my Linq code to be.
Any suggestions now LINQ syntax to get Top 1 Employee, but with all the children objects?

A: EmployeeNHEntity firstOrDefaultEmp = session.Query<EmployeeNHEntity>()
    .Fetch(e => e.MyEmployeeToJobTitleMatchLinks)
    .Fetch(e => e.ParentDepartment)
    .Fetch(e => e.MyParkingAreas)
    .Where(e => e.EmployeeUUID == employeeUuid)
    .AsEnumerable()    <-- note this line
    .FirstOrDefault();


text:
Q: How to set default audio device when two playback devices with same names are connected I am trying to Set default audio device when two playback devices with same names are connected.
Details:
For single or playback devices with a different name, I can set default using nircmd.exe. But When connecting a USB Speaker in my laptop. In Playback devices it is showing two Speakers with the same name as "Speakers". In this scenario, I'm  not able to set default playback device as per my request. It is by default setting first Speaker as Set Default.
So can anybody please help me on this.

A: It is possible to rename entries, through right-click "Properties".
No info if it persists through removals.

A: Got the Solution. For this we can just refer First Child of Speaker. If it matches with your requirement. Then we'll get the reference of that and perform suitable action.

A: Renaming entries does not persist.
However, in addition to nircmd, nirsoft also provides a tool named SoundVolumeView which can handle devices having the same name thanks to a "Command-line Friendly ID"
.\SoundVolumeView.exe /sjson list.json

returns a list of available devices in list.json
Example :
[
  {
    "Name":"5 - PL4071UH",
    "Type":"Device",
    "Device Name":"AMD High Definition Audio Device",
    "Command-Line Friendly ID":"AMD High Definition Audio Device\\Device\\5 - PL4071UH\\Render",
    ....
  },
  {
    "Name":"Casque",
    "Type":"Device",
    "Device Name":"Tronsmart Onyx Ace Hands-Free AG Audio",
    "Command-Line Friendly ID":"Tronsmart Onyx Ace Hands-Free AG Audio\\Device\\Casque\\Capture",
    ...
  }
]

And then, you can change device with :
.\SoundVolumeView.exe /SetDefault "AMD High Definition Audio Device\\Device\\5 - PL4071UH\\Render"


text:
Q: Conditional Required field in Oracle ADF 12c I have a form that requires multiple user inputs. One of them is a drop down list from which the User has to choose. Now I have to set the next input field as required depending on the options chosen in the first field.
For ex: There are 4 input options to be chosen for the first input field - A,B,C,D
I want the next input field to become mandatory when the user chooses option A and D.
How do I build the expression for the required field in this case?
I have tried doing this but that doesn't work
https://stackoverflow.com/a/48089828/15161963

A: 1). Assume that, the name of first field() is 'FirstField' and next input field id 'SecondField' .
2). Then on 'SecondField'component's Required property , write EL as below .
Required = #{bindings.FirstField.attributeValue eq 'A' || bindings.FirstField.attributeValue eq 'B'}
3). And ensure that , 'SecondField's partialTrigger property points to 'FirstField' component  .

A: I think you can binding your dopdownlist to a bean.
binding=#{yourBean.firstDropdowList}

Create method isDisableInputField
Boolean isRequireYourInputField(){
 Boolean dropdownValue=firstDropdowList.getValue();
if("A".equals(dropdownValue) ||"D".equals(dropdownValue)) {
return true:
}
return false

}

In your af dropdown tag. Set
require=#{yourBean.isRequireYourInputField()}


text:
Q: Is there a literal notation for decimal in IronPython? suppose I have the following IronPython script:
def Calculate(input):
    return input * 1.21

When called from C# with a decimal, this function returns a double:
var python = Python.CreateRuntime();
dynamic engine = python.UseFile("mypythonscript.py")

decimal input = 100m; // input is of type Decimal
// next line throws RuntimeBinderException:
//     "cannot implicitly convert double to decimal"
decimal result = engine.Calculate(input);

I seem to have two options:
First, I could cast at the C# side: seems like a no-go as I might loose precision.
decimal result = (decimal)engine.Calculate(input);

Second option is to use System.Decimal in the python script: works, but pollutes the script somewhat...
from System import *

def CalculateVAT(amount):
    return amount * Decimal(1.21)

Is there a short-hand notation DLR that the number 1.21 should be interpreted as a Decimal, much like I would use the '1.21m' notation in C#? Or is there any other way to enforce decimal to be used instead of double?

A: Look at the python docs:

Decimal instances can be constructed from integers, strings, or
  tuples. To create a Decimal from a
  float, first convert it to a string.
  This serves as an explicit reminder of
  the details of the conversion
  (including representation error).

Unfortunatelly there is no short hand notation you are looking for. Even python has none.
The standard way of 'hard coding' a decimal is to pass a string representation to the decimal constructor:
from decimal import Decimal
my_decimal = Decimal("1.21")

If you are writing code that is heavy on .net interop passing (it seems like you are) it may be better just using the .net Decimal datatype right away, as you proposed yourself. However be aware that you passing a floating point number to the decimal constructor in this example. You may get a small error in accuracy from the conversion, if the number has much more decimal places:
from System import *
my_decimal = Decimal(1.21)

So you may be better off using this constructor overload:
from System import *
my_decimal = Decimal(121, 0, 0, False, 2)

Not the most beautiful and shortest way of doing what you want, but the best in terms of performance and accuracy.

A:
seems like a no-go as I might lose precision.

Yeah, you do that in the other method too:
Decimal(1.21)

Once you've written 1.21 that's a floating point number and you've already lost the full precision before even passing it to the Decimal constructor. That's why Python's native Decimal class must be initialised from a string, not a float:
decimal.Decimal('1.21')

There doesn't seem to be a similar constructor for .NET's Decimal, but you could perhaps do it using the constituent parts constructor:
System.Decimal(121, 0, 0, False, 2)