text:
Q: Where or how does Sidekiq/Redis store an object when a Job is retrying? We provide our Clients a way to preview mass emails being delivered to their Users. For some of the emails, we mock (OpenStruct) some objects and use them in the email view:
UserMailer:
class UserMailer < ApplicationMailer
 def about_to_expire_card_reminder
    ...
    if params[:email_preview]
      @subject += " (email de prueba)"
      @user_default_credit_card = mock_credit_card
    end

    send_email(subject: @subject)
  end

  def mock_credit_card
    OpenStruct.new(last_four_digits: "1234 (tarjeta de prueba)",
                   expiration_date: 10.days.from_now.to_date)
  end

end

We were forcing errors today and noticed that the OpenStruct that mock_credit_card returns  does not show up in the Sidekiq admin page where the retrying Job shows.
Retrying Job info:
Next Retry: in 3 minutes
Retry Count: 4
Queue: mailers
Job: ActionMailer::MailDeliveryJob
Arguments: "UserMailer", "about_to_expire_card_reminder", "deliver_now", {"params"=>{"user"=>{"_aj_globalid"=>"gid://database/User/1"}, "to"=>info@testemail.com", "email_preview"=>true, "aj_symbol_keys"=>["user,"to","email_preview"]}, "args"=>[],"_aj_symbol_keys"=>["params","args"]}
Error: ActionView::Template:Error: undefined method "last_four_digits" for #struct expiration_date="2021-03-31">

Where does Sidekiq store the mocked OpenStruct object? Is it serialized? Does it take up memory until the job is finished or dropped?
Any insights would be appreciated. Let me know if you need more code.

A: TL;DR The mocked object isn't stored. The only thing that sidekiq stores are what you've printed out as "Retrying Job info:".
The long version... how does that work?
ActiveJob enqueues each job in sidekiq with a job name and arguments. If the job fails, it serializes the (original) jobs information so the failed job can be retried. You can see the job class name and arguments in the retry job info:
Job: ActionMailer::MailDeliveryJob
Arguments: "UserMailer", "about_to_expire_card_reminder", "deliver_now", {"params"=>{"user"=>{"_aj_globalid"=>"gid://database/User/1"}, "to"=>info@testemail.com", "email_preview"=>true, "aj_symbol_keys"=>["user,"to","email_preview"]}, "args"=>[],"_aj_symbol_keys"=>["params","args"]}

along with other information sidekiq needs (the queue it should be run on and the retry count).
When sidekiq runs the job, it constantizes the job class and calls perform on an instance of it, passing in the arguments it stored. In this case, it calls MailDeliveryJob#perform like so:
ActionMailer::MailDeliveryJob.new.perform("UserMailer", "about_to_expire_card_reminder", "deliver_now", {"params"=>{"user"=>{"_aj_globalid"=>"gid://database/User/1"}, "to"=>info@testemail.com", "email_preview"=>true, "aj_symbol_keys"=>["user,"to","email_preview"]}, "args"=>[],"_aj_symbol_keys"=>["params","args"]})

The Activejob base class does processing on the job arguments (turning {"_aj_globalid"=>"gid://database/User/1"} into User.find(1)), then the MailDeliveryJob#perform method calls your mailer class like so:
UserMailer.with({"user"=> User.find(1), "to"=>info@testemail.com", "email_preview"=>true}).about_to_expire_card_reminder.deliver_now

These are the same params stored in sidekiq, except the user has been inflated. At this point the about_to_expire_card_reminder method creates a new mock credit card object, stores it in an instance variable on your mailer class, and the mail object gets built with access to those instance variables.
Let me know if that makes sense / if that answers the question.


text:
Q: Magento 2.1.3 unable to reindex using SSH I tried the instructions under Magento 2 Reindexing - One or more indexers are invalid. Make sure your Magento cron job is running
but am still unable to reindex. I ssh'd into my webserver and tried running the command that was suggested from the root, php bin/magento indexer:reindex but it didn't work, so I tried going to the directory
"blahblah.com"/shop/bin$ magento indexer:reindex
-bash: magento: command not found
(I have a /shop directory where my files are installed)
and I tried magento indexer:status (and some others but am not able to run the commands, keep getting command not found)
I also opened up the file manager, found the magento file, opened it up and searched for indexer but am not finding it either.
Can someone help me to understand how I can reindex the status under the Index Management of my magento site? Thanks.

A: You either run the command as:
php magento indexer:reindex

Or you can make the magento script executable:
chmod +x magento

After making the script excutable you can run the script as:
./magento indexer:reindex

Your magento file should look like the following:
#!/usr/bin/env php
<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

if (PHP_SAPI !== 'cli') {
    echo 'bin/magento must be run as a CLI application';
    exit(1);
}

try {
    require __DIR__ . '/../app/bootstrap.php';
} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try {
    $handler = new \Magento\Framework\App\ErrorHandler();
    set_error_handler([$handler, 'handler']);
    $application = new Magento\Framework\Console\Cli('Magento CLI');
    $application->run();
} catch (\Exception $e) {
    while ($e) {
        echo $e->getMessage();
        echo $e->getTraceAsString();
        echo "\n\n";
        $e = $e->getPrevious();
    }
    exit(Magento\Framework\Console\Cli::RETURN_FAILURE);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to inject JavaScript into a page in my browser to customise a web page?  The Idea and Question
I am looking for something that functions to what amounts to JavaScript injectection, but safer. This idea can be most effectively observed by your broswer's console and start noodling with something like document.getElementById('btnSubmit').value = 'I took over your button'; after a quick inspection of the site in question.  I would effectively would like to amend an established website to a local machine for the purpose of pre-filling fields as an exercise of efficiency in a work process.
 The Background
I am well aware of the issue of XSS, howerver, JavaScript seems to be the best candidate for accessing elements with a document read in by a browser, and JavaScript injection is the only feasible method of sort of accomplishing this idea, but that's just from my limited perspective.  Many of the processes in question requires duplicate data input in more than one system where at least one of the data input sources is at least controllable by a proprietary server-side language. I am open to suggestion, however, I think the question itself is interesting.


text:
Q: iOS Mystery crash w libsystem_kernel.dylib The report I'm getting back from Crashlytics is
Crashed: com.apple.main-thread
SIGABRT ABORT at 0x357fedf0

How do I narrow this mystery crash down?
Also, here's some additional info from Crashlytics

EDIT
Thread : Crashed: com.apple.main-thread
0  libsystem_kernel.dylib         0x3b90f350 __pthread_kill + 8
1  libsystem_c.dylib              0x3b886123 pthread_kill + 58
2  libsystem_c.dylib              0x3b8c2973 abort + 94
3  libc++abi.dylib                0x3ae60d4f abort_message + 74
4  libc++abi.dylib                0x3ae5e0db safe_handler_caller(void (*)()) + 174
5  libc++abi.dylib                0x3ae5e114 std::terminate() + 19
6  libc++abi.dylib                0x3ae5f599 __cxa_current_exception_type
7  libobjc.A.dylib                0x3b4119d1 objc_exception_rethrow + 12
8  CoreFoundation                 0x336d7f21 CFRunLoopRunSpecific + 456
9  CoreFoundation                 0x336d7d49 CFRunLoopRunInMode + 104
10 GraphicsServices               0x3728a2eb GSEventRunModal + 74
11 UIKit                          0x355ed301 UIApplicationMain + 1120
12 MyAppName                      0x000f1e9f main (main.m:15)

A: as I see from the logs "pthread_kill" in the stack, I hope that this answer helps you.
Exception Type: EXC_CRASH (SIGABRT)


text:
Q: Write a short program in SNOBOL that calculate the sum of all even integers from 1 to 100 You should use loop for multiple iterations of addition. GOTO statement and labels can be used to design a loop of your requirement.
please give me some ideas.

A: I think it's not really Snobol if it doesn't contain a pattern match...
This solution generates the even numbers 000 .. 100 by matching a pattern against the string "01012345678902468" and adding the generated numbers through the function add(). Looping is done through the FAIL keyword at the end of the pattern, which forces the pattern scanning to continue looking for alternatives until the expression (*EQ(h t o,100) ABORT) causes the scanning to abort.
    &FULLSCAN = 1
    DEFINE('add(x)') :(add.End);add sum = sum + x :(RETURN);add.End
    "01012345678902468" (LEN(1) $ h *LEN(1 - h)) ARB (LEN(1) $ t
.       *LEN(9 - t)) ARB LEN(1) $ o *add(h t o)
.       (*EQ(h t o,100) ABORT) FAIL
    OUTPUT = sum
END

Works both in Snobol and Spitbol (&FULLSCAN = 1 is needed for Snobol, it's a no-op in Spitbol)

A: *This works on the Spitbol version of Snobol.
loop m = le(n, 98) (n = n + 2) + m  :s(loop); output = m ;end


text:
Q: Custom Checkboxes using Ruby on Rails I'm trying to add custom checkboxes that will also work in firefox, but I'm having trouble with the ruby-code. What I want is something along those lines:
    <%= f.check_box :privacy_statement_accepted, id:"agb" %>
    <%= f.label :privacy_statement_accepted, "".html_safe %>

However, this code disables the use of the checkbox and returns always true, but if I change it to:
    <%= f.check_box :privacy_statement_accepted, {:checked=>false}, id:"agb" %>
    <%= f.label :privacy_statement_accepted, "".html_safe %>

it doesn't update the value when the box is checked. Is there a solution that uses f.check_box and not check_boxe_tag?
This is what I'm using atm because it works but it is not great:
<input type="checkbox" id="agb" name="privacy_statement_accepted" />

The CSS:
input[type="checkbox"] {
    display: none;
}

input[type="checkbox"] + label {
    font-size:14px;
}

input[type="checkbox"] + label span {
    display:inline-block;
    width:19px;
    height:19px;
    margin: -1px 4px 0 0;
    vertical-align:middle;
    background:url(icons/checkbox.png) left top no-repeat;
    cursor:pointer;
}

input[type="checkbox"]:hover + label span {
    background:url(icons/checkbox.png) left bottom -20px no-repeat;
}

input[type="checkbox"]:checked + label span {
    background:url(icons/checkbox.png) left top -46px no-repeat;
}

The JavaScript:
function validateAgb() {
if ($('#agb').is(':checked')) {
    $('#agbMsg').hide();
    return true;
} else {
    $('#abg').focus();
    $('#agbMsg').show();
    return false;
}
}

Thanks!


text:
Q: Best Practice for masking Credit Card informations in Web Api 2 In an Asp.Net Web API 2 project, We're logging every http request and response with log4Net.
Some controllers have critical parameters such as "CreditCard, CVV, Month, Year" etc. This data should not be stored in a database.
I don't know how to check for these. Should I use a RegEx? Or should I hide the controller method's log which contains the critical parameters which must not be stored?

A: "We're logging every http request and response with log4Net."
Although im sure this is very useful for developers, its very bad practice and is potentialy illegal.
As you have pointed out you are probably saving credit card information in a non pci compliant way.
You are probably also processing 'personal information' such as names and addresses etc in ways which the owner has not given you permission to do so. Breaking the data protection act or equivilant law in your country.
You may also be saving your users usernames and passwords in clear text
The solution is simple to say but hard to implement. You have to stop logging every request/response and start controlling the exact message which is written to your logs.
Eg.
Instead of
Log.Write("Error processing request" + request.ToString());

you have Catch the exact error and write
...
   DoStuff(publicA,secret1,secret2)
}
catch(Exception ex)
{
    Log.Write("Error doing stuff with id : " + publicA);
}

Where you know publicA is some internal db reference or identifier with no meaning to a hacker and can prove it to your security auditor.
To clarify: Neither hiding the logs, having a blacklist of parameters or using a regex to spot and remove secret data really helps you. As you can't be sure that you have caught every case.

A: @LarsViklund nailed the answer in a comment.  Unless you're a payment processor, credit card information should never reach your servers at all.
You need to fix the real problem and not try to mask it by making exceptions to your logging practices.
Tell your business leaders that hackers will never get your client's data if you never had it to begin with.  Explain to them that they're very likely breaking a lot of privacy laws as well as PCI compliance - which can lead to some very large fines.


text:
Q: Error converting Json file to a feature class I want to convert some json data being returned from a request to a feature class, but I keep getting a RuntimeError: Object: Error in executing tool. I made a test gdb in a folder 'C:/Workspace/Sandbox/ScratchTests/cslf.gdb' in which to populate my new feature class after conversion. To test that the request is correct and that I am returning Json data, I added a couple of print statements. Otherwise, everything is pretty straight forward. Does anyone see a problem with my code? I am following the arcpy [JSON to Features][1] directions from the documentation. The only thing I am doing differently is instead of using an actual file, I am just plugging in the variable 'cslfJson`.
import arcpy, sys, os, arcgis, requests
arcpy.env.workspace = "C:/Workspace/Sandbox/ScratchTests"

params = {'f': 'json', 'where': '1=1', 'geometryType': 'esriGeometryPolygon', 'spatialRel': 'esriSpatialRelIntersects','outFields': '*', 'returnGeometry': 'false'}
r = requests.get('https://hazards.fema.gov/gis/nfhl/rest/services/CSLF/Prelim_CSLF/MapServer/3/query', params)
print(r.url)

cslfJson = r.json()
print(cslfJson)

arcpy.JSONToFeatures_conversion(cslfJson, os.path.join("cslf.gdb", "cslf"))

Also, Here's the Traceback:

https://hazards.fema.gov/gis/nfhl/rest/services/CSLF/Prelim_CSLF/MapServer/3/query?f=json&where=1%3D1&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelIntersects&outFields=%2A&returnGeometry=false
  Traceback (most recent call last):
File "", line 1, in
      runfile('C:/Workspace/Sandbox/ScratchTests/CSLF.py', wdir='C:/Workspace/Sandbox/ScratchTests')
File
  "C:\Users\jbridwell\AppData\Local\Continuum\anaconda3\envs\acrpro\lib\site-packages\spyder_kernels\customize\spydercustomize.py",
  line 668, in runfile
      execfile(filename, namespace)
File
  "C:\Users\jbridwell\AppData\Local\Continuum\anaconda3\envs\acrpro\lib\site-packages\spyder_kernels\customize\spydercustomize.py",
  line 108, in execfile
      exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Workspace/Sandbox/ScratchTests/CSLF.py", line 20, in

      arcpy.JSONToFeatures_conversion(cslfJson, os.path.join("cslf.gdb", "cslf"))
File "C:\Program
  Files\ArcGIS\Pro\Resources\ArcPy\arcpy\conversion.py", line 403, in
  JSONToFeatures
      raise e
File "C:\Program
  Files\ArcGIS\Pro\Resources\ArcPy\arcpy\conversion.py", line 400, in
  JSONToFeatures
      retval = convertArcObjectToPythonObject(gp.JSONToFeatures_conversion(*gp_fixargs((in_json_file,
  out_features), True)))
File "C:\Program
  Files\ArcGIS\Pro\Resources\ArcPy\arcpy\geoprocessing_base.py", line
  506, in
      return lambda *args: val(*gp_fixargs(args, True))
RuntimeError: Object: Error in executing tool
[1]:
  http://desktop.arcgis.com/en/arcmap/10.3/tools/conversion-toolbox/json-to-features.htm

A: Be sure to have the latest ArcGIS PRO patch release (2.2.1)
There were known issues in previous releases dealing with JSON conversions.

*

*BUG-000115464

GeoJSON to Features crashes ArcGIS Pro at GPCoreFunctions!Bucket_JSON2F::UnionProperties (gpesrijsontofeaturesfunction.cpp @ 1029).

*

*BUG-000110564

The Key Metadata function fails to run a JSON Metadata String in ArcGIS Pro, even with a valid input.
these BUGS are not limited to your issue but will affect your processing. Implement the patch and see if it clears the problem.

A: I was actually able to get this to work without updating to 2.2. Essentially, I had to turn the json data into a physical file in order for it to work. This is a little cumbersome, but as the file should get overwritten each time I run the script (as the REST service data is updated) it should be fine. I just added a part at then end to open a file and then write to that file, then use the newly created json file in JSONToFeatures_conversion:
cslfJson = r.json()
path = r"C:/Workspace/Sandbox/ScratchTests/cslf.json"
with open(path, 'w') as f:
     json.dump(cslfJson, f, indent=2)

arcpy.JSONToFeatures_conversion("cslf.json", os.path.join("cslf.gdb", "cslf"))


text:
Q: How can Iist only functions and those that come from a package I use the foreach package to parallelize some stuff and I am tired of indicating 5 functions in .export everytime I need to use it.
I know I can do foreach(...,.export=ls(.GlobalEnv)) but this transfers a lot of data to the workers and slow me down (there can be big tables defined).
So the question is how can I list only functions in the .GlobalEnv
I did that:
getAllFunctions <- function(envir=.GlobalEnv){
        allClasses <- sapply(grep(x=ls(envir), pattern='^%', value=TRUE, invert=TRUE), FUN=function(x){class(eval(parse(text=x)))})
        fnNames <- names(allClasses)[allClasses == 'function']
        return(fnNames)
}

But that's ugly (and gives everything) and I'm sure there is an idiomatic way

A: From the comments:
as.list(.GlobalEnv)[sapply(.GlobalEnv, is.function)]


text:
Q: Does entropy change when work in done on the system? Suppose, I have a cylinder filled with ideal gas molecules, and a piston is fitted at the top of the cylinder so that work can be done on and by the system. Now, if I do work on the system, isn't it the same as adding heat to the system?
Why then, does the formula only consider heat when calculating entropy?
$$dS=\frac{dQ}{T}$$
Can we not replace $dQ$ with $dW$, where $dW$ is the infinitesimal work done on the system?

A:
Does entropy change when work in done on the system?

Total entropy change equals entropy transferred plus entropy generated. Only heat transfers entropy. Reversible work itself does not transfer entropy. It is only the heat that may result from reversible work that transfers entropy. On the other hand, irreversible work does change (increase) entropy due to entropy generation.

Now, if I do work on the system, isn't it the same as adding heat to
the system?

It's the same only insofar as a differential change in internal energy $dU$ is concerned since they are related to the change by the first law
$$dU=\delta Q-\delta W$$
For example, if you did 10 J of compression work on the system but added no heat, or added 10 J of heat to the system but did no work, the change in internal energy would be the same, +10 J. After the change has occurred there is no way to know whether it was caused by heat or work. So in terms of the first law (conservation of energy) heat can be considered equivalent to work.
But work done on the system is not the same as adding heat to the system insofar as a change in entropy is concerned. If the 10 J of compression work was a reversible adiabatic process, then $\Delta S_{sys}=0$ because $Q=0$. If the 10 J of heat added was a reversible isochoric (constant volume) heat addition where $W=0$, then $\Delta S=mC_{v}\ln\frac{T_2}{T_1}$.

Why then, does the formula only consider heat when calculating
entropy?
$$dS=\frac{dQ}{T}$$

The equation
$$dS=\frac{\delta Q_{rev}}{T}$$
defines a differential change in entropy of a system for a reversible path, as in the reversible isochoric heat addition and reversible adiabatic compression examples above. Although the equation is for a reversible path, it is used to calculate the change in entropy for an irreversible path between the two equilibrium states since entropy is a state property independent of the path. However, for an irreversible path, you need to devise any convenient reversible path that satisfies the initial and final states per the first law.
For example, an irreversible adiabatic process generates entropy although there is no heat transfer. To determine the entropy increase you would devise any convenient reversible path connecting the initial and final states and apply the entropy equation to it. You would find that part of that path will require reversible heat transfer.
@Chet Miller has developed a helpful step by step approach to determine the change in entropy of a system. You can find it here:
https://www.physicsforums.com/insights/grandpa-chets-entropy-recipe/

Can we not replace $dQ$ with $dW$, where $dW$ is the infinitesimal work done on the system?

In the case of a reversible isothermal process involving an ideal gas, since $dU=0$, then $\delta Q=\delta W$, meaning the magnitude of energy transfer to/from the system in the form of reversible heat equals the magnitude of energy transfer from/to the system in the form of reversible work. But the fact the values are the same does not mean heat and work are equivalent with respect to entropy change as already stated above. It is reversible heat that transfers entropy, not reversible work.  For that reason I would be hesitant to substitute $\delta W$ for $\delta Q$ in the entropy equation as it may imply that heat and work are equivalent with respect to entropy change.
Hope this helps.

A: Work and heat are different concepts.
Work is a quantity which stems from a change in your system.
Heat is a quantity that stems from a change in energy coming from your environment i.e. outside your system.
Now consider the 1st law of thermodynamics
$$dE = \delta W + \delta Q$$
this is a phenomenological axiom which expresses the two different ways you can change the energy in your system when going from one equilibrium state to another. It is in this sense that heat and entropy are the same as you mention, they both change the energy but they are functionally different. The 1st law is also an exact differential, allowing us to express changes in energy.
Sticking to your example of a piston, we can begin to try and attain expressions for the inexact differentials in the expression above. Starting $\delta W$ this is obviously
$$W = - \int^{v_1}_{v_0}P dV$$
from observation. Giving us a path depentent way to evaluate work when moves from one equilibrium state to another in a state space (in this case some PV diagram).
For $\delta Q$ understanding how to attain an expression for this inexact differential is more challenging. We must define the notion of Carnot cycle (which predates the first law) and says that a maximally efficient transfer of heat occurs between two reservoirs when the following relationship is manifest
$$\frac{Q_1}{Q_2} = \frac{T_1}{T_2}$$
where $Q_i$ is the heat transferred from the $i$-th reservoir at temperatuvre $T_i$ through a Carnot cycle. From here we may postulate that any heat transfer may be decomposed into infinitessimal Carnot cycles giving
$$\frac{dQ_1}{T_1} = \frac{dQ_2}{T_2}.$$
For a reversible process we have
$$\oint \frac{dQ}{T_R} = 0$$
but if the process is irreversible we have
$$\oint \frac{dQ}{T_R} \leq 0$$
which is known as Clausius' Inequality. If one then quantifies this measure which takes us away from the optimal reversibility of a Carnot cycle and calls it entropy one has
$$ \Delta S_{A \rightarrow B} \geq \int^{B}_{A} \frac{dQ}{T}$$
or $dQ = TdS$ as you state for cyclic, reversible processes.
And so, $\delta W$ and $\delta Q$ cannot be interchanged because they refer to different quantities that describe different phenomena. And as such are expressed in and originate from different concepts. One from phenomenology, the other from the Carnot cycle.


text:
Q: FitBit integration,after allowing permission safari is not redirecting to app I'm new to iOS development. I'm trying to integrate Fitbit in my app. I followed get authorization from Fitbit using Oauth in iOS and FitBit documentation. I used following code
- (IBAction)fitbitLogin:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=xyxyxy&redirect_uri=xxxxx&scope=activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight"]];

}

It launches the Safari app and I fill my credentials and tap Allow means an error is showing in Safari like "Safari cannot open the page because address is invalid". I'm new to iOS development and don't know how to proceed further. Can some one help me to solve this. thanks in advance.

A: Adding following function in AppDelegate solved my problem, hope it works for you too.
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let notification = Notification(name: Notification.Name(rawValue: "NotificationString"), object: nil, userInfo: [UIApplicationLaunchOptionsKey.url:url])
    NotificationCenter.default.post(notification)
    return true
}


text:
Q: Trying to acquireTokenSilentAsync from android app I'm currently using

implementation 'com.microsoft.identity.client:msal:1.4.0'

to connect to the app via azure , my acquireToken() works fine and I get the user in response ( I save it in the SharedPrefs)
After that (next login) I'm trying to do acquireTokenSilentAsync like so :
      SharedPreferences pref = getSharedPreferences();

      Gson gson = new Gson();
      String json = pref.getString("IAccount", "");

      if(!json.isEmpty()){
          Account account = gson.fromJson(json, Account.class);
          AcquireTokenSilentParameters parameters = new AcquireTokenSilentParameters.Builder()
              .withScopes(Arrays.asList(scopes))
              .forAccount(account)
              .fromAuthority(getAuthority())
              .withCallback(getSilentAuthInteractiveCallback())
              .build();
          application.acquireTokenSilentAsync(parameters);
      }

And get to the onError callback with the exception of :
>  E/onError: exception : com.microsoft.identity.client.Account cannot be cast to com.microsoft.identity.client.MultiTenantAccount

Any ideas what's missing ?
Much Appreciated.

A: This page may help:
https://learn.microsoft.com/en-us/azure/active-directory/develop/accounts-overview
In particular, they don't use a Gson and they cast the account to prevent the exception you get in their example code.
I would start by trying to cast like this:
IMultiTenantAccount multiTenantAccount = (IMultiTenantAccount)account;

and using that as the argument in forAccount().


text:
Q: Efficient image dilation in TensorFlow I'm looking for an efficient way to implement morphological image dilation with a square kernel in TensorFlow.  It looks like the obvious ways of doing it are extremely inefficient compared to what they could be, as shown by OpenCV.  See results of running source code pasted at bottom - even the fastest method is about 30x slower than OpenCV.  These are from MacBook Air with M1 chipset.
Dilation of 640x480 image with a 25x25 kernel took:
  0.61ms using opencv
  545.40ms using tf.nn.max_pool2d
  228.66ms using tf.nn.dilation2d naively
  17.63ms using tf.nn.dilation2d with row-col

Question: Does anyone know of a way to do image-dilation with TensorFlow that isn't extremely inefficient?
Source Code for current solutions:
import numpy as np
import cv2
import tensorflow as tf
import time

def tf_dilate(heatmap, width: int, method: str = 'rowcol'):
    """ Dilate the heatmap with a square kernel """
    if method=='maxpool':
        return tf.nn.max_pool2d(heatmap[None, :, :, None], ksize=width, padding='SAME', strides=(1, 1))[0, :, :, 0]
    elif method == 'naive_dilate':
        return tf.nn.dilation2d(heatmap[None, :, :, None], filters=tf.zeros((width, width, 1), dtype=heatmap.dtype),
                                        strides=(1, 1, 1, 1), padding="SAME", data_format="NHWC", dilations=(1, 1, 1, 1))[0, :, :, 0]
    elif method == 'rowcol_dilate':

        row_dilation = tf.nn.dilation2d(heatmap[None, :, :, None], filters=tf.zeros((1, width, 1), dtype=heatmap.dtype),
                                        strides=(1, 1, 1, 1), padding="SAME", data_format="NHWC", dilations=(1, 1, 1, 1))
        full_dilation = tf.nn.dilation2d(row_dilation, filters=tf.zeros((width, 1, 1), dtype=heatmap.dtype),
                                         strides=(1, 1, 1, 1), padding="SAME", data_format="NHWC", dilations=(1, 1, 1, 1))
        return full_dilation[0, :, :, 0]
    else:
        raise NotImplementedError(f'No method {method}')

def test_dilation_options(img_shape=(480, 640), kernel_size=25):

    img = np.random.randn(*img_shape).astype(np.float32)**2

    def get_result_and_time(version: str):

        tf_image = tf.constant(img, dtype=tf.float32)
        t_start = time.time()
        if version=='opencv':
            result = cv2.dilate(img, kernel=np.ones((kernel_size, kernel_size), dtype=np.float32))
            return time.time()-t_start, result
        else:
            result = tf_dilate(tf_image, width=kernel_size, method=version)
            return time.time()-t_start, result.numpy()

    t_opencv, result_opencv = get_result_and_time('opencv')
    t_maxpool, result_maxpool = get_result_and_time('maxpool')
    t_naive_dilate, result_naive_dilate = get_result_and_time('naive_dilate')
    t_rowcol_dilate, result_rowcol_dilate = get_result_and_time('rowcol_dilate')
    assert np.array_equal(result_opencv, result_maxpool), "Maxpool result did not match opencv result"
    assert np.array_equal(result_opencv, result_naive_dilate), "Naive dilation result did not match opencv result"
    assert np.array_equal(result_opencv, result_rowcol_dilate), "Row-col dilation result did not match opencv result"
    print(f'Dilation of {img_shape[1]}x{img_shape[0]} image with a {kernel_size}x{kernel_size} kernel took: '
          f'\n  {t_opencv*1000:.2f}ms using opencv'
          f'\n  {t_maxpool*1000:.2f}ms using tf.nn.max_pool2d'
          f'\n  {t_naive_dilate*1000:.2f}ms using tf.nn.dilation2d naively'
          f'\n  {t_rowcol_dilate*1000:.2f}ms using tf.nn.dilation2d with row-col'
          )

if __name__ == '__main__':
    test_dilation_options()

A: Well if you're fine with an approximate solution, there is always "poor man's dilate", which approximates dilation using a weighted local average (a box filter), where weights are taken by exponentiating the image.  It's O((H+K)*(W+K)) where W,H are image width, height, and K is kernel size.
It also has the benefit that the gradient flows not just through the local maxima, but through the contenders to the thrown as well.
See code:
TensorImage = NewType('TensorImage', tf.Tensor)  # A (height, width, n_colors) uint8 image
TensorFloatImage = NewType('TensorFloatImage', tf.Tensor)
TensorHeatmap = NewType('TensorHeatmap', tf.Tensor)  # A (height, width) heatmap

def tf_box_filter(image: Union[TensorImage, TensorFloatImage, TensorHeatmap], width: int, normalize: bool = True, weights: Optional[TensorHeatmap] = None,
                  weight_eps: float = 1e-6, norm_weights: bool = True):
    image = tf.cast(image, tf.float32) if image.dtype != tf.float64 else image
    if weights is not None:
        if norm_weights:
            weights = weights/(width**2)
        if len(image.shape) == 3:
            weights = weights[:, :, None]  # Lets us broadcast weights against image

        image = image * weights

    lwidth = width // 2 + 1
    rwidth = width - lwidth

    integral_image_container = tf.pad(image,
                                      paddings=[(lwidth, rwidth), (lwidth, rwidth)] + [(0, 0)] * (len(image.shape) - 2))
    integral_image_container = tf.cumsum(tf.cumsum(integral_image_container, axis=0), axis=1)
    box_image = integral_image_container[width:, width:] \
                - integral_image_container[width:, :-width] \
                - integral_image_container[:-width, width:] \
                + integral_image_container[:-width, :-width]

    if not normalize:
        return box_image if (weights is None or not norm_weights) else box_image*(width**2)
    elif weights is None:
        return box_image / (width ** 2)
    else:
        box_weights = tf_box_filter(weights, width=width, normalize=False)
        return (box_image + weight_eps) / (box_weights + weight_eps)

def tf_poor_mans_dilate(heatmap: TensorHeatmap, width: int, power: int = 4, cast_to_64 = False) -> TensorHeatmap:
    """ A 'poor man's' version of dilation, whise runtime is O((image_height+kernel_width), (image_width+kernel_width))"""
    if cast_to_64:
        heatmap = tf.cast(heatmap, tf.float64)
    return tf_box_filter(heatmap, width, weights=heatmap**power, weight_eps=1e-9)

A test reveals it to be around 3x faster than the solutions in the question (more when kernel is large).

def test_poor_mans_dilate(show=False):
    """ Can be faster for large images and kernels

    Dilating image of shape (1280, 720) with kernel of shape 40x40
        Real Dilate: Elapsed time is 0.09009s
        Poor Man's Dilate: Elapsed time is 0.02953s

    Dilating image of shape (640, 480) with kernel of shape 40x40
        Real Dilate: Elapsed time is 0.03089s
        Poor Man's Dilate: Elapsed time is 0.008736s

    Dilating image of shape (640, 480) with kernel of shape 20x20
        Real Dilate: Elapsed time is 0.01475s
        Poor Man's Dilate: Elapsed time is 0.009809s
    """
    img = tf.random.Generator.from_seed(1234).normal((640, 480))**4
    width = 20
    print(f'Dilating image of shape {img.shape} with kernel of shape {width}x{width}')
    with profile_context('Real Dilate', print_result=True):
        dil_img = tf_dilate(img, width=width)
    with profile_context("Poor Man's Dilate", print_result=True):
        poor_dil_img = tf_poor_mans_dilate(img, width=width)

    assert np.allclose(dil_img.numpy().max(), poor_dil_img.numpy().max(), rtol=0.001)


text:
Q: unix: files starting with - wildcard I want to rm or cp a bunch of files with common extensions, some of them start with a - and so unix complains about unknown options. What can I do?
rm *csv

A: man rm:
To remove a file whose name starts with a '-', for example '-foo',
use one of these commands:

       rm -- -foo

       rm ./-foo

So:
$ touch -- -test test
$ rm -- *test
rm: remove regular empty file 'test'? y
rm: remove regular empty file '-test'? y
$

A: Also, quoting works to inhibit globbing if there's, say, a literal asterisk in the name:
rm "*cvs"

Sometimes it might be useful to use the interactive option and confirm the file you want to delete:
rm -i -- *

This is handy if filenames have characters hard to type on your keyboard.


text:
Q: Insert and resize images in the Text widget : problems HTML pages written by Word are horrible. So I'm making myself a little tool to capture my texts and convert them into HTML. I insert the images divided by 4 by choosing them with Listbox. Afterwards, I still adjust its size with a Scale. It almost works, but there is still a problem. I have to put the function which reduces in stop with an input, otherwise the image goes away. And what is strange, its format remains! She just became some sort of image-sized space character. Does anyone understand what is going on? I had the idea of an input. You see in my code an input('——') with which it works. Without even hitting a key. But of course, that's definitely not the way to do it! Besides, I have runtime errors: can't re-enter readline
A second problem seems to have the same nature: if I insert a second image elsewhere in the text, the first disappears, under the same conditions, its location remains.
def insertionImage(self):
    def choisir(event) :
        self.liste.unbind("<Return>")
        print("choisir")
        posit =  self.liste.curselection()
        self.nom_fichier = self.liste.get(posit[0])
        self.chemin_nom = 'static/img/' + self.nom_fichier
        self.im = Image.open(self.chemin_nom)
        self.larg, self.haut = self.im.width//2, self.im.height//2
        self.im_quart = self.im.resize([self.larg, self.haut])
        self.photo = ImageTk.PhotoImage(image = self.im_quart)
        self.ascenseur.grid_remove()
        self.liste.grid_remove()
        self.la = "1.0"
        if self.insertion_texte :
            self.lab1 = Label(self, text = "click\on the text\n where you insert\nthe image.")
            self.lab1.grid(row = 2, column = 10)
            self.clic = "insertion_image"
            self.text.bind("<Button-1>", self.situer)

        else :
            self.text.image_create(self.la, image = self.photo)
            b=input(" --choisir_else-- ")
            self.lab2 = Label(self, text = "validate\n the photo\n and its size")
            self.lab2.grid(row = 2, column = 10)
            self.lab2.bind("<Button-1>", self.validerPhoto)

    self.boiteListe("img")
    self.liste.bind("<Return>", choisir)

    for n in self.noms :
        self.liste.insert('end', n)

    self.reg = Scale(self, length = 150, orient = HORIZONTAL, resolution = 0.05, tickinterval = 0.2,
                            sliderlength = 10, width = 10, from_ = 1, to = 0.1)
    self.reg.set(1)
    self.reg.configure(command = self.reduire)
    self.reg.grid(row = 1, column = 10)

def reduire(self, event):
    reduc = self.reg.get()
    facteur = 1 / reduc
    l, h  = int(self.larg / facteur), int(self.haut / facteur)
    i = ImageTk.PhotoImage(self.im.resize([l, h]))
    self.text.delete(self.la)
    self.text.image_create(self.la, image =i)
    b=input(" --reduire-- ")

I tried to understand. Without success.


text:
Q: How to maintain stateful in yaws I have some process (spawned) with state.
How to maintain simple stateful service in yaws?
How to implement communication to process in "appmods" erl source file?
update:
let's we have simple process
start() -> loop(0).

loop(C) ->
  receive
    {inc} -> loop(C + 1);
    {get, FromPid} -> FromPid ! C, loop(C)
  end.

What is the simplest (trivial: without gen_server, yapp) way to access process from web?
Maybe, I need a minimal example with gen_server+yapp+yaws / appmods+yaws.

A: The #arg structure is a very important datastructure for the yaws programmer.
In the ARG of Yaws out/1 there is a variable that can save user state.
"state,          %% State for use by users of the out/1 callback"
You can get detail info here .

A: There only 2 ways to access a process in Erlang: Either you know its Pid (and the node where you expect the process to be) or You know its registered Name (and the erlang node its expected to be).
Lets say you have your appmod:
-module(myappmod).
-export([out/1]).
-include("PATH/TO/YAWS_SERVER/include/yaws_api.hrl").
-include("PATH/TO/YAWS_SERVER/include/yaws.hrl").
out(Arg) ->
   case check_initial_state(Arg) of
       unknown -> create_initial_state();
       {ok,Value}->
              UserPid = list_to_pid(Value),
              UserPid ! extract_request(Arg),
              receive
                Response -> {html,format_response(Response)}
              after ?TIMEOUT -> {html,"request_timedout"}
              end
   end.
check_initial_state(A)->
   CookieObject = (A#arg.headers)#headers.cookie,
   case yaws_api:find_cookie_val("InitialState", CookieObject) of
        [] -> unkown;
        Cookie -> {ok,Cookie}
   end.
extract_request(Arg)-> %% get request from POST Data or Get Data
 Post__data_proplist = yaws_api:parse_post(Arg),
 Get_data_proplist = yaws_api:parse_query(Arg),
 %% do many other things....
 Request = remove_request(Post__data_proplist,Get_data_proplist),
 Request.

That simple set up shows you how you would use processes to keep things about a user. However, the use of processes is not good. Processes do fail, so you need a way of recovering what data they were holding.
A better approach is to have a Data storage about your users and have one gen_server to do the look ups. You could use Mnesia. I do not advise you to use processes on the web to keep user state, no matter what kind of app you are doing, even if its a messaging app. Mnesia or ETS tables can keep state and all you need to do is look up.

Use a better storage mechanism to keep state other than processes. Processes are a point of failure. Others use Cookies (and/or Session cookies), whose value is used in some way to look up something from a database. However, if you insist that you need processes, then, have a way of remembering their Pids or registered names. You could store a user Pid into their session cookie e.t.c.


text:
Q: Selector for filtered items with jQuery tableSorter plugin This got into my head lately and honestly I think its worth asking. Here is the thingy..
I have a table , just like any other ordinary table with jquery tablesorter plugin with the filter widget.   On the very right of the table columns I've put a checkbox and above that column, on the table headers on that columhn I have another checkbox which has a function  linked to it, so that when it gets clicked all the checkboxes get updated with this checkbox's value .
This is not very fancy or sophisticated and I have two way of accomplishing this .. either using a jquery selector or plain old javascript.
so here is what I want todo .. I want to filter elements of the table, then click the checkbox on the header , and I want to affect the row's checkboxes that were filtered with the plugin.
anyone has something to say about this?
thanks .

A: I already have a demo set up for that here
$( function() {
    // using .on() which requires jQuery 1.7+
    $( 'table' ).on( 'tablesorter-initialized', function() {

        // class name to add on tr when checkbox is checked
        var highlightClass = 'checked',
        // resort the table after the checkbox is modified?
        resort = true,
        // if a server side database needs to be updated, do it here
        serverCallback = function( table, inputElement ) {},

        $table = $( this ),
        c = this.config,
        wo = c && c.widgetOptions,
        // include sticky header checkbox; if installed
        $sticky = c && wo.$sticky || '',
        doChecky = function( c, col ) {
            $table
                .children( 'tbody' )
                .children( 'tr:visible' )
                .children( 'td:nth-child( ' + ( parseInt( col, 10 ) + 1 ) + ' )' )
                .find( 'input[type=checkbox]' )
                .each( function() {
                    this.checked = c;
                    $( this ).trigger( 'change' );
                });
        };

        $table
            .children( 'tbody' )
            .on( 'change', 'input[type=checkbox]', function() {
                // ignore change if updating all rows
                if ( $table[0].ignoreChange ) { return; }
                var col, $this = $( this );
                $this.closest( 'tr' ).toggleClass( highlightClass, this.checked );
                $this.trigger( 'updateCell', [ $this.closest( 'td' ), resort ] );
                // if your server side database needs more parameters, add them here sent to the callback
                serverCallback( $table[0], this );
                // uncheck header if any checkboxes are unchecked
                if ( !this.checked ) {
                    $table.add( $sticky ).find( 'thead input[type=checkbox]' ).prop( 'checked', false );
                }
            })
            .end()
            .add( $sticky )
            .find( 'thead input[type=checkbox]' )
            // Click on checkbox in table header to toggle all inputs
            .on( 'change', function() {
                // prevent updateCell for every cell
                $table[0].ignoreChange = true;
                var c = this.checked,
                    col = $( this ).closest( 'th' ).attr( 'data-column' );
                doChecky( c, col );
                // update main & sticky header
                $table.add( $sticky ).find( 'th[data-column=' + col + '] input[type=checkbox]' ).prop( 'checked', c );
                $table.children( 'tbody' ).children( 'tr:visible' ).toggleClass( highlightClass, c );
                // update all at once
                $table[0].ignoreChange = false;
                $table.trigger( 'update', [ resort ] );
            })
            .on( 'mouseup', function() {
                return false;
            });

    });

    $('table').tablesorter({
        theme: 'blue',
        widgets: ['zebra', 'stickyHeaders','filter'],
        headers: {
            0: { sorter: 'checkbox' }
        }
    });
});

Just make sure to include the parser-input-select.js file


text:
Q: How to compare a couple binary bytes in code? I read a binary file and want to make sure that some specific bytes have some specific value. What's the most perl way of doing this?
my $blob = File::Slurp::read_file( 'blob.bin', {binmode=>'raw'} );
substr( $blob, 4, 4 ) == #equals what?

I want to test if bytes 5-8 equal 0x32 0x32 0x00 0x04. What should I compare the substr to?

A: substr( $blob, 4, 4 ) eq "\x32\x32\x00\x04"

If it's a 32-bit unsigned number, you might prefer the following:
unpack( "N",  substr( $blob, 4, 4 ) ) == 0x32320004   # Big endian
unpack( "L>", substr( $blob, 4, 4 ) ) == 0x32320004   # Big endian
unpack( "L<", substr( $blob, 4, 4 ) ) == 0x04003232   # Little endian
unpack( "L",  substr( $blob, 4, 4 ) ) == ...          # Native endian

(Use l instead oaf L for signed 32-bit ints.)
substr can even be avoided when using unpack.
unpack( "x4 N", $blob ) == 0x32320004

You could also use a regex match.
$blob =~ /^.{4}\x32\x32\x00\x04/s

$blob =~ /^ .{4} \x32\x32\x00\x04 /sx

my $packed = pack( "N", 0x32320004 );
$blob =~ /^ .{4} \Q$packed\E /sx


text:
Q: Convert Grails Application to Plugin I read this question but it didn't answer the way I was hoping so I'm posting a similar question with a few more details.
I have a grails application that I need to turn into a plugin, but I'd like to know if this can be done without creating a new plugin and copying files.  Assuming the application name is 'admin' I created a AdminGrailsPlugin.groovy file in the root and copied the contents of another plugin's file and changed names accordingly.  I ran a package-plugin which generated the plugin.xml and the zip file.  So I assumed things were going to work.  However, when I tried to use this plugin in an application using the inline plugin mechanism, I'm not able to access any of the plugin's controllers.  They all have their own URL Mappings in the plugin's URLMappings.groovy file.
Is there a piece to this puzzle that I am missing?
UPDATE: I added one of the admin plugin's URL Mappings to the applications URLMappings.groovy and things seem to work from there.  At least for that controller.  So not sure why the plugin's URLMappings.groovy is being ignored?

A: Ok, after some more searching I discovered that in a plugin, UrlMappings.groovy is ignored.  I renamed it to AdminUrlMappings.groovy and now it works like a champ.  I'm going to go check JIRA for a bug because my other plugin's mapping class is called UrlMappings when, in my opinion, if I run 'grails run-app common' I should get CommonUrlMappings.groovy.  But that doesn't happen.


text:
Q: pgadmin4 Ver 3.0 not starting on windows 10 for a PostgreSQL project I installed pgadmin 4 Ver. 3.0 on a Windows 10 computer.
Anyhow pgadmin does not start and I get the following error from the Internet Explorer Browser:
"Cannot reach this page. Make sure the web address http://127.0.0.1:56575 is correct.".
I've been using PgAdmin 4 Ver 2.1 for some time without issues, and have uninstalled it before installing the Ver 3.0.
Any help would be appreciated.
Regards,

A: For PGadmin 4 Ver 3.0 you need to completely start afresh. Remove any old shortcuts and make a new one. You need to locate where PGadmin was installed and make a new shortcut with a target and path like ""C:\Program Files (x86)\pgAdmin 4\v3\runtime\pgAdmin4.exe".
For anyone else viewing this, make sure you do an uninstall of the old PGadmin before installing the new one.
Further, you may not be able to get an SQL window running unless you allow it through addblockers etc


text:
Q: Data inside tableview are mixed-up after scrolling I've read many questions and tried the solutions but I still couldn't resolve the problem with my tableview.
After scrolling, the data in the rows of the tableview got interchanged and sometimes missing.
Here's my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *modifierCheckCell = @"BGMModifierCheckCell";

    BGMModifierCheckCell *cell = nil;
    cell = (BGMModifierCheckCell *)[tableView dequeueReusableCellWithIdentifier:modifierCheckCell];

    if (cell == nil) {

        NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:modifierCheckCell owner:self options:nil];
        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[UITableViewCell class]]) {
                cell = (BGMModifierCheckCell *)currentObject;
                break;
            }
        }

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        NSArray *optionIds = [[[arrayInsideDict objectAtIndex:indexPath.section] objectForKey:@"optnItem"] objectAtIndex:indexPath.row];

        BGMOptnCats *optnCat = [BGMOptnCats MR_findFirstByAttribute:@"iOptnCatId" withValue:[[arrayInsideDict objectAtIndex:indexPath.section] objectForKey:@"optnCatId"]];

        [optionIds enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

            __block int optnTag = [obj intValue];

            BGMItemDayOptns *item = [BGMItemDayOptns MR_findFirstByAttribute:@"iItemDayOptnId" withValue:obj];

            [item.optns.optnLangs enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {

                BGMOptnLangs *lang = (BGMOptnLangs *)obj;

                if ([lang.sLangCode isEqualToString:@"en"]) {

                    NSString *optn = [NSString stringWithFormat:@"%@", lang.sOptnName];

                    if ([optnCat.sOptnType isEqualToString:@"single"]) {

                        RadioButton *rb1                   = [[RadioButton alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
                        [rb1 setGroupID:indexPath.section AndID:optnTag AndTitle:optn];
                        rb1.delegate                    = self;

                        if (idx == 0) {

                            [cell.firstOption addSubview:rb1];

                        } else if (idx == 1) {

                            [cell.secondOption addSubview:rb1];

                        } else if (idx == 2) {

                            [cell.thirdOption addSubview:rb1];

                        }

                    } else if ([optnCat.sOptnType isEqualToString:@"multiple"]) {

                        SSCheckBoxView *checkBox = [[SSCheckBoxView alloc] initWithFrame:CGRectMake(0, 0, 200, 40) style:kSSCheckBoxViewStyleMono checked:NO];
                        checkBox.tag = optnTag;
                        [checkBox setStateChangedTarget:self selector:@selector(checkBoxViewChangedState:)];
                        [checkBox setText:@""];
                        [checkBox setText:optn];

                        if (idx == 0) {

                            [cell.firstOption addSubview:checkBox];

                        } else if (idx == 1) {

                            [cell.secondOption addSubview:checkBox];

                        } else if (idx == 2) {

                            [cell.thirdOption addSubview:checkBox];

                        }

                    }

                }

            }];

        }];

    }

    return cell;

}

A: The problem is that your cells are being reused. So the rows are interchanged when scrolling.
Set the cell content outside of the if (cell == nil).
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *modifierCheckCell = @"BGMModifierCheckCell";

    BGMModifierCheckCell *cell = nil;
    cell = (BGMModifierCheckCell *)[tableView dequeueReusableCellWithIdentifier:modifierCheckCell];

    if (cell == nil) {

        NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:modifierCheckCell owner:self options:nil];
        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[UITableViewCell class]]) {
                cell = (BGMModifierCheckCell *)currentObject;
                break;
            }
        }
     }

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        NSArray *optionIds = [[[arrayInsideDict objectAtIndex:indexPath.section] objectForKey:@"optnItem"] objectAtIndex:indexPath.row];

        BGMOptnCats *optnCat = [BGMOptnCats MR_findFirstByAttribute:@"iOptnCatId" withValue:[[arrayInsideDict objectAtIndex:indexPath.section] objectForKey:@"optnCatId"]];

        [optionIds enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

            __block int optnTag = [obj intValue];

            BGMItemDayOptns *item = [BGMItemDayOptns MR_findFirstByAttribute:@"iItemDayOptnId" withValue:obj];

            [item.optns.optnLangs enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {

                BGMOptnLangs *lang = (BGMOptnLangs *)obj;

                if ([lang.sLangCode isEqualToString:@"en"]) {

                    NSString *optn = [NSString stringWithFormat:@"%@", lang.sOptnName];

                    if ([optnCat.sOptnType isEqualToString:@"single"]) {

                        RadioButton *rb1                   = [[RadioButton alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
                        [rb1 setGroupID:indexPath.section AndID:optnTag AndTitle:optn];
                        rb1.delegate                    = self;

                        if (idx == 0) {

                            [cell.firstOption addSubview:rb1];

                        } else if (idx == 1) {

                            [cell.secondOption addSubview:rb1];

                        } else if (idx == 2) {

                            [cell.thirdOption addSubview:rb1];

                        }

                    } else if ([optnCat.sOptnType isEqualToString:@"multiple"]) {

                        SSCheckBoxView *checkBox = [[SSCheckBoxView alloc] initWithFrame:CGRectMake(0, 0, 200, 40) style:kSSCheckBoxViewStyleMono checked:NO];
                        checkBox.tag = optnTag;
                        [checkBox setStateChangedTarget:self selector:@selector(checkBoxViewChangedState:)];
                        [checkBox setText:@""];
                        [checkBox setText:optn];

                        if (idx == 0) {

                            [cell.firstOption addSubview:checkBox];

                        } else if (idx == 1) {

                            [cell.secondOption addSubview:checkBox];

                        } else if (idx == 2) {

                            [cell.thirdOption addSubview:checkBox];

                        }

                    }

                }

            }];

        }];

    return cell;

}

A: you need to remove your subviews because each time CellForRowAtIndexpath is called it will create a subview  so before adding new subview remove the previous one
for (UIView *view in cell.contentView.subviews) {
                    [view removeFromSuperview];
                }


text:
Q: How to post form data on an UTF-8 page to a western european (ISO) page I need to post a form on a new website which is UTF-8 encoded. The problem is - i need to post it to a legacy site encoded with western european (iso). Certain characters gets messed up in the post (like danish special characters).
It is not possible to change the character encoding on the legacy website as it would definately break stuff on the old site (so that's a no-go). I might be able to do some magic with the data (some branching on input) on the legacy site, but that would be the fallback solution.
I have jquery on the client to help with whatever possible encoding tricks would be possible there.
I see a possible solution of actually posting from the new UTF-8 page to another new page that changes the encoding server-side and reposting it to the legacy site, but that just seems ugly...
The new site is running asp.net mvc and the old legacy is classic asp (not asp.net) if that makes a difference (i hope it doesn't since i'd really like to handle stuff client-side).

A: IIUC, it doesn't really matter what the web pages on the old site are encoded in, as the form will be on the new site. What matters is what encoding the server of the old site expects. And if the server expects the data to be submitted in latin-1, you only have two choices:

*

*change the server to acccept the data in UTF-8 (perhaps under a different URL)

*make sure the client submits the data in Latin-1

As you have ruled out option 1, your only choice is option 2 (but do reconsider doing option 1). For option 2, you again have choices, one being to use a proxy as you propose. However, it would probably be better if the page containing the form was encoded in Latin-1 (despite the rest of the site being UTF-8). This should work well if you don't want to display non-latin-1 information on the page (such as Chinese text). You just have to explain to asp.net that this specific page should be rendered in latin-1 (and the web server should send an appropriate Content-type).

A: You can control the encoding used in the form, regardless of the encoding of the hosting page. For example,
  <form accept-charset="latin-1" ... >

A: Ok so we ended up url encoding the data before submitting it to the landing page.
This solved the two problems the other solutions had of 1) an extra landing/jump-page to transform the values and 2) of not rewriting a large part of the old legacy (which is being migrated) site to accept UTF-8
Anyways we put the logic of submitting data from out site to the legacy site into a jquery plugin, which handles any form elements in the form by escaping each value before posting the form - actually the landing/old page requires the data in GET format, so we just end up setting window.location to the resulting querystring - but i guess we might as well have submitted the form with a normal POST if we wanted to.


text:
Q: System Administrator? Or Systems Administrator? I've seen both variations in job titles. Which do you use?

A: I use Systems Administrator because I look after a number of different systems whether you look at it from OS (Windows, Linux, Mac) or at an application level (more than I care to list).

A: Unless you're looking after one monolithic system, it's "Systems Administrator"

A: It should (IMO) be "Systems." Even if you are only looking after one giant "system" you have to take into consideration enough individual aspects that are on their own individual systems.

A: Systems Administrator

A: It should always be Systems Administrator. Even a single computer can be considered as several systems (like for example a server running multiple virtualized OS).
My college degree has Systems Administration in it as well.


text:
Q: Use Excel VBA to open Word document and use Find method to find a string and replace all to another string, it doesn't take effect My objective:
Use Excel VBA to open Word document and use Find method to find a string and replace all to another string
My input file content: ("C:\Temp\testWord1.doc")

Code in Excel VBA:
Private Sub testReplaceWordFile()
    Dim oWrdApp
    Dim doc1
    On Error Resume Next

    Set oWrdApp = CreateObject("word.application")
    Set doc1 = oWrdApp.Documents.Open(FileName:="C:\Temp\testWord1.doc", ReadOnly:=False)

    Debug.Print doc1.Content.Text
    With doc1.Content.Find
        .Text = "PsWD"
        .Replacement.Text = "Test"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = True
        .Execute Replace:=wdReplaceAll
    End With
    Debug.Print "==========================="
    Debug.Print doc1.Content.Text

    doc1.Save
    doc1.Close
    oWrdApp.Quit

    If Err.Number = 0 Then
        Debug.Print "done"
    Else
        Debug.Print "error:" & Err.Description
        Err.Clear
    End If
    On Error GoTo 0
End Sub

Problem:

*

*My expectation is: after execute the code, all "PsWD" will be placed with "Test". We should also see the change of "doc1.Content.Text" before and after executing ".Execute Replace:=wdReplaceAll"

*Actual is: no change on the doc file, the code ".Execute Replace:=wdReplaceAll" doesn't take effect

Help required:
Please help to advise what's the issue of the code. Thanks.


text:
Q: JComboBox action won't perform Let say the user chose petrol stations. The frame will change and the user will be able to choose a location and the list of petrol stations in that location will appear below the combobox.
So I've tried adding another action listener inside the if statement, using another if else and I also tried switch statements but both won't show the output. So how do I solve this? Thanks in advance.
This is the shortened version of my code before adding the 2nd action listener
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Testing5 {
private JFrame frame1, frame2;
private ActionListener action, action2;
private JButton PetrolStations, back, Foods;
private JComboBox locationChooser;
final static String[] location = {"Petaling Jaya", "Port Klang", "Kuala Lumpur"};

public void  HELPMEGUI() {

    frame1 = new JFrame("Frame 1");
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel contentPanel = new JPanel(new GridLayout(5,2));

    PetrolStations = new JButton ("PetrolStations");
    Foods = new JButton ("Foods");
    back = new JButton ("Back");

    locationChooser = new JComboBox(location);

    action = new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JButton button = (JButton) ae.getSource();

            if (button == PetrolStations) {
                frame2 = new JFrame("FRAME 2");
                frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame2.add(locationChooser, BorderLayout.NORTH);
                frame2.add(back, BorderLayout.SOUTH);

                frame2.setSize(300, 300);
                frame2.setLocationRelativeTo(null);
                frame2.setVisible(true);
                frame1.setVisible(false);

            }

            else if (button == Foods) {
                frame2 = new JFrame("FRAME 2");
                frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame2.add(locationChooser, BorderLayout.NORTH);
                frame2.add(back, BorderLayout.SOUTH);

                frame2.setSize(300, 300);
                frame2.setLocationRelativeTo(null);
                frame2.setVisible(true);
                frame1.setVisible(false);

            }

            else if (button == back ) {
                frame1.setVisible(true);
                frame2.setVisible(false);
                frame2.dispose();
            }
        }
    };

    PetrolStations.addActionListener(action);
    Foods.addActionListener(action);
    back.addActionListener(action);
    locationChooser.addActionListener(action2);

    contentPanel.add(PetrolStations);
    contentPanel.add(Foods);

    frame1.getContentPane().add(contentPanel);
    frame1.setSize(640, 400);
    frame1.setVisible(true);
    frame1.setLocationRelativeTo(null);

}

public static void main(String...args) {
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            new Testing5().HELPMEGUI();
        }
    });
}

}

EDIT:
This is what I tried to do
 action2 = new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        JComboBox locationSelected = (JComboBox) e.getSource();

                        if (locationSelected == Kuala Lumpur ) {
                            System.out.println("Address 1");
                        }
                    }
                };

2nd try
   action2 = new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                     int temp;

                     if(e.getSource() == locationChooser) {
                         temp = locationChooser.getSelectedIndex();

                         switch (temp) {
                         case 0: System.out.println("Address 1"); break;
                         case 1: System.out.println("Address 2"); break;
                         }
                     }
                    }
                    };}

A: You don't show the context of your action listener definition, so I think you might have it in the wrong place.  Here's how I did it, and it seems to work:
    PetrolStations.addActionListener(action);
    Foods.addActionListener(action);
    back.addActionListener(action);
    action2 = new ActionListener() {
        public void actionPerformed(ActionEvent e)
        {
            int temp;

            if (e.getSource() == locationChooser) {
                temp = locationChooser.getSelectedIndex();

                switch (temp) {
                    case 0:
                        System.out.println("Address 1");
                        break;
                    case 1:
                        System.out.println("Address 2");
                        break;
                }
            }
        }
    };
    locationChooser.addActionListener(action2);


text:
Q: MLT messing up the orientation of video MLT is automatically changing the orientation of a portrait video to landscape. Is there a way to prevent it?

A: The real problem is that it is NOT auto-rotating your video. On a smartphone, the video is actually recorded in landscape mode, and then it sets metadata in the file to describe the orientation. If software does not read this and apply some transformation to rotate the video, then it appears incorrect. FFmpeg and then MLT only recently started to support this metadata and automatically do transformations. Obviously, FFmpeg came first, but it took a while for MLT, which only recently added support for it as of v6.2.0. If you have that version and built against recent enough FFmpeg, then it will work automatically. If you run melt some-video -consumer xml then you will see some metadata like
<property name="meta.media.0.codec.rotate">90</property>

In case you want to prevent automatic orientation, set the autorotate property to 0:
melt myvideo autorotate=0


text:
Q: Find the value of $(g-Pg)(x);x\in [0,1]$ Let $V$ be a closed subspace of $L^2[0,1]$ and let $f,g\in L^2[0,1]$ be given by $f(x)=x$ and $g(x)=x^2$.If $V^\perp=\operatorname{Span }f$ and $Pg$ is the orthogonal projection of $g$ on $V$,then $(g-Pg)(x);x\in [0,1]$
The problem is I can't get the meaning of orthogonal projection of an element of a vector space and as a result I can't proceed.
I surfed the internet but could not proceed .
Please provide some guidance on how to solve the problem

A: The formula for the orthogonal projector onto a 1D subspace is the same regardless of dimension. If $a$ is a nonzero vector in the subspace and $b$ is some other vector then
$$Pb=\frac{\langle a,b \rangle}{\| a \|^2} a.$$
In your case, if you take $a=x$ and $b=x^2$, then you get the orthogonal projector onto $V^\perp$. The orthogonal projector onto $V$ is then $I-P$.
As it happens, the formula for the orthogonal projector onto a finite dimensional subspace is also the same regardless of dimension, but that is not necessary for this problem.


text:
Q: Using Start and End Times of employee shifts, how can I create an array to show how many people are scheduled by 15 minute increments? Input Data: employee scheduled shifts given by employee ID, start time, and end time

Employee_ID
Start_Time
End_Time

1
202303150100000000000000
202303150245000000000000

2
202303150015000000000000
202303150700000000000000

3
202303150230000000000000
202303160100000000000000

Desired Output: dataframe or array with with a sum of how many people are scheduled by date and 15 minute increments (shifts can span more than one day and should carry over)

Date
12
12:15
12:30
12:45
0
0:15
0:30
0:45
1
1:15
1:30
1:45
2
2:15
2:30
2:45
3
...
24

3/15/2023
0
1
1
1
2
2
2
2
2
2
2
2
2
2
3
2
2
...
1

3/16/2023
1
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
...
0

So far I have figured out how to display the data in hourly increments, but this does not work properly when a shift starts or ends not exactly on the hour (ex: 2:45 start shift is recorded as 2:00 start)
Create hourly columns and fill with numPy's NA
df = df.assign(**{'0': np.nan, '1': np.nan, '2': np.nan, '3': np.nan, '4': np.nan, '5': np.nan,
           '6': np.nan, '7': np.nan, '8': np.nan, '9': np.nan, '10': np.nan, '11': np.nan,
          '12': np.nan, '13': np.nan, '14': np.nan, '15': np.nan, '16': np.nan, '17': np.nan,
         '18': np.nan, '19': np.nan, '20': np.nan, '21': np.nan, '22': np.nan, '23': np.nan})

df['0'] = (df['Start_Time']< 1) &  (1 <= df['End_Time'])
df['0'] = df['0'].astype(int)

df['1'] = (df['Start_Time']< 2) &  (2 <= df['End_Time'])
df['1'] = df['1'].astype(int)

df['2'] = (df['Start_Time']< 3) &  (3 <= df['End_Time'])
df['2'] = df['2'].astype(int)

df['3'] = (df['Start_Time']< 4) &  (4 <= df['End_Time'])
df['3'] = df['3'].astype(int)

df['4'] = (df['Start_Time']< 5) &  (5 <= df['End_Time'])
df['4'] = df['4'].astype(int)

df['5'] = (df['Start_Time']< 6) &  (6 <= df['End_Time'])
df['5'] = df['5'].astype(int)

df['6'] = (df['Start_Time']< 7) &  (7 <= df['End_Time'])
df['6'] = df['6'].astype(int)

df['7'] = (df['Start_Time']< 8) &  (8 <= df['End_Time'])
df['7'] = df['7'].astype(int)

df['8'] = (df['Start_Time']< 9) &  (9 <= df['End_Time'])
df['8'] = df['8'].astype(int)

df['9'] = (df['Start_Time']< 10) &  (10 <= df['End_Time'])
df['9'] = df['9'].astype(int)

df['10'] = (df['Start_Time']< 11) &  (11 <= df['End_Time'])
df['10'] = df['10'].astype(int)

df['11'] = (df['Start_Time']< 12) &  (12 <= df['End_Time'])
df['11'] = df['11'].astype(int)

df['12'] = (df['Start_Time']< 13) &  (13 <= df['End_Time'])
df['12'] = df['12'].astype(int)

df['13'] = (df['Start_Time']< 14) &  (14 <= df['End_Time'])
df['13'] = df['13'].astype(int)

df['14'] = (df['Start_Time']< 15) &  (15 <= df['End_Time'])
df['14'] = df['14'].astype(int)

df['15'] = (df['Start_Time']< 16) &  (16 <= df['End_Time'])
df['15'] = df['15'].astype(int)

df['16'] = (df['Start_Time']< 17) &  (17 <= df['End_Time'])
df['16'] = df['16'].astype(int)

df['17'] = (df['Start_Time']< 18) &  (18 <= df['End_Time'])
df['17'] = df['17'].astype(int)

df['18'] = (df['Start_Time']< 19) &  (19 <= df['End_Time'])
df['18'] = df['18'].astype(int)

df['19'] = (df['Start_Time']< 20) &  (20 <= df['End_Time'])
df['19'] = df['19'].astype(int)

df['20'] = (df['Start_Time']< 21) &  (21 <= df['End_Time'])
df['20'] = df['20'].astype(int)

df['21'] = (df['Start_Time']< 22) &  (22 <= df['End_Time'])
df['21'] = df['21'].astype(int)

df['22'] = (df['Start_Time']< 23) &  (23 <= df['End_Time'])
df['22'] = df['22'].astype(int)

df['23'] = (df['Start_Time']< 24) &  (24 <= df['End_Time'])
df['23'] = df['23'].astype(int)`

Group data and sum to specific dates (after parsing and formatting start and end dates)
df = df.groupby(['Start_Date','End_Date']).sum().reset_index()
df = df.drop(columns={'End_Date'})
df = df.rename(columns={'Start_Date':'Date'})
df['Date'] = pd.to_datetime(df['Date'])
df = df.groupby(['Date']).sum().reset_index()

A: The dataframe you gave as example does not give clear idea about the formatting, so I will make some assumption here. Considering the dataframe you have is something like this:
import pandas as pd

df = pd.DataFrame({
    'Employee id': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
    'Shift start': ['2023-02-14 08:00:00', '2023-02-14 09:30:00', '2023-02-14 12:00:00',
                    '2023-02-14 13:00:00', '2023-02-15 16:00:00', '2023-02-15 18:00:00',
                    '2023-02-17 10:00:00', '2023-02-17 14:00:00'],
    'Shift end': ['2023-02-14 16:00:00', '2023-02-14 17:30:00', '2023-02-14 18:00:00',
                  '2023-02-14 19:00:00', '2023-02-15 20:00:00', '2023-02-15 22:00:00',
                  '2023-02-17 18:00:00', '2023-02-17 19:00:00']
})

This function will do the job, but not in the prettiest way. I am sure there are many ways to optimize this:
def count_employees_per_15_min_interval(df):
    # convert string columns to datetime format
    df['Shift start'] = pd.to_datetime(df['Shift start'])
    df['Shift end'] = pd.to_datetime(df['Shift end'])

    # find minimum and maximum shift start and end times
    min_start_time = df['Shift start'].min().replace(hour=0, minute=0, second=0, microsecond=0)
    max_end_time = df['Shift end'].max().replace(hour=23, minute=59, second=59, microsecond=0)

    # create a list of dates to iterate over
    dates = pd.date_range(start=min_start_time, end=max_end_time, freq='D').date.tolist()

    # initialize an empty dictionary to store the employee counts
    employee_counts = {date: [0] * 96 for date in dates}

    # iterate over each employee's shift and increment the count for each 15-minute interval
    for _, row in df.iterrows():
        start_time = row['Shift start']
        end_time = row['Shift end']
        date = start_time.date()

        # calculate the number of 15-minute intervals between the start and end times
        num_intervals = int((end_time - start_time) / timedelta(minutes=15))

        # add the employee to the count for each 15-minute interval
        for i in range(num_intervals + 1):
            start_index = int(start_time.hour * 4 + start_time.minute / 15)
            employee_counts[date][start_index + i] += 1

    # create a DataFrame from the employee counts dictionary
    result = pd.DataFrame.from_dict(employee_counts, orient='index',
                                    columns=[f'{hour:02d}:{minute:02d}' for hour in range(24) for minute in range(0, 60, 15)])

    return result

The output would be (I used transpose on the result, so they fit here):
        2023-02-14  2023-02-15  2023-02-16  2023-02-17
00:00   0   0   0   0
00:15   0   0   0   0
00:30   0   0   0   0
00:45   0   0   0   0
01:00   0   0   0   0
01:15   0   0   0   0
01:30   0   0   0   0
01:45   0   0   0   0
02:00   0   0   0   0
02:15   0   0   0   0
02:30   0   0   0   0
02:45   0   0   0   0
03:00   0   0   0   0
03:15   0   0   0   0
03:30   0   0   0   0
03:45   0   0   0   0
04:00   0   0   0   0
04:15   0   0   0   0
04:30   0   0   0   0
04:45   0   0   0   0
05:00   0   0   0   0
05:15   0   0   0   0
05:30   0   0   0   0
05:45   0   0   0   0
06:00   0   0   0   0
06:15   0   0   0   0
06:30   0   0   0   0
06:45   0   0   0   0
07:00   0   0   0   0
07:15   0   0   0   0
07:30   0   0   0   0
07:45   0   0   0   0
08:00   1   0   0   0
08:15   1   0   0   0
08:30   1   0   0   0
08:45   1   0   0   0
09:00   1   0   0   0
09:15   1   0   0   0
09:30   2   0   0   0
09:45   2   0   0   0
10:00   2   0   0   1
10:15   2   0   0   1
10:30   2   0   0   1
10:45   2   0   0   1
11:00   2   0   0   1
11:15   2   0   0   1
11:30   2   0   0   1
11:45   2   0   0   1
12:00   3   0   0   1
12:15   3   0   0   1
12:30   3   0   0   1
12:45   3   0   0   1
13:00   4   0   0   1
13:15   4   0   0   1
13:30   4   0   0   1
13:45   4   0   0   1
14:00   4   0   0   2
14:15   4   0   0   2
14:30   4   0   0   2
14:45   4   0   0   2
15:00   4   0   0   2
15:15   4   0   0   2
15:30   4   0   0   2
15:45   4   0   0   2
16:00   4   1   0   2
16:15   3   1   0   2
16:30   3   1   0   2
16:45   3   1   0   2
17:00   3   1   0   2
17:15   3   1   0   2
17:30   3   1   0   2
17:45   2   1   0   2
18:00   2   2   0   2
18:15   1   2   0   1
18:30   1   2   0   1
18:45   1   2   0   1
19:00   1   2   0   1
19:15   0   2   0   0
19:30   0   2   0   0
19:45   0   2   0   0
20:00   0   2   0   0
20:15   0   1   0   0
20:30   0   1   0   0
20:45   0   1   0   0
21:00   0   1   0   0
21:15   0   1   0   0
21:30   0   1   0   0
21:45   0   1   0   0
22:00   0   1   0   0
22:15   0   0   0   0
22:30   0   0   0   0
22:45   0   0   0   0
23:00   0   0   0   0
23:15   0   0   0   0
23:30   0   0   0   0
23:45   0   0   0   0

A: IIUC, you can use a combination of melt, groupby and pivot. I've included the intermediate states of the dataframe:
df=pd.DataFrame({'Employee_ID': {0: 1, 1: 2, 2: 3}, 'Start_Time': {0: '202303150100000000000000', 1: '202303150015000000000000', 2: '202303150230000000000000'}, 'End_Time': {0: '202303150245000000000000', 1: '202303150700000000000000', 2: '202303160100000000000000'}})

# shorten your datetime values and turning it into real date time values.
df['Start_Time'] = df['Start_Time'].astype(float).divide(10000000000).astype(int)
df['End_Time'] = df['End_Time'].astype(float).divide(10000000000).astype(int)
df['Start_Time'] = pd.to_datetime(df['Start_Time'], format='%Y%m%d%H%M%S')
df['End_Time'] = pd.to_datetime(df['End_Time'], format='%Y%m%d%H%M%S')

# create a melt, basically stacking the column Start_Time and End_Time
df = pd.melt(df, id_vars=['Employee_ID'], value_vars=['Start_Time', 'End_Time']).drop(columns='variable').set_index('value')
print(df)
#                     Employee_ID
# value
# 2023-03-15 01:00:00            1
# 2023-03-15 00:15:00            2
# 2023-03-15 02:30:00            3
# 2023-03-15 02:45:00            1
# 2023-03-15 07:00:00            2
# 2023-03-16 01:00:00            3

# Group this dataframe by Employee_ID, while resampling the datetimes to 15 minute intervals.
df = df.groupby('Employee_ID').resample('15T').ffill().reset_index(drop=True, level=0).reset_index()
print(df)
#                   value  Employee_ID
# 0   2023-03-15 01:00:00            1
# 1   2023-03-15 01:15:00            1
# 2   2023-03-15 01:30:00            1
# 3   2023-03-15 01:45:00            1
# 4   2023-03-15 02:00:00            1
# ..                  ...          ...
# 122 2023-03-16 00:00:00            3
# 123 2023-03-16 00:15:00            3
# 124 2023-03-16 00:30:00            3
# 125 2023-03-16 00:45:00            3
# 126 2023-03-16 01:00:00            3

# Group the df by 'value' (which has all the dates) and extract date and time columns
df = df.groupby('value').count().rename(columns={'Employee_ID': 'Employee_Count'})
df['Date'] = df.index.date
df['Time'] = df.index.time
print(df)
#                      Employee_Count        Date      Time
# value
# 2023-03-15 00:15:00               1  2023-03-15  00:15:00
# ...
# 2023-03-16 00:45:00               1  2023-03-16  00:45:00
# 2023-03-16 01:00:00               1  2023-03-16  01:00:00

# Finally, pivot the dataframe, taking the Time column as columns.
df = df.pivot(columns='Time', index='Date', values='Employee_Count').fillna(0)
df


text:
Q: Volume of cone not returning correct value My code assembles correctly, however it is not returning the volume of a cone. I tried a few other ways to get it to give me the volume of a cone, and it doesn't give me the correct answer. Is there something I am missing?
Edit: I fixed my code to output a number, however its not giving me the right number.
This is the formula I am using for this code:
V= (22)(r)(r)(h)/21
diviser         DWORD       21
height          WORD        0
radius          BYTE        0                                           ;*** Declare an unsigned, integer variable for the value
product         WORD        0
askRadius       BYTE        "What is the radius?", 0ah, 0dh, 0              ;*** Declare the prompt and message parts
askHeight       BYTE        "What is the height? ", 0
volumeOutput    BYTE        "The volume of the cone is:  ", 0
lineBreak       BYTE        " ",0dh, 0ah, 0

.code
main PROC

mov ebx, diviser                         ;Initializes the diviser

mov edx,OFFSET askRadius                 ;Asks for Radius
call WriteString
call ReadDec
mov radius, al                           ;moves radius into al (8-bit)
mul radius                               ;Multiplies radius * radius(16-bit)

mov edx,OFFSET askHeight                 ;asks for Height
call writestring
call ReadDec
mov height, dx                           ;moves height into AX
mov WORD PTR product, ax                 ;convert 16-bit into 32-bit
mov WORD PTR product+2, dx               ;converts 16-bit into 32-bit
mul eax                                  ;multiplies by 22
mov edx, 22
mul edx
div ebx                                  ;divides by 21

mov edx, OFFSET volumeOutput
call WriteString
call WriteDec
call WaitMsg
exit

main ENDP
END main

A: Something like this should work better. Note you should choose where you want to widen the calculation to 64 bit.
askRadius       BYTE        "What is the radius?", 0ah, 0dh, 0              ;*** Declare the prompt and message parts
askHeight       BYTE        "What is the height? ", 0
volumeOutput    BYTE        "The volume of the cone is:  ", 0
lineBreak       BYTE        " ",0dh, 0ah, 0

.code
main PROC

mov edx,OFFSET askRadius                 ;Asks for Radius
call WriteString
call ReadDec
imul eax, eax                            ; radius * radius
mov ecx, eax                             ; save for later

mov edx,OFFSET askHeight                 ;asks for Height
call writestring
call ReadDec
imul eax, eax, 22
mul ecx                                  ;multiplies by radius * radius
mov ecx, 21
div ecx                                  ;divides by 21

mov edx, OFFSET volumeOutput
call WriteString
call WriteDec
call WaitMsg
exit

main ENDP
END main


text:
Q: Python: io redirect how to exclude return value from output content? E.g, I can use os.system to execute a shell command, like this:
>>> import os
>>> os.system("ls")
1p.py                  Tmytest1               getpip.py              src
1p.pyc                 a.out                  helloworld             tags
0

Seems the "0" is the return value of "system" function call, and python prints it out. Then I tried to redirect the system command output to a file like this:
>>> import os
>>> import sys
>>> testlog=open('testlog.txt','w')
>>> os.dup2(testlog.fileno(),sys.stdout.fileno())
>>> print 'abc'
>>> print 'xyz'
>>> os.system("ls")

Then I cat "testlog.txt", I found the content contains last line of "0". This is not what I wanted, how to exclude the return value from being re-directed to output file?

A: Since it's a returned value, why not save it?
_ = os.system('ls')

After this, the value of _ will be 0, and that 0 won't be included in the output.


text:
Q: Shadowed underlined text with perspective I have the following html structure where I style my titles with an underline and a shadow.

.title {
    font-size: 28px;
    line-height: 1;
    letter-spacing: 0px;
    text-shadow: 2px 2px #32c8ff;
    text-decoration: underline;
    text-underline-position: under;
}

MY TITLE

I tried to apply a perspective effect with the following css

.container {
    -webkit-perspective: 150px;
    perspective: 150px;
}

.content {
    -webkit-transform: rotateX(25deg);
    transform: rotateX(25deg);
}

MY TITLE

As you can see, it works fine on the text but on the underline the shadow is not displayed and the distance from the text (text-underline-position: under;) is ignored.
Is there a way to display the shadow and keep the correct distance of the underline from the text when using the perspective?

A: You can simulate the underline with the pseudo element before:
.title {
    display: inline-block;
    font-size: 28px;
    line-height: 1;
    letter-spacing: 0px;
    position: relative;
    text-shadow: 2px 2px #32c8ff;
    text-decoration: none;
}

.title::before {
    border-bottom: 2px solid #000;
    bottom: 0;
    content: "";
    position: absolute;
    left: 0;
    right: 0;
    box-shadow: 2px 2px #32c8ff;
}

See the example here

A: Check this out:
https://jsfiddle.net/zzhn5gh7/

.container {
  width: 200px;
  height: 200px;
  border: 1px solid #CCC;
  margin: 0 auto 60px;
  position: relative;
  -webkit-perspective: 600px;
  -moz-perspective: 600px;
  -o-perspective: 600px;
  perspective: 600px;
}

.title {
  width: 100%;
  height: 100%;
  position: absolute;
  background: green;
  font-size: 35px;
  line-height: 1;
  letter-spacing: 0px;
  text-shadow: 2px 2px #32c8ff;
  text-decoration: underline;
  text-underline-position: under;
}

#rotate-x .title {
  -webkit-transform: rotateX( 45deg);
  -moz-transform: rotateX( 45deg);
  -o-transform: rotateX( 45deg);
  transform: rotateX( 45deg);
}

MY TITLE

A: Another possibility: Fiddle

.title, .subtitle {
    font-size: 28px;
    line-height: 1;
    letter-spacing: 0px;
    text-shadow: 2px 2px #32c8ff;
    text-align: center;
}
.title {
    border-bottom: 2px solid;
    box-shadow: 2px 2px #32c8ff;
}
.container {
    display: table-cell;
    -webkit-transform: rotateX(45deg);
    transform: rotateX(25deg);
}
.content {
    -webkit-transform: rotateX(45deg);
    transform: rotateX(25deg);
}

GREENPEACE

THE SURFER

A: The right solution for me was the following:

.title {
    display: inline-block;
    position: relative;
    font-size: 28px;
    line-height: 2.5;
    letter-spacing: 0px;
    text-shadow: 2px 2px #32c8ff;
    text-decoration: none;
}
.title::before {
    border-bottom: 4px solid #ffffff;
    bottom: 0;
    content: "";
    position: absolute;
    left: 0;
    right: 0;
    box-shadow: 2px 2px #32c8ff;
    margin: 11px 0px;
}
.subtitle {
    font-size: 28px;
    line-height: 0.7;
    letter-spacing: 0px;
    text-shadow: 2px 2px #32c8ff;
}


text:
Q: JQuery source code DomEval understanding I'm studying the actual JQuery file for 3.1.1 as a tool to learn Javascript.
In the DOMEval function, there is a line
doc.head.appendChild( script ).parentNode.removeChild( script );

Am I missing something or is this adding then removing a script element in the head tag?
If so what is the purpose of this line?


text:
Q: How to create a trigger that moves data to another table when a table is truncated I created the trigger but it doesn't move data to the other table
It creates the trigger successfully. It also truncates the table but the data is not moved.

CREATE OR REPLACE TRIGGER test_trigger
BEFORE TRUNCATE ON SCHEMA
BEGIN
IF (ora_sysevent='TRUNCATE' and ora_dict_obj_name='testtab') THEN
INSERT INTO testtab2
SELECT name, id FROM testtab;
END IF;
END test_trigger;

A: From the other references your source table does not have a quoted identifier, so it will be stored in uppercase in the data dictionary etc. Read more in the docs.That means you need the comparison to be uppercase too:
and ora_dict_obj_name='TESTTAB'

Not related, but it is good practice for your insert statement to list the target column names:
INSERT INTO testtab2 (name, id)
SELECT name, id FROM testtab;


text:
Q: SQL Server - evaluate a function in a dynamic query I have a piece of dynamic SQL inside part of which retrieves a function dependent on other results from the query, but also uses these results to evaluate this function. I know eval() does not exist in SQL so what do I use?
A very simplified version
select reading, functiontype, @result = eval(f.functionformula)
from readingstables r
join functiontable f on (r.functiontype = f.functiontype)

So basically (note these are only example formulae) I want to use the functionformula which is related to a set of readings via the formulatype
if f.functiontype == 'A' then  f.functionformula = reading * reading
if f.functiontype == 'B' then  f.functionformula = reading * costant / anothervalue
    //etc etc
The real version is a huge piece of dynamic SQL in a stored procedure that drives a cursor. I would prefer to do it in one query but suspect I might have to compromise and have a second dynamic query driven from the first.

A: Why not simply use the POWER function:
Case functionType
    When 'A' Then Power( reading, 2 )
    When 'B' Then Power( reading, 3 )
    ...
    End

You could even get super fancy like so:
Power( reading, Ascii( functionType ) - Ascii('A') + 2 )

Edit
Given your change to your OP, beyond dynamic SQL, there is no way to dynamically execute a function call. You could create a UDF which takes the function type parameter and executes the correct expression however the UDF itself would need to be a large Case expression.
Create Function FunctionTypeExpression( @FunctionType char(1) )
Returns float
As

Return Case @FunctionType
    When 'A' Then ..expression 1
    When 'B' Then ..expression 2
    ...

One note in this, you will need to make the return value of the function compatible with any possible return type from the expressions. Hopefully, they are all numeric. If they are not all numeric (or all text), then a more detailed explanation for why this is not the case would be needed.


text:
Q: Latch-up, JESD17, and JESD78 I am somewhat familiar with latchup (parasitic transistors in the body of a CMOS device that are activated by over- or under-voltage conditions).  However, I have seen some devices that advertise "Latch-Up Performance Exceeds 250 mA Per JESD 17", while others say "Latch-Up Performance Exceeds 100 mA Per JESD 78, Class II"
What exactly does this mean?  Specifically, what is the mA value in reference to?
Which one of these is better?  I think the JESD 78 standard is newer, so is it also "better" despite having a lower mA rating?

A: JESDxxx are standards.
 Date does not necessarily indicate goodness.
Currents are what can be injected into pin by voltage outside rails without causing latchup.
 100 mA is good,
 250 mA is very good.

A: Both are standsrd tests defined by JEDEC, a member of the Electronic Industries Alliance (EIA).
JESD17 (the document is not available anymore) is an old standard, dated 1988, which has been replaced by the newer JESD78 (you need to register to download the document). So you can consider the performance test with JESD17 "less accurate" for newer devices than the one defined by the newer standard.
From the document:

As these technologies have evolved, it has been necessary to adjust this document to the realities of characterization with limits not imagined when the first latch-up document was generated some 25 years ago.

But if the component you have is older than the latest standard, you can assume that the testing has been made with the newest (at the time) version of the standard, and consider it reliable.
Moreover, the newer one may have a lower rating because, being newer technology, operates at lower current/voltage ratings, or it's just less rough.


text:
Q: Member access rules for friend of derived class, where the naming class is the base class All standard references below refer, unless noted otherwise, to N4861 (March 2020 post-Prague working draft/C++20 DIS).

Background
According to [class.access.base]/5:

If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class [...].

Meaning the following example is well-formed:
class N {};

class P : private N {
    friend void f();
};

void f()  {
    P p{};
    N* n = &p; // R: OK as per [class.access.base]/5
}

as N is an accessible base class at R above(+).
[class.access.base]/5 also mentions that [emphasis mine]:

The access to a member is affected by the class in which the member is
named. This naming class is the class in which the member name was
looked up and found. [ Note: [...] If both a class member access
operator and a qualified-id are used to name the member (as in
p->T::m), the class naming the member is the class denoted by the
nested-name-specifier of the qualified-id (that is, T). — end note
]

and [emphasis mine]:

A member m is accessible at the point R when named in class N if

*

*[...]

*/5.3 m as a member of N is protected, and R occurs in a member or friend of class N, or in a member of a class P derived
from N, where m as a member of P is public, private, or
protected, or

*/5.4 there exists a base class B of N that is accessible at R, and m is accessible at R when named in class B.

With that in mind, consider the following example:
class N {
  protected:
    int m;
};

class P : private N {
    friend void f();
};

void f()  {
    P p{};
    (&p)->N::m = 42;  // R: #1
}

where as per above the naming class at #1 is N. The example is accepted by both Clang and GCC, for various compiler versions and standards, meaning it's arguably well-formed.
It would seems as if &p (which is of type P*) is implicitly converted to N* (fulfilling [class.access.base]/6), but I'm wondering by what rules the member m of N (N being the naming class) is accessible at an R which is a friend to a derived class P of N.
Question

*

*What rule(s) governs that #1 is well-formed?

As per above, the naming class at #1 is N, but [class.access.base]/5.3 should not apply as R is in a friend of class P derived from N (/5.3 only mentions in a member of class P). [class.access.base]/5.4 should not apply as the naming class is N which is the top-level class in the class hierarchy.
We may note that [class.protected]/1 mentions the very example above as well-formed as part of the non-normative example block of the paragraph. However, [class.protected]/1 in its entirety is described as

An additional access check [...]

arguably meaning [class.access.base] still needs to apply; it particularly seems as if [class.access.base]/5.3 is arguably missing mentioning the case "or a friend of class P" which [class.protected]/1 shows in an (non-normative) example.

(+) An accessible base class
In the following example:
class B { };

class N : B {
    friend void f();
};

void f()  { /* R */ }

according to [class.access.base]/4, specifically [class.access.base]/4.2 [emphasis mine]:

A base class B of N is accessible at R, if

*

*/4.1 [...]

*/4.2 R occurs in a member or friend of class N, and an invented public member of B would be a private or protected member
of P, [...]

B is accessible at R, namely in the friend f of N.

A: Actually, the section [class.protected#1] is an additional clause for [class.access.base#5] when the nominated member is a protected member of the naming class to which R occurs at a member or friend of a derived class.
According to class.access.base#1,
the non-static protected member of N is accessible as a private member of the derived class P. We are permitted to access the member m in a friend of P as per class.access.base#5.2, if the naming class is P

m as a member of N is private, and R occurs in a member or friend of class N, or

Back to [class.protected#1], we should take a look at the following rule:

An additional access check beyond those described earlier in Clause [class.access] is applied when a non-static data member or non-static member function is a protected member of its naming class ([class.access.base])115 As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C.

In other words, the rule says that only if these conditions are satisfied will the additional rule be applied. That is:

*

*The member should first be a non-static member(data or function)

*The member should be a protected member of the naming class.

In order to make the additional rule apply, the following conditions should also be satisfied

*As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C.

*If the access is to form a pointer to member ([expr.unary.op]), the nested-name-specifier shall denote C or a class derived from C.

*All other accesses involve a (possibly implicit) object expression. In this case, the class of the object expression shall be C or a class derived from C.

Condition 3 might have some confusion, however, it does not say C must be the naming class or not. It just says that the member can be accessible in a member or friend of C.
After sorting out these conditions, we could take a look at the example
void f()  {
    P p{};
    (&p)->N::m = 42;  // R: #1
}

The naming class is N and the non-static member m is a protected of N, hence conditions 1 and 2 are true.
m as a private member is accessible in a friend of P, hence condition 3 is true.
(&p)->N::m is a class member access expression where its object expression is of type P, hence condition 5 is true. So, such an expression is well-formed when it occurs in f.
If change the non-static member m to be a static member, then condition 1 is false, which means the additional rule will not apply to the expression.
In simple, [class.protected#1] add an extra option(that is a friend) for the latter bullet of [class.access.base#5.2], if these conditions are satisfied. Moreover, it also restricts these members that might be accessible as per the latter bullet of [class.access.base#5.2] to turn non-accessible members when they satisfy these conditions.