text:
Q: How can I get d3-selection-multi in scope for an external js file in nuxt? In my script tag on my vue page I am using:
import * as d3 from "d3";
import "d3-selection-multi";
import CreateGrid from "@/assets/javascript/transformations/Grid";

In my Grid.js file I make a call using attrs, but when my program runs I get the error: grid.append(...).attrs is not a function
I have also tried adding this to nuxt.config.js:
head: {
  script: [
    {
      src: "/js/d3-selection-multi.v1.min.js",
    },
  ]
}

And I have the js file in static/js, but I still get the same error.
How can I get this to work?


text:
Q: jenkins pipeline no permission to run a tool from system32 folder I'm running jenkins pipeline on a slave computer (slave run from agent command line - user with full admin privileges).
when trying to run a tool from system32 folder, it failes: The system cannot find the path specified.
if I copy the tool to c:\myfolder, it succeeds.
I've also tried to run msbuild - fails on post build regsvr32. but, when running the same command via computer's command line (not jenkins), it succeeds.
It looks like I have a problem with permissions but I do not know what is wrong. jenkins is running via command line with a user that have administrator permissions.
any ideas?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Outputting image with underlined text using php GD library What is the best way to display underlined text and output the result as image with GD or any other library?

A: You can try using the Unicode underline combining character U+0332.
<?php
// Set the content-type
header('Content-type: image/png');

// Create the image
$im = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The text to draw
$text = "̲U̲d̲e̲r̲l̲i̲n̲e";
// Replace path by your own font path
$font = 'arial.ttf';

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>

A: There are lots of FREE PHP CAPTCHA out there that come with a lot of customization, download one and see what exactly happens behind the scene. Also have a look at this link
HTH

A: I am using this...
    $font = imageloadfont($font_file);
$font_width = ImageFontWidth($font);
$font_height = ImageFontHeight($font);
    $str_width = strlen($text)*$font_width;
    ImageLine($image, $left, $top+$font_height, $left+$str_width,  $top+$font_height, $color);


text:
Q: IBM Db2 SQL Alchemy adapter -- issue with client driver I run into this error trying to use IBM Db2 SA adapter, and really am at a loss as to what I should do. Perhaps there's some mismatch between the Db2 client driver and the Python package. Would appreciate any guidance.
Traceback (most recent call last):
  File "/Users/d/projects/backend/database_provider/sql_alchemy_connection.py", line 45, in connect
    engine = create_engine(uri, case_sensitive=False)
  File "/Users/d/projects/backend/venv/lib/python3.6/site-packages/sqlalchemy/engine/__init__.py", line 456, in create_engine
    return strategy.create(*args, **kwargs)
  File "/Users/d/projects/backend/venv/lib/python3.6/site-packages/sqlalchemy/engine/strategies.py", line 87, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "/Users/d/projects/backend/venv/lib/python3.6/site-packages/ibm_db_sa/ibm_db.py", line 104, in dbapi
    import ibm_db_dbi as module
  File "/Users/d/projects/backend/venv/lib/python3.6/site-packages/ibm_db_dbi.py", line 35, in <module>
    import ibm_db
ImportError: dlopen(/Users/d/projects/backend/venv/lib/python3.6/site-packages/ibm_db.cpython-36m-darwin.so, 2): Symbol not found: ___cxa_throw_bad_array_new_length
  Referenced from: /Applications/dsdriver/lib/libdb2.dylib
  Expected in: /usr/lib/libstdc++.6.dylib
 in /Applications/dsdriver/lib/libdb2.dylib

I'm using Mac OS Big Sur 11.3.1, Python 3.6.8, and the following libraries:
ibm-db==3.0.1
ibm-db-sa==0.3.5
SQLAlchemy==1.3.8


text:
Q: How can I use if/else in list comprehensions? I'm trying to create a list with even numbers showing as they are and odd numbers showing as "odd".
Here is the code I am trying.
lst = [if x % 2 == 0 else 'odd' for x in range(11)]

I expected to get something like this
[0, "odd", 2, "odd", 4, "odd", 6, "odd", 8, "odd", 10]

But I keep getting SyntaxError exception:
>>> lst = [if x % 2 == 0 else 'odd' for x in range(11)]
  File "<stdin>", line 1
    lst = [if x % 2 == 0 else 'odd' for x in range(11)]
            ^
SyntaxError: invalid syntax

What am I doing wrong?

A: You are missing the x before if:
lst = [x if x % 2 == 0 else 'odd' for x in range(11)]

The Python conditional expression syntax has to have both the 'true' and the 'false' expressions present, so true_expr if condition else false_expr, where one of true_expr or false_expr will be evaluated based on the truth value of the condition expression.
Demo:
>>> [x if x % 2 == 0 else 'odd' for x in range(11)]
[0, 'odd', 2, 'odd', 4, 'odd', 6, 'odd', 8, 'odd', 10]

Note that using a conditional expression doesn't filter, it always produces output. That's great for the per-iteration expression side of the list comprehenion syntax, but if you wanted to filter the input list and remove odd values altogether, then use a if condition test after the for ... in ... loop:
>>> [x for x in range(11) if x % 2 == 0]  # filtering, only even numbers
[0, 2, 4, 6, 8, 10]

A: Is this what you wanted?
[x if x % 2 == 0 else 'odd' for x in range(11)]
[0, 'odd', 2, 'odd', 4, 'odd', 6, 'odd', 8, 'odd', 10]

If that is the case you where simply missing something to return in the list comprehension, in this case you want to return x if the condition is satisfied.

A: lst = [x if x % 2 == 0 else 'odd' for x in range(11)]

for more details regarding list comprehension and ternary operator, here the links:
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
https://docs.python.org/3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator

A: You're missing the value that should be shown if the if statement is true
[if x % 2 == 0 else 'odd' for x in range(11)]

should be
[x if x % 2 == 0 else 'odd' for x in range(11)]


text:
Q: Android Service restarting multiple times When I launch the app on my phone the service's onCreate is called 3-4 times in less than a second.
on other hand the oncreate is set to start a thread derived class that prints the network ip of the device on the logcat.
weirdly each call to oncreate gives randomly either the actual ip (192.168.1.xxx) or the loopback (127.0.0.1)
@Override
public void onCreate() {
    super.onCreate();

    TheService=this;

    chargingState = GetChargingState();

    if(mainActivity!=null)
        mainActivity.UpdateDisplay(chargingState);

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

    registerReceiver(new ChargingStateListener(),ifilter);

    new NetworkHandler().findServer();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    return START_STICKY;
}

Function to get the IP in the threaded class
    public String GetOwnIPAddress()
    {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;

    }

A: You're misarchitecting your service.
OnCreate should never start a Thread.  Anything like that should be done in onStartCommand or later.  Creation of your service doesn't mean its running, that's what onStartCommand means.  Your service may be created or killed at the will of the system, onCreate should do a bear minimum.
On a side note-  never use your service as a singleton like you are with TheService=this.  It can get you into all sorts of trouble such as querying a stopped service.  If you need to call functions on a service, bind to it and return a Binder in onBind that accesses your API.  What you're doing will cause memory leaks and crashes.


text:
Q: Get all process of current active session I have a small problem while developing an application. I want to access all process of the current session only. Currently I am using Process class but it will return all process of all session.
Please help me to get process of the current active session only not all.
Help needed to solve the problem.

A: This will give you a list of the process running that are running with the same sessionID as
the current process.  I think that is what you want.
Process[] runningProcesses = Process.GetProcesses();
var currentSessionID = Process.GetCurrentProcess().SessionId;

Process[] sameAsThisSession =
    runningProcesses.Where(p => p.SessionId == currentSessionID).ToArray();

foreach (var p in sameAsthisSession)
{
   Trace.WriteLine(p.ProcessName);
}


text:
Q: Photon PUN: Is it possible to receive event when custom room properties have been changed? When using Photon Unity Networking (PUN), can I receive an event on all clients when some custom room property has been changed by one of the clients (for example by calling PhotonNetwork.room.SetCustomProperties() )?
Any ideas?
Thanks!

A: Not Photon event but OnPhotonCustomRoomPropertiesChanged Unity message fired each time custom room properties updated.
You can find more such messages and details on its usage in \Assets\Photon Unity Networking\Plugins\PhotonNetwork\Enums.cs


text:
Q: How do i save my tool arrangement at the top of arcmap when i close it? When I close an arcmap project and then reopen it, even though I save the mxd, the toolbar arrangement is not the way I left it. Is there a setting or some way to save my toolbar locations?

A: This is a quirk of Esri, it used to be the other way around. By default it will save all customization in only the current document, to change this open the menu customize::customize mode..

Turn off the checks indicated by the arrows to make ArcMap save to your Normal.mxt.
Please note that any open instances of ArcMap will write to the normal on exit so ensure that this is the only ArcMap open (catalog and scene don't count in this case) then exit ArcMap to make the settings permanent.


text:
Q: telnet connects, but mysql times out I have access to two servers:

*

*A runs Ubuntu Server and I connect to it via SSH

*B runs Windows Server 10

A should be able to connect to B:1433 to the MySQL Server.
Both A and B are on the same network.
I have tried to do:
mycli --verbose -u USER -h IP_OF_SERVER_B -P 1433 -p '...'

This times out.
However, nmap shows the 1433 port as open and telnet can connect to it.
$ sudo nmap IP_OF_SERVER_B
[sudo] password for ...:

Starting Nmap 7.60 ( https://nmap.org ) at 2020-07-23 04:45 UTC
Nmap scan report for IP_OF_SERVER_B
Host is up (0.0014s latency).
Not shown: 999 filtered ports
PORT     STATE SERVICE
1433/tcp open  ms-sql-s

And:
$ telnet IP_OF_SERVER_B 1433
Trying IP_OF_SERVER_B...
Connected to 10.10.1.7.
Escape character is '^]'.

How can I connect to the MySQL Server? I already enabled remote access on the MySQL Server side.

A: Your server is running MS SQL, and you are trying to connect to it using MySQL client.
MySQL and MS SQL are different products, and you cannot use tools designed for MySQL to access MS SQL server.
You need to use MS SQL client to access your MS SQL server.


text:
Q: How do you use StreamWriter to write to a file ok so heres the issue, i need to write data to a html file to save it, this format allows me to add anchors and links in which will be needed in many of the files
the names can not be predetermined (they will be files for roleplay characters, and places, 1 file per place or character)
heres the code i have so far
private async Task savetest(string name)
    {

        //ok so we get the local storage
        StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

        //create the character folder
        var dataFolder = await local.CreateFolderAsync("Character",
            CreationCollisionOption.OpenIfExists);

        //create the character html
        var file = await dataFolder.CreateFileAsync(name+".html",
        CreationCollisionOption.ReplaceExisting);

        //heres where it will get interesting
        using (StreamWriter writer = new StreamWriter(local+"/"+dataFolder+"/"+file))
        {
            writer.WriteLine("<title>Character File for " + z.charNameFirst + " " + z.charNameSecond + "</title>");
            writer.WriteLine("<title>Character File for " + z.charNameFirst + " " + z.charNameSecond + "</title>");
            writer.WriteLine("Name: " + z.charNameFirst + " " + z.charNameSecond + "
");
            writer.WriteLine("Gender:" + z.charGender+"
");
            writer.WriteLine("Race:" + z.charRace + "
");
            writer.WriteLine("Class:" + z.charClass + "
");
            writer.WriteLine("Gender:" + z.charGender + "
");
            writer.WriteLine("SomeTest
");
            writer.WriteLine("AnotherTest
");
            for (int i = 20; i > 0; i--)
            {
                writer.WriteLine("some test text some test text some test text some test text some test text some test text ");
            }

            writer.WriteLine("SomeTest
");

            for (int i = 20; i > 0; i--)
            {
                writer.WriteLine("some test text some test text some test text some test text some test text some test text ");
            }
            writer.WriteLine("AnotherTest
");

            for (int i = 20; i > 0; i--)
            {
              writer.WriteLine("some test text some test text some test text some test text some test text some test text ");
            }

            writer.WriteLine("");
        }

    }

However, there is an issue with the following line:
using (StreamWriter writer = new StreamWriter(local+"/"+dataFolder+"/"+file))

The error message says:

The best overloaded method match for 'System.IO.StreamWriter.StreamWriter(System.IO.Stream, System.Text.Encoding)' has some invalid arguments

I don't understand why all the examples I have seen use
new StreamWriter(FILENAME)

or
new StreamWriter(FILENAME,true)

for appending data to existing files.
These will be fresh on each run. FILENAME in this case should be
<Windows Phone App's Local Storage>/Character/<NAMEOFCHARACTER>.html
I have so many tabs open right now that all say this is the way to do it, but it's just not working and I have no idea why.
NOTE: All of this takes place in the MainPage.xaml.cs in the Windows Phone project.

A: Replace
new StreamWriter(local+"/"+dataFolder+"/"+file)
with
new StreamWriter(await file.OpenStreamForWriteAsync())


text:
Q: Drools vs JBPM ? differences, pros and cons I'm looking for a good rule engine.
I've seen it exists two good projects : JBPM and Drools.
I don't really understand differences between the two and I don't know what is the ideal tool to use.
Please could you provide me more information and your experience with one or other and what do you think is the best to use to manage business rules.

A: Drools is a Rete rules engine that does forward and back induction.  You can use it in a small setting for local decisions that only require a handful of rules OR something as large as an underwriting decision engine in insurance.
jBPM is an enterprise singleton that helps you to wire together interactions between humans and services into a state machine that fulfills a well-defined, complex business process.  Think of the Mediator pattern in GoF.
I can see where jBPM might use a Rete rules engine to help with complex decisions in a business flow.  There's nothing to stop me from embedding Drools in jBPM.
I would say they are complimentary, not an either/or choice.

A: jBPM is not a rule engine, it's a workflow engine.
Drools is a rule engine. So Drools is what you're looking for.
Drools and jBPM are companion projects: they integrate really nicely if you need workflows with rules.

A: jBPM is a workflow engine whereas Drools is a rule engine.
Drools Flow will be merged in the project we call jBPM 5.

A: It is not correct to say that Drools should only be used for a handful of rules. It is able to scale really well, at least at the time of this comment (version 7.5/6)
The whole point of drools and any other rules engine is the implementation of algorithms that optimize the execution of rules. Manageability of rules is proportional (if such a thing exists) to the design of the rules.
As the others have said, JBPM is not a rules engine but a workflow system that interops with drools naturally.


text:
Q: Ubuntu 17.10 installation from a thumb drive I have tried installing Ubuntu 17.10 several times now, but the process keeps failing.
The installation seems to be going smoothly; however, once the installation is complete, the system asks to be restarted. For some reason, it is this -- the restarting -- part where errors appear.
The error I get is:

squashfs error unable to read page

It is the first time I am installing Linux and I have no clue what to do, so any suggestions are welcome.

A: I am not sure what the problem is but with the DVD you have to leave it in the computer after the reboot, until it tells you to remove it.
This maybe the same when installing via a flash drive.


text:
Q: Jquery Click Event in if Else Statement With Same Class but Different IDs In my code I have two buttons with the same class and different ids. As the two buttons need to do similar things (specifically information from an ajax request) I first called the two buttons by their class and am trying set up an if else statement that will add the final pieces of the functionality for the buttons based on their IDs. However, right now the second button's else statement doesn't appear to be running and instead when I press the second button I see the changes that are supposed to happen to the first button occur. Any suggestions on how to get the li to appear correctly for the else statement?
$(".consumeFood").on("click",function(){
  $.ajax({
    url:url,
},
error:function(err){
},
complete:function(s){
  $.ajax({
    },
    success: function(r){
    if ($(".consumeFood".id=="eat")){
$('#eaten').append("
"+inputInfo+"
");
    }
    else if($("#consumeFood".id=="possibleEat")){
      $('#want').append("
"+input+"
");

    }

Html
    <form id='first'class="" method="post">
        <input type="text" placeholder="what have you eaten" name="item" id="inputID" value="" class="toEat">
        <button id="eat" class=consumeFood>Add food</button>
    </form>

    <form id="second" class="" method="post">
        <input type="text" placeholder="any foods you would like to eat" name="item2"id="wantToEat" class="toEat">

        <button id="possibeEat"class="consumeFood">include</button>
    </form>

A: I am still trying to actually understand what you are doing and maybe I still not have understood but think this should solve your problem
 $(".consumeFood").on("click",function(){
var buttonId=$(this).attr('id');
      $.ajax({
        url:url,
    },
    error:function(err){
    },
    complete:function(s){
      $.ajax({
        },
        success: function(r){
        if (buttonId=="eat"){
    $('#eaten').append("
"+inputInfo+"
");
        }
        else if(buttonId=="possibeEat"){
          $('#want').append("
"+input+"
");

        }

do consider the variables inputInfo and input i hope they are coming from somewhere above in the script and they have a valid value.


text:
Q: IE8 CSS rotation I'm looking for CSS solution for rotating elements in IE8. Some of solutions I've found say that it should work in IE8, but it does not for me. What I do wrong?
Here is what I tried:
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        .rotate {
            font-weight: bold;color: #000;background: #aa0;display: block;margin: 0 auto;width: 300px;height: 300px;top: 10%;text-align: center;line-height: 300px;
            -webkit-transform: rotate(-90deg);
            -moz-transform: rotate(-90deg);
            -ms-transform: rotate(-90deg);
            -o-transform: rotate(-90deg);
            filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
        }
    </style>
</head>
<body>
<div class="rotate">
    TESTING ROTATION
</div>
</body>
</html>

I would appreciate if you test your solution before answering, and it would be great ir you could just edit my given example and repost all code.
[EDIT]
If anyone is still curious the problem is not the code, but the testing environment.
You should use real IE8, but not IE8 emulator in IE10/IE11 (not sure about IE9)

A: You are missing IE vendor prefix -ms-
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);

So, Use this
-ms-filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); /* for IE8 */

Also look at this question: CSS rotate property in IE that might help you

A: Well,  I dont think the filters for rotation work in a elegant way in IE8. I also tried that, but it didnt work for me properly. I tried using jquery rotate plugin. You can try that out - http://code.google.com/p/jqueryrotate/
I have a issue even with that going on (jQueryRotate - Issue in IE8), but it might help you, just in case.


text:
Q: Service Value Isn't Persistent Between Parent Component and Children Component I am trying to set a value in a service from one component and read it another.
The hierarchy of my components is as: parent => child => grandchild
If I set the service value in the first child component the parent gets the correct value from the service whereas if I set the value in the child more inner child the parent component doesn't get the correct value.
Below is code:
service.ts
 @Injectable()
    export class ConfirmationDialogService {
        componentHasDirtyForm: boolean;// value to set
        constructor(private confirmationDialogReferenceService: ConfirmationDialogReferenceService,
                    private dialog: MatDialog) { }

parentComponent.ts
constructor(private confirmService: ConfirmationDialogService) {
}

ngOnInit() {
}

isDirty(): boolean {
    console.log(this.confirmService.componentHasDirtyForm)
    return this.confirmService.componentHasDirtyForm;
}

ChildComponent.ts
constructor(private confirmService: ConfirmationDialogService) { }

ngAfterViewChecked(){
    this.confirmService.componentHasDirtyForm = this.generalInfoForm.dirty;
}

GrandchildComponent (rendered inside child component)
constructor(private confirmationService: ConfirmationDialogService) { }
    ngAfterViewChecked(){
        this.checkForDirtyForm();
    }

    checkForDirtyForm(){
        for(var i = 0; i < this.ContactFormArr.length; i++){
            if(this.ContactFormArr.at(i).dirty){
                this.confirmationService.componentHasDirtyForm = true;
                break;
            }
        }
    }

Basically, in grandchild component I am trying to set componentHasDirtyForm prop of ConfirmationDialogService. It is read correctly in parent if I set it from child but not grandchild.
I have included the service as a provider in app.module.ts

A: if your service is declared like
@Injectable(
{
  provide:root
})

(is Wand Maker comment) the service is common to all the application
Else, you declare de service as providers:[] in the main module (and the service is common to all the aplication) or declare as providers:[] in a module witch has all the components.
If you declare the service as provider of each component or inject using Injector, the service is different fo each component

A: You should wrap componentHasDirtyForm inside your service as an observable and then link that to all your components (parent, child, grandchild). That way all three (or more) all share the same value all the time.
// service
private readonly _componentHasDirtyForm = new BehaviorSubject<any>({});
public readonly $componentHasDirtyForm = this._data.asObservable();

// component
public componentHasDirtyForm: Observable<any>;

ngAfterViewChecked() {
   this.componentHasDirtyForm = confirmationService.$componentHasDirtyForm;
}

// template
<div>{{ componentHasDirtyForm | async }}</div>

A: I managed to find the issue.
The Grandchildren/Children components were setting the service's value correctly. The issue was the Parent/Child component's ngAfterViewChecked() hook was running after the hooks in the Grandchildren/Children.
This was causing the service's value to basically always reflect the Parent components status (The component higher up in the chain). I got around the issue by setting the dirty check in the parent component to conditionally modify the service depending on its current value.
For example
isDirty(): boolean {
    if(!this.confirmService.componentHasDirtyForm)
        this.confirmService.componentHasDirtyForm = formStatus;
}


text:
Q: What is the difference between a liveness and a progress property? I know this is a very academic question, but I was hoping someone here could help me get an answer.
I'm taking a concurrency class in which we use LTS'es and FLTL's. In one of our assignments a question is given: "Give an example of a liveness property, expressed as an FLTL formula, that cannot be expressed as a progress property.". Just to clarify, I don't want the answer to this question.
My problem is that I always thought of the 2 as 1 :) So in order to answer the question, I need to know the difference between progress and liveness properties.
Any help would be greatly appreciated :)

A: An liveness property, is when you defining that, at some point in the future the program will execute a given part of the program. In FSP that you can define most liveness properties as a progress property, but in your assignment you have to come up with an example where you expresses a liveness property as an FLTL, but you cannot do it as a progress property.
You have to lookup the definition the FLTL formula and the progress property in FSP to see how they are different, and then come up with an example where caused some limitation in the FSP progress property cannot express as one.
Further more, I just read a bit about it, and it seems, en the progress property of FSP, you cannot describe a "loose" liveness propety such as, when the action "enter" happens then some other could actions could happen, but eventually an "exit" action occurs. This cannot be described as a progress property, because you only can describe specifics, such as an "enter" happens and an "exit" happens, and under the assumption of fairness they will both occur infinitely often, but in FLTL it is possible to say that, [](enter -> <>exit), this means always when an "enter" occurs eventually there will happen an "exit". this is the big difference of progress in FSP and FLTL formalism.


text:
Q: How to display reverse relation data in Django with unique title? I have 2 models and I want to display the data on my template, but currently, it's reflected with my other app. I have created the dynamic title and it's working fine on live but it's conflicting with other apps. Could you please help me here?
I want to display the data on ListingTech models, and a ListingTech models have multiple data of Listing so it should be displayed under the ListingTech model slug. A ListingTech model has multiple Listing so the title and description should be displayed of ListingTech.
It is working fine with the current code of the views.py file but it's giving an error whenever I try to access other app URL (Error is coming: The view company.views.company_list didn't return an HttpResponse object. It returned None instead.)
Please solve this issue, your help will be appreciated.
Here is my models.py file...
class ListingTech(models.Model):
    city = models.ForeignKey(City, default=None, related_name="ListTechCity", on_delete=models.CASCADE, help_text=f"Value: Select City")
    name = models.CharField(max_length=60, default=None, help_text=f'Type: String, Values: Enter Company Name')
    slug= models.SlugField(max_length=60, unique=True, help_text=f'Type: String, Values: Enter Slug')
    title = models.CharField(max_length=100, null=True, blank=True, verbose_name="Meta Title", help_text=f"Values: Enter ListingTech Title.")
    description = models.TextField(max_length=200, verbose_name="Meta Description", null=True, blank=True, help_text=f'Values: Enter ListingTech Meta Description.')
    listing_img = models.ImageField(upload_to="listing-image", default=None, help_text=f"Enter Listing Image", verbose_name="Upload Image")
    overview=RichTextField(null=True,
                        blank=True,
                        verbose_name='Listing Overview',
                        help_text=f"Values: Enter Listing Overview")

here is another model
class Listing(models.Model):
    city = models.ForeignKey(City,
                            verbose_name="Select City",
                            related_name='ListingCIty', null=True, blank=True, on_delete=models.CASCADE, help_text=f"Values: Select Company City")
    listing_technology = models.ForeignKey(ListingTech,
                                verbose_name="Select Listing For",
                                related_name='ListingTechnology', on_delete=models.CASCADE, help_text=f"Values: Select Company Technology")
    company = models.ForeignKey(Company,
                            verbose_name="Select Company",
                            related_name='ListingCompany', on_delete=models.CASCADE, help_text=f"Values: Select Company")
    company_url = models.URLField(max_length=256, null=True, blank=True, verbose_name="Company Page URL", help_text=f"Values: Enter Company Page URL")
    listing_overview = models.TextField(max_length=1500, null=True, blank=True, help_text=f'Values: Enter Listing Page Overview.')

here is my urls.py file...
re_path(r'^(?P<city_slug>[\w\-]+)/(?P<slug>[\w\-]+)', views.company_list, name="company_list"),

here is my views.py file...
def company_list(request, city_slug, slug):
comp_list = Listing.objects.filter(listing_technology__city__slug = city_slug, listing_technology__slug=slug).select_related('company','listing_technology').order_by('-boosted_price')
for item in comp_list:
    if item.listing_technology.title and item.listing_technology.description  != '':
        title= item.listing_technology.title
        description = item.listing_technology.description
        template_name = 'company/list.html'
        context = {'comp_list':comp_list, 'title':title, 'description':description}
        return render(request, template_name, context)
    else:
        this_year = str(datetime.now().year)
        this_month = datetime.strftime(datetime.now(), '%B')
        proj_prop = list(map(lambda x:"Top" + " " + x.listing_technology.name + " " + this_month + " " + this_year, comp_list))
        title = "".join(proj_prop[0])
        prop_desc = list(map(lambda x:x.listing_technology.city.city_name + " " +"Based Top" + " " + x.listing_technology.name + ". " + "Are you looking for the top" + " " + x.listing_technology.name + "" +", Here is the list of top" + " " + x.listing_technology.name, comp_list))
        description = "".join(prop_desc[0])
        template_name = 'company/list.html'
        context = {'comp_list':comp_list, 'title':title, 'description':description}
        return render(request, template_name, context)


text:
Q: Can't upload s3 bucket from android using cognito Hi guys so I try to upload a picture from my emulator on a s3 bucket using android and cognito:
package com.example.s3_aws;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferState;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    AmazonS3 s3;
    TransferUtility transferUtility;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        credentialsProvider();
        setTransferUtility();
        upload();

    }

    public void credentialsProvider(){
        // Initialize the Amazon Cognito credentials provider
        CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
                getApplicationContext(),
                "idafa", // I actually have here the correct identity pool id
                Regions.US_EAST_1// Region
        );

        setAmazonS3Client(credentialsProvider);
    }

    public void setAmazonS3Client(CognitoCachingCredentialsProvider credentialsProvider){

        s3 = new AmazonS3Client(credentialsProvider);
        s3.setRegion(Region.getRegion(Regions.US_EAST_1));
    }

    public void setTransferUtility(){
        transferUtility = new TransferUtility(s3, getApplicationContext());
    }

    public void upload(){
        @SuppressLint("SdCardPath") final TransferObserver observer = transferUtility.upload(
                "s3.android.test",
                "test.png",
                new File("/sdcard/DCIM/Camera/IMG_20200415_001815.jpg"),
                CannedAccessControlList.PublicRead
        );

        observer.setTransferListener(new TransferListener() {
            @Override
            public void onStateChanged(int id, TransferState state) {
                if (state.equals(TransferState.COMPLETED)) {
                    Log.i("state changed", state+"");
                } else if (state.equals(TransferState.FAILED)) {
                    Log.e("state changed", state+"");
                }

            }
            @Override
            public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

            }
            @Override
            public void onError(int id, Exception ex) {

            }
        });
    }

}

The problem is that it gives me some errors while I run the program:

Error occurred while accessing AndroidKeyStore to retrieve the key for
  keyAlias: com.amazonaws.android.auth.aesKeyStoreAlias
Error in retrieving the decryption key used to decrypt the data from
  the persistent store. Returning null for the requested dataKey

I'm leaving here also the inline policy i gave to the unauth role, maybe could be the problem here:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement0",
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": "arn:aws:s3:::s3.android.test/*"
        }
    ]
}

A: this also happend to me here is what worked
add
-keep class com.amazonaws.mobileconnectors.s3.transferutility.TransferNetworkConnectionType {*;}

to proguard-rules.pro file in your project that solved my problem.
and here are my s3 dependencies
//amazon s3 bucket
implementation 'com.amazonaws:aws-android-sdk-core:2.15.1'
implementation 'com.amazonaws:aws-android-sdk-cognito:2.6.23'
implementation 'com.amazonaws:aws-android-sdk-s3:2.15.1'
//implementation 'com.amazonaws:aws-java-sdk:1.11.404'
implementation 'com.amazonaws:aws-android-sdk-ddb:2.2.0'
implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.16.8') { transitive = true; }

saw it here


text:
Q: Ruby min function not selecting the shortest string I don't understand why min is selecting the longest string instead of the shortest:
x='AGG'
y='AAAACTGACCCACCCCAGG'
[x,y].min #=> "AAAACTGACCCACCCCAGG" # why is this the min one?
[x,y].max #=> "AGG"

a='AGAGACTTA'
b='AAA'
[b,a].min #=> "AAA" # good
[b,a].max #=> "AGAGACTTA"

A: Normally Ruby uses something called lexicographical ordering to get minimum and maximum string. Therefore AGG > AAAACTGACCCACCCCAGG, because G > A (first letter they differ in).
To get your expected behaviour you need to manually provided comparator block, like this:
[x,y].min { |x,y| x.size <=> y.size }

A: Because it is not comparing by string length, but by lexicographical ordering; and AA comes before AG. If you want to compare by length, you need to specify it:
p [x,y].min_by(&:length)

A: Ruby's min function sorts by whether a string is greater than another one. In this case String Y occurs earlier in the alphabet than string X, therefore it's less than string X. If you want to find which is the shortest string you could do something like.
[x,y].min_by(&:length)
=> "AGG"

To find the longest string you would do
[x,y].max_by(&:length)

A: The problem is that min/max doesn't do what you think it does. It doesn't compare string sizes, just gives you the first one in alphabetic order.
Luckily, min / max functions allow you to define how to check which object is bigger. Try something like:
arr.min {|a,b| a.length <=> b.length}
arr.max {|a,b| a.length <=> b.length}


text:
Q: MySQL Views Authorization Questions:

*

*Is there a way, using SQL, to identify how many views are in the database per user?

*How can you authorize/deny users access to delete views created by another user?

A: Here is the definition of information_schema.views:
mysql> show create table information_schema.views\G
*************************** 1. row ***************************
       Table: VIEWS
Create Table: CREATE TEMPORARY TABLE `VIEWS` (
  `TABLE_CATALOG` varchar(512) NOT NULL DEFAULT '',
  `TABLE_SCHEMA` varchar(64) NOT NULL DEFAULT '',
  `TABLE_NAME` varchar(64) NOT NULL DEFAULT '',
  `VIEW_DEFINITION` longtext NOT NULL,
  `CHECK_OPTION` varchar(8) NOT NULL DEFAULT '',
  `IS_UPDATABLE` varchar(3) NOT NULL DEFAULT '',
  `DEFINER` varchar(77) NOT NULL DEFAULT '',
  `SECURITY_TYPE` varchar(7) NOT NULL DEFAULT '',
  `CHARACTER_SET_CLIENT` varchar(32) NOT NULL DEFAULT '',
  `COLLATION_CONNECTION` varchar(32) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=utf8
1 row in set (0.01 sec)

Here is how you can count the views per database per user
SELECT COUNT(1) ViewCount,table_schema,definer
FROM information_schema.views
GROUP BY table_schema,definer;

I am not that sure about access/denial of views. In the information_schema.views table, there is field called SECURITY_TYPE (which have values DEFINER and INVOKER).
If a View has SECURITY_TYPE as INVOKER, everybody and his grandmother can SELECT from that View. My guess is that you would have to set the SECURITY_TYPE to DEFINER to restrict everyone from running a SELECT from that View. Of course any user with SUPER privilege and the definer can a SELECT on that View.
Changing the SECURITY_TYPE is a little painful.
You can mysqldump all views. Here is a post I made back on July 26, 2011 : Modify DEFINER on Many Views. @DTest had an even more concise answer using ALTER VIEW.
Edit the output file in vi or some other editor to change the SECURITY TYPE of any View you wish. Then, jus reimport the view from that text file.
Give it a Try !!!

A: *

*
SELECT
COUNT(*)
FROM
INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'db_name'
AND TABLE_TYPE = 'VIEW' ;

This will return # of views in a database.

*

*You should not give DROP permission to other users and have CREATE VIEW and DROP user permission to user which can DROP a view like this:
CREATE USER 'view'@'%' IDENTIFIED BY 'view';
GRANT CREATE VIEW, DROP ON sakila.* TO 'view'@'%' ;


text:
Q: Assign number to names I have two table. One of them contain four column, the first column are names and other three column are numbers. I want to assign the mean of the numbers to the name.
ID   number_1  number_2  number_3
A01  13        11        12
A02  18        16        17
......

The second table have a column contain the names from the first table and I want to replace the names with the mean of the numbers. For example:
v1  v2  v3  ......
8   5   A01 ......
6   3   A02 ......

replace the name so I can get:
v1  v2  v3  ......
8   5   12  ......
6   3   17  ......

I have no idea how to do this. Hope you can understand my question.

A: Assuming that both of your tables are dataframes and that they have the same order (i.e. A01, A02 etc.)
df1 <- read.table(text = "ID   number_1  number_2  number_3
                         A01  13        11        12
                         A02  18        16        17",
                 header = T)

df2 <- read.table(text = "v1  v2  v3
                          8   5   A01
                          6   3   A02",
                  header = T)

df1means <- rowMeans(df1[2:4])

df2$v3 <- df1means

df2

#    v1 v2 v3
# 1  8  5  12
# 2  6  3  17


text:
Q: Problem with configuring servletModule with Guice injecting GWT RequestFactory I want to use GUICE on the server side with the GWT 2.3 RequestFactory.
I have my class that extends the ServletModule with :
@Override
public void configureServlets() {
  // RequestFactory servlet
  bind(RequestFactoryServlet.class).in(Singleton.class);
  serve("/gwtRequest").with(RequestFactoryServlet.class);
}

and in the web.xml I have added :
<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

and I have the validation-api.XXX.jar referenced (as it is part of GWT)
When I run it (under Eclipse with the GWT plugin), it says:
jetty-6.1.x
[WARN] failed guiceFilter: com.google.inject.ProvisionException: Guice provision errors:
1) Error injecting constructor, java.lang.NoClassDefFoundError: javax/validation/ValidationException
  at com.google.web.bindery.requestfactory.server.RequestFactoryServlet.(RequestFactoryServlet.java:74)
  at com.djay.eyeandtrack.server.EatServletModule.configureServlets(EatServletModule.java:13)
  while locating com.google.web.bindery.requestfactory.server.RequestFactoryServlet
1 error
[WARN] Failed startup of context com.google.apphosting.utils.jetty.DevAppEngineWebAppContext@17b3de2{/,C:\5_DJAY\03_EYEANDTRACK\branches\djaysbox\EyeAndTrack\war}
com.google.inject.ProvisionException: Guice provision errors:
1) Error injecting constructor, java.lang.NoClassDefFoundError: javax/validation/ValidationException
  at com.google.web.bindery.requestfactory.server.RequestFactoryServlet.(RequestFactoryServlet.java:74)
  at com.djay.eyeandtrack.server.EatServletModule.configureServlets(EatServletModule.java:13)
  while locating com.google.web.bindery.requestfactory.server.RequestFactoryServlet
1 error
    at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:987)
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1009)
    at com.google.inject.servlet.ServletDefinition.init(ServletDefinition.java:108)
    at com.google.inject.servlet.ManagedServletPipeline.init(ManagedServletPipeline.java:82)
    at com.google.inject.servlet.ManagedFilterPipeline.initPipeline(ManagedFilterPipeline.java:102)
    at com.google.inject.servlet.GuiceFilter.init(GuiceFilter.java:172)
    at org.mortbay.jetty.servlet.FilterHolder.doStart(FilterHolder.java:97)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:662)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.jetty.Server.doStart(Server.java:224)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:186)
    at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:157)
    at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:169)
    at com.google.appengine.tools.development.gwt.AppEngineLauncher.start(AppEngineLauncher.java:119)
    at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:500)
    at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:1055)
    at com.google.gwt.dev.DevModeBase.run(DevModeBase.java:804)
    at com.google.gwt.dev.DevMode.main(DevMode.java:309)
Caused by: java.lang.NoClassDefFoundError: javax/validation/ValidationException
    at com.google.web.bindery.requestfactory.server.ServiceLayer.create(ServiceLayer.java:74)
    at com.google.web.bindery.requestfactory.server.RequestFactoryServlet.(RequestFactoryServlet.java:88)
    at com.google.web.bindery.requestfactory.server.RequestFactoryServlet.(RequestFactoryServlet.java:74)
    at com.google.web.bindery.requestfactory.server.RequestFactoryServlet$$FastClassByGuice$$54253391.newInstance()
    at com.google.inject.internal.cglib.reflect.$FastConstructor.newInstance(FastConstructor.java:40)
    at com.google.inject.internal.DefaultConstructionProxyFactory$1.newInstance(DefaultConstructionProxyFactory.java:60)
    at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:85)
    at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:254)
    at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1031)
    at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
    at com.google.inject.Scopes$1$1.get(Scopes.java:65)
    at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
    at com.google.inject.internal.InjectorImpl$4$1.call(InjectorImpl.java:978)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1024)
    at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:974)
    ... 26 more
Caused by: java.lang.ClassNotFoundException: javax.validation.ValidationException
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:176)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 42 more
I'm probably missing something but I don't knwo where to look...
Thanks

A: Is validation-api.jar in your war/WEB-INF/lib? (you say "referenced", which might not be enough)


text:
Q: How to not print state changes in console My console is displaying all these values and I am not printing it using console.log . How to remove these from the console in order to keep the console clean.
I believe they are coming from the response.

A: These are generated by a redux-middleware called 'redux-logger'. Just remove it from your middlewares when creating your store.


text:
Q: Whats the difference in terms of memory usage (clean up, etc) of Delphi Interface and C# interfaces I am a Delphi programmer and trying to get some stuff done with C# here.
Does interfaces in C# works in the same way as in Delphi - you don't need to worry in freeing it as it is freed when its out of scope.

A: The key difference between Delphi and .NET in this area, relating specifically to interfaces, is the non-deterministic nature of the clean-up.
In Delphi all interface usage follows the COM model.  That is, it is reference counted.  If the class implements a reference counted lifetime management model, then when the reference count drops to zero the object instance is destroyed AT THAT POINT.
NOTE: Lifetime management is a function of the class implementation.  To see this most clearly, a look at the implementation of IUnknown.Release in TInterfacedObject:
function TInterfacedObject._Release: Integer;
begin
  Result := InterlockedDecrement(FRefCount);
  if Result = 0 then
    Destroy;
end;

If the implementation of Release did not call Destroy, then the object would NOT be destroyed when the reference count drops to zero and would still have to be explicitly Free'd through some object reference to the object.  This can be used in Delphi to create objects which implement interfaces but which are not subject to automatic, reference counted lifetime management (though you cannot avoid the reference counting code injected by the compiler, i.e. calls to AddRef and Release).
In .NET first of all there is no reference counting per se.  The Garbage Collector works in a far more sophisticated fashion, the details of which are not directly relevant to this discussion.
The key difference is that when an object is no longer being used (however that is determined beyond a simple reference count) that is NOT the point at which it is destroyed in .NET.
In fact, it is theoretically possible that unused objects would accumulate in your application until a much, much later point in your process lifetime - especially in compute intensive applications with few idle cycles.  In .NET you simply cannot be sure precisely when those unused objects will eventually be free'd.
Some would argue that this is A Good Thing, though it confuses the usual practice of cleaning up resources that are locked or owned by objects when those objects are destroyed, since you typically need to release those locked/owned resources more urgently than is afforded by waiting around for the Garbage Collector.  This is where IDisposable comes in in .NET, the details of which are again not directly relevant can may be researched further at your leisure.

A: Yes, to a programmer they look the same. Use And Forget.
Internally they work different, in .NET an interface is (just another) reference that is sweeped by the Garbage collector.
In Delphi interfaces are a special kind of reference that are reference-counted (a different Meory management technique).
The main .NET/Delphi difference is that in .NET all references (interface, object and array) are garbage Collected.

A: I don't think it is freed when out of scope but when the garbage collection happens (when they are not used anymore)

A: Everything in c# is garbage collected, so you do not need to free them manually.
But there are significant differences. Delphi interfaces are reference counted, c# interfaces are garbage collected. C# supports multiple interface inheritance.

A: Memory management is handled by the CLR. Garbage collection is an intrinsic service in the CLR.
You do not need to null out variables or fields in order to have the object collected by garbage collection.
You do not need to implement or use IDisposable to clean up memory. The Dispose method does nothing to free managed objects in memory. The Dispose method is should be used to free up "unmanaged" resources including database connections, bitmaps, or any unmanaged structures you may be holding onto.
If you are talking about interfaces as in visual components (Forms, dialogs, etc), this gets a little bit more confusing.  In WinForms, I believe that when an interface (visual) is no longer visible, it will be cleaned up and garbage collected. The form will be recreated again when it is needed. In WPF, Windows and Pages are not immediately destroyed. They are cached for the lifetime of the application unless they are specifically cleaned up by the application developer. This improves performance with WPF applications but places an additional burden of having to worry about resources in your application.
Garbage collection is a completely separate topic. The actual freeing of managed objects from physical memory occurs in here and is completely up to the Garbage Collection service and you should not normally have to worry about how this works.
Cheers


text:
Q: Application of Egoroff's Theorem in $M$-measurable functions Here's the theorem that I'm trying to prove;

Here's how I have tried to solve it;
Since $||f||_\infty$ = sup{ R > $0$:|$\mu$ ({x $\in$ X:| f(x) | > R) > $0$}  ; $||f||_\infty$= sup |f(x)|
so, $f$ is a positive measurable function i.e., $f\in$ $L^+$(X, $\mu$). So, we apply Egoroff's theorem here which states;
"$f_n$ $\to$ $f$ $\mu$. a.e $\implies$ $f_n$ $\to$ $f$ almost uniformly."
Now, by the definition of Essential Uniform Convergence in $L^\infty$;
" For all $\epsilon$>0, there exist E $\in$ $M$ : $\mu$(E) = $0$ and $f_n$ $\to$ $f$ on $E^c$, for all x$\in$X."
For this, let us have a decreasing sequence $E_k$= $\sum$$1/2^k$ and $X \supseteq E_1 \supseteq E_2 \supseteq E_3 \supseteq...$ and $E = \bigcap E_k$
so by continuity from above , $\mu (E_k)$ $\to 0$ as $k \to 0$ and $\mu(E_1) < \infty$.
Now, by the definition of Essential Uniform Convergence,
$lim ||f_n - f||_\infty$ $\to 0$ on $E_k^c$
Also, By a result, " $f_n \in L^+(X, \mu)$ $\to$ $f$ and   $lim f_n=f$   a. e.Then, there exists a subsequence $f_{n_{k}}$ $\to$ $f_n$ $\mu$.a.e."
$\implies$ $lim || f_{n_{k}} - f||_\infty$ $\to$ $0$ on $E_k^c$
$\implies$ $lim || f_{n_{k}} - f||_\infty$ $=$ $0$ on $E_k^c$
$\implies$ $lim || $1_${E_k^c}$$ f_{n_{k}} - f||_\infty$ $=$ $0$ on $E_k^c$
However, my Professor says that I have correctly invoked Egoroff's theorem, but the subsequence is not chosen in conjunction with the descending sequence of sets. I need help in correcting my solution.

A: For each $k$, there is, by Egorov's theorem, a set $A_k\in\mathcal{M}$ such that $\mu(X\setminus A_k)<2^{-k}$,  such that such that  $f_n(x)\rightarrow f(x)$ uniformly for all $x\in A_k$. Thus, for some $n_k$,
$\|(f-f_n)\mathbb{1}_{A_k}\|_\infty<2^{-k}$ for all $n\geq n_k$. One can choose the $n_k$'s so that $n_k<n_{k+1}$ (why?).
Let $E=\bigcap_k\bigcup_{j\geq k}(X\setminus A_j)$. Notice
$$\mu(E)=\lim_k\mu(\bigcup_{j\geq k}X\setminus A_j\big)\leq\lim_k\sum_{j\geq k}\mu(X\setminus A_j)=\lim_k2^{-k+1}=0$$
Let $E_k=\bigcup_{j\geq k}(X\setminus A_j)$. Clearly $E_k$ is a decreasing sequence. Check that the sequence of $E_k$'s does the job.

A: Since $||f||_\infty$ = sup{ R > $0$:|$\mu$ ({x $\in$ X:| f(x) | > R) > $0$}  ; $||f||_\infty$= sup |f(x)|
so, $f$ is a positive measurable function i.e., $f\in$ $L^+$(X, $\mu$). So, we apply Egoroff's theorem here which states;
"$f_n$ $\to$ $f$ $\mu$. a.e $\implies$ $f_n$ $\to$ $f$ almost uniformly."
Now, by the definition of Essential Uniform Convergence in $L^\infty$;
" For all $\epsilon$>0, there exist E $\in$ $M$ : $\mu$(E) = $\epsilon$ and $f_n$ $\to$ $f$ on $E^c$, for all x$\in$X."
For this, By Egoroff's, let us have a decreasing sequence $\mu(E_k)$= $1/2^k$ and on $E^c$
$\implies \mu(E^c)= 1/2^k$ and $f_n \to f$ uniformly on $E^c$
In particular, there exists $n_k$ such that $n_K<n_{k+1}$
By induction, we define, $X \supseteq E_1 \supseteq E_2 \supseteq E_3 \supseteq... E_k$ with $\mu(E^c)= 1/2^k$ and $||(f_{n_k} - f)1_{E^c}||_\infty < 1/2^k$
Applying Egoroff's to $E^c$ to get some $F \subset E_k$ with $\mu(F) < 1/2^{k+1}$ such that $f_n$ $\to$ $f$ uniformly on $E^k/F$
Since $f_n$ $\to$ $f$ uniformly on $X/E^k$ ($E^k/F \bigcup X/E^k = X/F$
$\implies f_n$ $\to$ $f$ uniformly on $X/F$
Now, let $E_{k+1} = F$ and let $n_{k+1}>n_k$ such that $||(f_{n_{k+1}} - f)1_{E^{k+1}}||_\infty < 1/2^{k+1}$ as $k\to \infty$
So, we get the required result.


text:
Q: getting pid of process in windows server I was looking for a script to get PID of a java process based on CommandLine value of task manager. ALl these java processes have similar COmmandLine value but differ in a keyword within the CommandLine. The process can't be identified by the image name because they all have same java.exe. Is there a way? I've placed below code based on npocmaka's answer
@echo off
setlocal enableDelayedExpansion

set "command_line="%1""

set "command_line=!command_line:"=%%!"

echo ~~!command_line!~~

for /f "usebackq tokens=* delims=" %%# in (
    `wmic process where 'CommandLine like "%command_line%"' get /format:value`
) do (
    for /f %%$ in ("%%#") do (
        set "%%$"
    )
)

echo %ProcessId%

I'm using a keyword in CommandLine to identify the PID. Yet when I execute this script, I get the wrong PID. I'm assuming its returning the scripts PID as the script may also contain the keyword. The argument while executing the script is taken as keyword

A: WMIC PROCESS is what you need.Though you'll need some tricks to use it from batch.I've used more complex command line which contains quotes ,brackets,spaces, file separators.... You'll need to change it and set the value you want.
First you'll need to double every backslash in the command line(the script should do it I mean).Quotes also can be a problem and need to be replaced  with % or escaped with \" (WMIC uses WQL a subset of SQL commands and % is used as wildcard).Another thing is you need to process the result twice with FOR loop to rid-off unwanted special characters./Format:Value can be used for direct declaring variable/value pairs.So here it is:
@echo off
setlocal enableDelayedExpansion

:: !!!!!!!!!
set "command_line="C:\Program Files (x86)\Dropbox\Client\Dropbox.exe" /systemstartup"
:: !!!!!!!!

set "command_line=!command_line:\=\\!"
set "command_line=!command_line:"=%%!"
::or
::set "command_line=!command_line:"=\"!"

rem echo ~~!command_line!~~

for /f "usebackq tokens=* delims=" %%# in (
    `wmic process where 'CommandLine^="!command_line!"' get /format:value`
) do (
    for /f %%$ in ("%%#") do (
        set "%%$"
    )
)

echo %ProcessId%

A:  wmic process where name='explorer.exe' get commandline, pid /format:list

is one way. Also see tasklist /v.


text:
Q: Running commands in bash and updating tkinter.Text in a python GUI I'm creating a Python GUI application in Tkinter that's supposed to run a list of commands in bash. I also want to update the user on what task is running and whether or not it finished successfuly.
The way I have it set up right now is simillar to this:
import tkinter
from time import sleep

class mainApp(tkinter.Frame):

    def __init__(self, parent, *args, **kwargs):
        # Set up a simple gui
        tkinter.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        # Text box with messages for the user
        self.textBox = tkinter.Text(master = parent)
        self.textBox.pack()

        # Button to run the test
        self.commandButton = tkinter.Button(master = parent,text = "Run test", command = self.doCommand)
        self.commandButton.pack()

    def doCommand(self):
        # The command also creates the list it's supposed to run. Commands themselves run qiime2 (a program that runs in bash)
        listOfCommands = ["command1", "command2","command3"]
        for command in listOfCommands:
            self.textBox.insert(tkinter.END, "Running: {}\n".format(command))
            #subprocess.run(command.split())
            sleep(5)
            self.textBox.insert(tkinter.END, "Finished. \n")

if __name__ == "__main__":
    root = tkinter.Tk()
    mainApp(root).pack(side="top", fill = "both", expand = True)
    root.mainloop()

*

*The sequence of events that I wanted was:

*

*The textBox gets updated with "Running: command"

*The command is run in bash using subprocess (in the example I'm just using sleep as a placeholder)

*Once the command finishes, the textBox gets updated with "Finished"

*

*repeat for all commands in list

What actually happens is the GUI freezes, commands run in the background in bash and once the last one is finished then the textBox gets updated with all messages at once.
I'd really appreciate any help. I tried a bunch of different things, like making the subprocess run in a generator or a coroutine, I also tried threading (but admittedly I don't fully understand it so I may have done it wrong) and the results didn't change.
UPDATE: changing process = subprocess.run to process = subprocess.Popen, running self.textBox.update_idletasks() before and process.communicate() after process seems to have solved my issue.


text:
Q: Portable encryption algorithm I need to implement a new, or already existing, encryption algorithm that encrypt and decrypt a string using another string as key. The problem is that this algorithm have to work independently from a computer on which it is used.
So the methods signature are:
public static string Encrypt(this string source, string key);

public static string Decrypt(this string source, string key);

I tried these algorithms, but they don't work the way I want:
public static string Encrypt(this string source, string key)
{
    if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(key))
        throw new ArgumentException();

    CspParameters cspp = new CspParameters { KeyContainerName = key };

    using (var rsa = new RSACryptoServiceProvider(cspp) { PersistKeyInCsp = true })
        return BitConverter.ToString(rsa.Encrypt(UTF8Encoding.UTF8.GetBytes(source), true));
}

public static string Decrypt(this string source, string key)
{
    if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(key))
        throw new ArgumentException();

    try
    {
        CspParameters cspp = new CspParameters { KeyContainerName = key };

        using (var rsa = new RSACryptoServiceProvider(cspp) { PersistKeyInCsp = true })
        {
            string[] decryptArray = source.Split(new char[] { '-' }, StringSplitOptions.None);
            byte[] bytes = Array.ConvertAll<string, byte>(decryptArray, (s => Convert.ToByte(Byte.Parse(s, NumberStyles.HexNumber))));

            return UTF8Encoding.UTF8.GetString(rsa.Decrypt(bytes, true));
        }
    }
    catch
    { return null; }
}

How can I do?

A: The KeyContainerName is NOT the key. In your example above, by passing the key as the store name, you'll create a NEW RSA keypair on each machine with a store name of the key you passed in (rather than a storename of something like "MyRSAKeyPair" or whatever). This will mean both the public and private keys will be completely different and your routines won't seem to work.
ALSO: You're using asymmetric encryption, this has a maximum block size limit of the key length. This means you'll either need to create a chunking mechanism (slow as asymmetric encryption is expensive) OR use something symmetric like AES with the AES key being sent using asymmetric encryption (such as RSA) on a per conversation basis.
You need to export the RSA public key and then import it into the remote machine's keystore. Easier still is generating an X509 certificate (you can self sign if you're just going between a couple of machines, exporting the public part of it into a .CER file, then you can use the X509 Certificate Store API to get the RSA Provider, meaning you have a nice transportable key.
 public static RSACryptoServiceProvider GetRsaProviderFromCertificate()
 {
     X509Store store = new X509Store(StoreLocation.LocalMachine);
     store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
     X509Certificate2Collection certCollection =  (X509Certificate2Collection)store.Certificates;

     foreach(X509Certificate2 cert in certCollection)
     {
         if (cert.SubjectName.Name.IndexOf("TheCertIWantToUse") > 0)
         {
              return cert.PrivateKey as RSACryptoServiceProvider;
         }
     }

I hope that's explicit enough...
If you want to do it without certs
// Export public key (on the encrypting end)
            publicKey = rsaProvider.ToXmlString(false);
// Write public key to file
            publicKeyFile = File.CreateText(publicKeyFileName);
            publicKeyFile.Write(publicKey);

Then on the other machine
            // Select target CSP
            cspParams = new CspParameters();
            cspParams.ProviderType = 1; // PROV_RSA_FULL
            rsaProvider = new RSACryptoServiceProvider(cspParams);

            // Read public key from file
            publicKeyFile = File.OpenText(publicKeyFileName);
            publicKeyText = publicKeyFile.ReadToEnd();

            // Import public key
            rsaProvider.FromXmlString(publicKeyText);


text:
Q: Find command not deleting anything when -delete is used I'm using this script:
find $convfold -name \*.mkv -o -name \*.avi -o -name \*.mov -o -name \*.wmv -o -name \*.m4p -o -name \*.m4v -o -name \*.mpg -o -name \*.mp2 -o -name \*.mpeg -o -name \*.mpe -o -name \*.mpv -o -name \*.m2v -o -name *.m4v -delete

where $convfold is a variable for the folder in which I'm deleting the video.
If I remove the -delete from the code it displays the files it should be deleting but when I have it in the code I get no return errors nor exceptions.
Example:
flynn@Tron:~/FilebotHandbrake/testconverting$ find -name \*.mkv -o -name \*.mp4 -o -name \*.avi
./TV Shows/Mr. Robot/Season 02/Mr. Robot - S02E02 - eps2.0_unm4sk-pt2.tc.mkv
./TV Shows/Mr. Robot/Season 02/Mr. Robot - S02E01 - eps2.0_unm4sk-pt1.tc.mkv

Any help or suggestions would be appreciated.

A: The issue is that, with find,  logical-and binds tighter than logical-or.  Observe:
$ ls
file1  file2  file3  file4
$ find . -name \*1 -o -name \*2 -exec echo {} \;
./file2

In the above, -name \*2 and -exec echo {} \; are bound together with an implied logical-and.  This logical-and binds stronger than the logical-or, -o, that connects the first -name to the second.
To avoid that, you need to apply parens for grouping:
$ find . \( -name \*1 -o -name \*2 \) -exec echo {} \;
./file1
./file2

Or, for your complete command:
find $convfold \( -name \*.mkv -o -name \*.avi -o -name \*.mov -o -name \*.wmv -o -name \*.m4p -o -name \*.m4v -o -name \*.mpg -o -name \*.mp2 -o -name \*.mpeg -o -name \*.mpe -o -name \*.mpv -o -name \*.m2v -o -name *.m4v \) -delete

Documentation
From man find:

Please note that -a when specified implicitly (for example by two
  tests appearing without an explicit operator between them) or
  explicitly has higher precedence than -o.  This means that
   find . -name afile -o -name bfile -print
  will never print afile.


text:
Q: BiometricPrompt Android: UnrecoverableKeyException on Samsung after software or security updates Posting here for the first time, wish me luck :)
We have developed a support of biometric authentication in our mobile app using BiometricPrompt API. We decided to go with CryptoObjects as it allows us to comply with regulations.
After implementation we are facing an issue that on Samsung devices and on some Huawei devices after some device software updates and after almost every Security Patch we are getting:
Caused by java.security.UnrecoverableKeyException: Failed to obtain information about key
       at android.security.keystore.AndroidKeyStoreProvider.getKeyCharacteristics(AndroidKeyStoreProvider.java:238)
       at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyFromKeystore(AndroidKeyStoreProvider.java:360)
       at android.security.keystore.AndroidKeyStoreSpi.engineGetKey(AndroidKeyStoreSpi.java:116)
       at java.security.KeyStore.getKey(KeyStore.java:1062)
       at com.*****.mobile.data.crypto.CryptoRepositoryImpl.getSignature(CryptoRepositoryImpl.java:527)
       at com.*****.mobile.business.biometric.authentication.BiometricAuthenticationPromptInteractorImpl$getSignatureForAuthentication$1.subscribe(BiometricAuthenticationPromptInteractorImpl.java:52)

Caused by android.security.KeyStoreException: User authentication required
       at android.security.KeyStore.getKeyStoreException(KeyStore.java:1151)
       at android.security.keystore.AndroidKeyStoreProvider.getKeyCharacteristics(AndroidKeyStoreProvider.java:240)
       at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyFromKeystore(AndroidKeyStoreProvider.java:360)
       at android.security.keystore.AndroidKeyStoreSpi.engineGetKey(AndroidKeyStoreSpi.java:116)
       at java.security.KeyStore.getKey(KeyStore.java:1062)

This forces us generating a new key pair, leading to a terrible user experience.
Has anyone experienced similar issues? And can suggest what needs to be changed/considered to prevent our key getting invalidated/corrupted after Samsung security patches?
We are generating a key pair using following code
(fallback is used as we discovered that cheaper Samsung devices not supporting EC, hence we use RSA on such devices):
@RequiresApi(Build.VERSION_CODES.M)
override fun createSigningKey(keyBaseName: KeyBaseName, useFallbackAlgorithm: Boolean): Either<Throwable, JavaPublicKey> = try {
  deleteKey(keyBaseName)
  when {
    useFallbackAlgorithm -> KeyPairGenerator
        .getInstance(KEY_ALGORITHM_RSA, ANDROID_KEY_STORE_PROVIDER)
        .apply {
          initialize(KeyGenParameterSpec.Builder(keyBaseName, PURPOSE_SIGN or PURPOSE_VERIFY)
              .setAlgorithmParameterSpec(RSAKeyGenParameterSpec(KEY_SIZE, RSAKeyGenParameterSpec.F4))
              .setDigests(DIGEST_SHA256, DIGEST_SHA512)
              .setSignaturePaddings(SIGNATURE_PADDING_RSA_PKCS1)
              .setUserAuthenticationRequired(true)
              .build())
        }
    else -> KeyPairGenerator
        .getInstance(KEY_ALGORITHM_EC, ANDROID_KEY_STORE_PROVIDER)
        .apply {
          initialize(KeyGenParameterSpec.Builder(keyBaseName, PURPOSE_SIGN or PURPOSE_VERIFY)
              .setDigests(DIGEST_SHA256, DIGEST_SHA512)
              .setUserAuthenticationRequired(true)
              .build())
        }
  }.generateKeyPair()
      .public
      .right()
} catch (e: Exception) {
  firebaseRepository.logException(RuntimeException("createSigningKey", e))
  e.left()
}

Thank you!

A: You can try to implement below 2 solutions to see if it works for you.

*

*Add allowBackup false to AndroidManifest.xml file

<application
    android:allowBackup="false"
...
>

*Android keystore is not thread-safe, please wrap all your Android keystore operations with synchronized keyword.


text:
Q: Struts2 regex configuration

I am creating a Struts2 web app.
I want an URL like www.xyz.com/portal/orgCode/signin,
this orgCode is dynamic, so I am using regex for that.
I configure struts.xml like:
<constant name="struts.devMode" value="false" />
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.action.extension" value=",html,action" />
<constant name="struts.action.excludePattern" value=".*unfiltered.*,.*\\.nofilter" />
<constant name="struts.multipart.maxSize" value="2097152000"/>
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
<constant name="struts.patternMatcher" value="regex" />

<package name="portal" namespace="/portal/{orgCode}" extends="default">
    <interceptors>
        <interceptor name="portalUrlInterceptor"
                    class="com.wtmit.service.portal.interceptor.PortalCommonInterceptor">
        </interceptor>
        <interceptor-stack name="commonPortalUrlInterceptor">
            <interceptor-ref name="portalUrlInterceptor" />
            <interceptor-ref name="defaultStack" />
        </interceptor-stack>
    </interceptors>

    <action name="signin" method="signin"
           class="com.wtmit.service.portal.action.PortalSignInAction">
        <interceptor-ref name="commonPortalUrlInterceptor"></interceptor-ref>
        <result name="portalSignIn" type="tiles">portalSignIn</result>
        <result name="successLogin" type="redirect">home</result>

    </action>
</package>

this is working fine, but URLs like www.xyz.com/mainLogin is not working for the following configuration:
<package name="main" namespace="/" extends="default">
    <action name="*Login" method="{0}" class="com.service.user.action.LoginAction">
        <result name="login" type="tiles">login</result>
        <result name="successLogin" type="redirect">home</result>
    </action>
</package>

The error is

HTTP Status 404 - There is no Action mapped for namespace / and action name mainLogin.

A: You are mixing Wildcards with Advanced Wildcards; instead of this:
<action name="*Login" method="{0}" class="com.service.user.action.LoginAction">

try using this:
<action name="/{method}/Login" method="{1}" class="com.service.user.action.LoginAction">

Related reads:

*

*Creating dynamic URL with 2 action parameters in Struts 2 using OGNL

*Advanced Wildcard Mappings Parameters not found in Prepare() method


text:
Q: In C++ STL algorithms, get index of a value inside lambda function? I wanted to get the index of the value(s) inside std algorithm's lambda function. So that, I can perform computation on the values based on the index. I am able to get an index with for_each function. However, I am not able to do so for std::adjacent_difference. Can you help me understand why I am not able to extract the index in other algorithms that use binary op? My attempt is to try in a generic fashion that work on a parallel (thrust) setting as well. So, did not seek a method of static count'ing.
//~~~START:Mon, 04-Oct-2021, 13:03:46 IST
//~~~Author:Rajesh Pandian M | mrprajesh.co.in
#include <bits/stdc++.h>
void print(const auto &data){
  std::copy(data.begin(),data.end(), std::ostream_iterator<int>(std::cout, " "));
  std::cout << '\n';
}
int main(int argc, char* argv[]){

  std::vector<int> data={0,2,3,5,10,11};
  std::for_each(data.begin(), data.end(), [&data](int const& value) {
    int idx = &value - &data[0];
    std::cout<< "idx: " << idx << '\n';
  });

  print(data);

  std::vector<int> result(data.size());
  std::adjacent_difference(data.begin(), data.end(), result.begin(),
    [&data]( const int& value2, const int& value1) {
      int idx = &value2 - &data[0];
      std::cout<< "idx: " << idx << '\n';
      return value2-value1; //Some expression involving index, values[1,2]
    });

  print(result);

  return 0;
}

Outputs:
idx: 0
idx: 1
idx: 2
idx: 3
idx: 4
idx: 5
0 2 3 5 10 11
idx: -102822055
idx: -102822055
idx: -102822055
idx: -102822055
idx: -102822055
0 2 1 2 5 1

A: From cppreference/adjacent_difference:

First, creates an accumulator acc whose type is InputIt's value type, initializes it with *first, and assigns the result to *d_first. Then, for every iterator i in [first + 1, last) in order, creates an object val whose type is InputIt's value type, initializes it with *i, computes val - acc (until C++20) val - std::move(acc) (since C++20) (overload (1)) or op(val, acc) (until C++20) op(val, std::move(acc)) (since C++20) (overload (3)), assigns the result to *(d_first + (i - first)), and move assigns from val to acc.

In short: The binary operator is called via op(val,acc) and neither val nor acc are elements of the container.
If you need the index you can populate a std::vector<std::pair<size_t,int>> such that data[ i ].first == i.


text:
Q: Using the Proguard tool with imported jars I'm using a jar of which I don't have the source code. I started using the proguard tool and some of the functionality of the implementation of this jar stop working, so I tried  changing the proguard configuration by adding (As seen in another question):
-keep class com.myexternaljar.** { public protected *; }

But it still doesn't behave as it should. So I'm guessing that this jar uses some other external classes that are being modified by the proguard tool.
Is there any configuration that can keep all the classes in a certain jar and all the classes that aren't in the jar itself but that are used by it?


text:
Q: C# UDPClient send data over global network Server Code :
    Thread thdUDPServer;
    private void Server_Load(object sender, EventArgs e)
    {
        thdUDPServer = new Thread(new ThreadStart(serverThread));
        thdUDPServer.Start();
    }

    UdpClient udpClient;
    public void serverThread()
    {
        udpClient = new UdpClient(53);
        while (true)
        {
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
            string returnData = Encoding.ASCII.GetString(receiveBytes);
            listBox1.Items.Add(RemoteIpEndPoint.Address.ToString() + ":" + returnData.ToString());
        }
    }

Client Code :
    UdpClient udpClient;
    private void Client_Load(object sender, EventArgs e)
    {
        udpClient = new UdpClient();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        udpClient.Connect(textBox1.Text, 53);
        Byte[] senddata = Encoding.ASCII.GetBytes("Hello World");
        udpClient.Send(senddata, senddata.Length);
    }

Working on local network but i need global.
Details :

*

*Microsoft Defender off.

*Run as admin (For Server App and Client App)

Example :
udpClient.Connect(95.10.xxx.13, 53);

Where am I doing wrong?
How can i send data over global network using another method?


text:
Q: How can I wait for my asynchronous Kiwi tests to complete, or run code after they do? I'm using Kiwi to do some asynchronous testing. One test checks that, after a (stubbed) network request, the response from the network is written to disk. Both the network request and writing the response to disk are done on background queues:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    [[HZMediationAPIClient sharedClient] GET:@"start" parameters:nil success:^(HZAFHTTPRequestOperation *operation, NSDictionary *json) {

        // store JSON to disk
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
            [json writeToURL:[[self class] pathToStartInfo] atomically:YES];
        });

        [self.delegate startWithDictionary:json fromCache:NO];

    } failure:^(HZAFHTTPRequestOperation *operation, NSError *error) {

    }];
});

I can test things like the delegate receiving the startWithDicationary:fromCache method using Kiwi's asynchronous testing capabilities:
[[expectFutureValue(starterMock) shouldEventually] receive:@selector(startWithDictionary:fromCache:) withArguments:json,theValue(NO)];

However, I'm not sure how to test that the data is written to disk correctly. I can do something like send a delegate method when after the data is written to disk, and then test that that happens:
[[expectFutureValue(starterMock) shouldEventually] receive:@selector(wroteDictionaryToCache)];

But even if I verify that message is sent, I can't check that the data is actually written to disk.
it(@"Returns the data from network when no cached value, then updates the cache", ^{
    // ... test setup here

    [[expectFutureValue(starterMock) shouldEventually] receive:@selector(wroteDictionaryToCache)]; // This code finishes immediately
    // Code here checking if the data has been written to disk will be executed before the above expectations become true.
});

Is there a way I can wait for the asynchronous expectations to pass/fail, so that I can then test that the data is written to disk? Or can I attach a completion block to the expectations, so that I can write future tests when those async expectations pass/fail?
If you have an alternative approach to testing this, that would be good as well.

A: I didn't come up with a way to accomplish exactly this, but I concluded it was better for testing purposes to move the caching logic out into a separate object and make it a dependency for the class I was testing. The interface for that looks like this:
@interface HZCachingService : NSObject

- (void)cacheDictionary:(NSDictionary *)dictionary filename:(NSString *)filename;
- (NSDictionary *)dictionaryWithFilename:(NSString *)filename;

@end

I just pass that object to the class I'm testing in its init method. In the tests, I stub that object and verify that cacheDictionary:filename: is called on it with the correct arguments.
I test the actual writing-to-disk behavior of HZCachingService in a separate spec.


text:
Q: Update map in-place I have a piece of code manipulating a map<int,int> object. Let's say that at some point I want to double all the entries, keys and values. Is a there a way to do it in place, without creating a new map, looping and entering updated entries?
My concern is saving memory space.

A: Doubling the values is possible like this:
std::map<int,int> my_map;
for(auto& item:my_map){
    item.second*=2; // double all values
}

However, it is not possible to double the Key since item is from the type std::pair<const int,int>. Notice the const for the Key.
Suggestion:
I think std::map is not best container for this case. Try this way:
std::vector<std::pair<int,int>> my_simi_map;
for(auto& my_simi_map){
    item.first*=2; // double all keys
    item.second*=2; // double all values
}

Edit:

My concern is saving memory space.

If it is just memory problem then you can pick an item from the map and insert a doubled version of it in the new map and directly delete it from the old map. In this case you will loose the size of just one element of the map not a whole another map.

A: You can traverse the map in reverse order of key for positive keys, in order to circumvent side effects, and create the new key/value pairs. You can do the equivalent for negative keys.
#include <cstdio>
#include <algorithm>
#include <map>

using namespace std;

int main() {
  map<int, int> m = {
    {10, 20},
    {-5, 23},
    {-10, 7},
    {20, 30},
    {15, 21},
    {18, 2},
  };

  for (auto it = m.begin(); it != m.end() && it->first < 0; it = m.erase(it)) {
    m[it->first * 2] = 2 * it->second;
  }

  for (auto it = m.rbegin(); it != m.rend() && it->first > 0; it++) {
    m[it->first * 2] = 2 * it->second;
    m.erase(----it.base());
  }

  for (auto &p: m) {
    printf("%d, %d\n", p.first, p.second);
  }
}

Output:
-20, 14
-10, 46
20, 40
30, 42
36, 4
40, 60


text:
Q: Matlab: plotting animation with fixed axes When I call this function, the axes are moving with the plot. How can I stop this from happening? I tried putting xlim and ylim before the function in the command window but that didn't work.
My code is:
function h = plootwithanimation(x,y)

    for  h = 1:length(x)
        plot(x(h),y(h),'*')
        pause(1)
        hold on
    end

A: Try fixing the bounds using the axis function:
function h = plootwithanimation(x,y)

for  h = 1:length(x)
     plot(x(h),y(h),'*')
     axis([0 10 -2 100]) %or whatever you want. This sets 0<x<10 and -2<y<100
     pause(1)
     hold on

end

A: You can fix the bounds by using xlim and ylim as you tried, but plotting will ignore whatever you set the axes to before calling plot.
You should instead use them after the plot
function h = plotwithanimation(x, y, xlims, ylims)
% Also pass in axis limits
%   xlims = [x0,x1]
%   ylims = [y0,y1]

hold on; % You only have to hold on once around plotting
for  h = 1:length(x)
    plot(x(h),y(h),'*');
    xlim(xlims);
    ylim(ylims);
    pause(1);
end
hold off; % Good habit so you don't accidentally plot over this figure later


text:
Q: Makefile: CreateProcess(...) failed. The system cannot find the file specified I'm trying to deal with Makefiles and wrote a simple "program":
DELETE_COMMAND := del
COMPILER := gcc
SOME_TEXT := lalalalalalalalalalalal!!!

all: sum.o even.o main.o pi.o
    @$(COMPILER) -o output.exe sum.o even.o main.o pi.o
    SOME_TEXT_2 := $(subst la,La,$(SOME_TEXT))
    @echo $(SOME_TEXT_2)

clean:
    @$(DELETE_COMMAND) *.o
    @$(DELETE_COMMAND) output.exe

sum.o: sum.c sum.h
    @$(COMPILER) -c sum.c

main.o: main.c sum.h pi.h
    @$(COMPILER) -c main.c

pi.o: pi.c pi.h even.h
    @$(COMPILER) -c pi.c

even.o: even.c even.h
    @$(COMPILER) -c even.c

But I get the following error:

SOME_TEXT_2 := LaLaLaLaLaLaLaLaLaLaLal!!!
  process_begin: CreateProcess(NULL, SOME_TEXT_2 := LaLaLaLaLaLaLaLaLaLaLal!!!, ...) failed.
  make (e=2): The system cannot find the file specified.
  make: *** [Makefile:7: all] Error 2

The problem is caused by this line:
    SOME_TEXT_2 := $(subst la,La,$(SOME_TEXT))

but I have no idea what the problem is.
I'm using make from mingw-w64 on Windows.

A: Consider the rule...
all: sum.o even.o main.o pi.o
        @$(COMPILER) -o output.exe sum.o even.o main.o pi.o
        SOME_TEXT_2 := $(subst la,La,$(SOME_TEXT))
        @echo $(SOME_TEXT_2)

Assuming all lines except the first begin with a tab character then each command will be run in a separate shell.  But...
SOME_TEXT_2 := $(subst la,La,$(SOME_TEXT))

is not valid shell syntax -- it looks like it's supposed to be interpreted by make.
If the intent is simply to modify the variable SOME_TEXT and print the result then you can have either...
all: sum.o even.o main.o pi.o
        @$(COMPILER) -o output.exe sum.o even.o main.o pi.o
        @echo $(subst la,La,$(SOME_TEXT))

or, let make assign to SOME_TEXT_2...
SOME_TEXT_2 := $(subst la,La,$(SOME_TEXT))

all: sum.o even.o main.o pi.o
        @$(COMPILER) -o output.exe sum.o even.o main.o pi.o
        @echo $(SOME_TEXT_2)


text:
Q: No wrap on whitespace provides additional space when there is a line break I've been using this aligned list to display recent titles.
You can see an example of it here: http://jsfiddle.net/01day856/
However, I've noticed that whenever I break a line it will show up as an extra bit of space on the top. So, I changed my .game class to appears as this:
.game {
    display: inline-block;
    white-space: nowrap;
}

I've included the white-space: nowrap; and it seemed to fix it, but now my titles don't break the line like they are supposed to.
How can I combat the white-space: nowrap and allow my titles to break lines when they extend too far? I tried  adding in  word-wrap: break-word and nothing seems to work.

A: The simple alternative would be to remove white-space: nowrap. Since they are inline-block level elements, you could add vertical-align: top to fix the alignment issues:
Updated Example
.game {
    display: inline-block;
    vertical-align: top;
}


text:
Q: off screen graphics resolution in java.awt I have some java code that needs to programmatically render text onto an image. So I use BufferedImage, and write text on the Graphics object.
However, when configuring the font instance, one would specify the font size in points. When a piece of text is rendered onto an image, AWT will translate the points into pixels, based on the resolution of the Graphics object. I don't want to get myself involved in computing the pixel/point ratio, since it's really the task for the AWT. The image that is being produced is for a high resolution device (higher than any desktop monitors).
But, I don't seem to find a way to specify what the resolution of the Graphics is. It inherits it from the local graphics environment, which is beyond my control. I don't really want this code to be dependent on anything local, and I'm not even sure it's "sane", to use local graphics environment for determining the resolution of off screen rasters, who knows what people would want them for.
So, any way I can specify the resolution for an off screen image of any kind (preferably the one that can create Graphics object so I can use standard AWT rendering API)?
(update)
Here is a (rather long) sample problem that renders a piece of text on an image, with predefined font size in pixels (effectively, the target device DPI is 72). What bugs me, is that I have to use local screen DPI to make the calculation of the font size in points, though I'm not using the screen in any way, so it's not relevant, and plain fails on headless systems all together. What I would loved in this case instead, is being able to create an off screen image (graphics, raster), with DPI of 72, which would make points, by value, be equal to pixels.
Sample way to run the code:
$ java FontDisplay Monospace 150 "Cat in a bag" 1.png

This would render "Cat in a bag message", with font size of 150 pixels, on a 150 pixel tall image, and save the result in 1.png.
import java.awt.*;
import java.awt.image.*;
import java.awt.font.*;
import javax.imageio.*;
import javax.imageio.stream.*;
import java.io.*;
import java.util.*;

public class FontDisplay {

    public static void main(String a[]) throws Exception {

        // args: <font_name> <pixel_height> <text> <image_file>
        // image file must have supported extension.

        int height = Integer.parseInt(a[1]);
        String text = a[2];

        BufferedImage bi = new BufferedImage(1, 1,
                BufferedImage.TYPE_INT_ARGB);

        int dpi = Toolkit.getDefaultToolkit().getScreenResolution();
        System.out.println("dpi : "+dpi);
        float points = (float)height * 72.0F / (float)dpi;
        System.out.println("points : "+points);

        Map m = new HashMap();
        m.put(TextAttribute.FAMILY, a[0]);
        m.put(TextAttribute.SIZE, points);

        Font f = Font.getFont(m);

        if (f == null) {
            throw new Exception("Font "+a[0]+" not found on your system");
        }

        Graphics2D g = bi.createGraphics();

        FontMetrics fm = g.getFontMetrics(f);

        int w = fm.charsWidth(text.toCharArray(), 0, text.length());

        bi = new BufferedImage(w, height, BufferedImage.TYPE_INT_ARGB);

        g = bi.createGraphics();
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, w, height);
        g.setColor(Color.WHITE);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
        g.setFont(f);
        g.drawString(text, 0, fm.getMaxAscent());

        String fName = a[3];
        String ext = fName.substring(fName.lastIndexOf('.')+1).toLowerCase();

        File file = new File(fName);
        ImageWriter iw = ImageIO.getImageWritersBySuffix(ext).next();

        ImageOutputStream ios = ImageIO.createImageOutputStream(file);
        iw.setOutput(ios);
        iw.write(bi);
        ios.flush();
        ios.close();

    }

}

A: Comparing points to pixels is like kg to Newton where the acceleration may give varying conversions. AWT lets you elect a device (screen, printer), but in your case you definitely have to determine your ratio.
You may of course use Photoshop or Gimp and create a normative image for java.

After elaborated question:
Ah, I think I see the misunderstanding. An image does only concern pixels, never points, mm, DPI, or whatever. (Sometimes only as metainfo added separately to the image.)
So if you know the DPI of your device, the inches you want to use, then the dots/pixels are clear. points/dpi may shed more light.


text:
Q: Como converto LINQ em SQL para o MySQL? Estou tentando remover o uso de instruções SQL de dentro do sistema (para torná-lo flexível quanto ao banco que será usado), uso instruções Insert, Update e Delete via stored procedure (pelo de desempenho e pela flexibilidade), mas ainda uso instruções SQL para as consultas pois se transforma-las em stored procedures vou ter que criar várias procedures para cada tabela do sistema.
Então como posso converter uma instrução LINQ qualquer em um SQL para MySQL?

A: Stored procedure não possue ganho de desempenho significativo para operações de CRUD, a não ser que você esteja fazendo agregações de dados e manipulações complexas que envolveriam muitos "ir e vir" entre sua aplicação e o DB.
Store procedures também não aumentam flexibilidade, uma vez que cada RDBMS possui sintaxe diferente, causando a reescrita as vezes até total da procedure.
Como você não postou código algum, recomendo que leia o beginner's guide da própria Microsoft sobre o assunto:
Beginner's Guide to LINQ to SQL
Edição
Para utilizar LINQ com MySql, acredito que sua única opção seja o pacote LinqConnector, que inclusive suporta outros RDBMS além do MySQL. Ele está disponível no NuGet para instalação ou no endereço:
LinqConnect Express

A: Pelos comentários deu para entender (eu acho) que você quer deixar de usar SQL para usar o LINQ.
Além de tudo o que o Vinícius disse, você não deve fazer isso se você quer a possibilidade de usar vários bancos de dados diferentes. Talvez a mais notória limitação do LINQ To SQL é justamente em não poder trabalhar com diversos bancos.
Se esta é sua intenção deve criar um mecanismo próprio ou usar algum pronto que abstraia as diferenças entre os diversos bancos.
Não vou dizer que recomendo mas você deveria dar uma olhada no Entity Framework, este é o ORM que é recomendado pela Microsoft em casos assim. Na página da Wikipedia tem uma lista de outras opções como o NHibernate que ainda também tem razoável utilização.
Não é tão fácil aprender usá-los mas deve dar o resultado que você espera.
Não conheço estes produtos o suficiente para lhe dizer se é fácil trabalhar com stored procedures da maneira como você pretende usando estas tecnologias.
Com o EF é possível usar o LINQ mas no modelo LINQ To Entities.
Se preferir algo mais simples e puder continuar lidando com SQL pode dar uma olhada no Dapper. Em geral eu prefiro caminhos mais simples. Mas é claro que neste caso tem que saber como trabalhar com os diversos bancos sem causar confusão. Eu particularmente acho mais fácil fazer desta forma mas a maioria dos programadores acham que é mais fácil deixar um framework pronto lidar com isto.
Reforço a ideia já relatada por outros que stored procedure não é uma boa ideia para o que você deseja. Muito menos vai trazer os benefícios que está relatando que terá. Eu diria que provavelmente trará resultado contrário em algumas situações.


text:
Q: How to perform data factory transformations on large datasets in Azure data warehouse We have Data warehouse tables that we perform transformations using ADF.
If I have a group of ADW tables, and I need to perform transformations on them to land them back onto ADW, should I save the transformations into Azure Blob Storage? or go direct into the target table.
The ADW tables are in excess of 100Mil records.
Is it an acceptable practice to use Blob Storage as the middle piece.

A: I can think of two ways to do this (they do not require moving the data into blob storage),

*

*Do the transformation within SQL DW using stored procedure and use ADF to orchestrate the stored procedure call

*Use ADF's data flow to apply the transformation to read from SQL DW and write back to SQL DW

A: Yes, you'd better using the use Blob Storage as the middle piece.
You can not copy the tables from SQL DW(Source) to the same SQL DW(Sink) directly! If you have tried this, you will have the problems:

*

*Copy data: has the error in data mapping, copy data to the same table, not create new tales.

*Copy Active: Table is required for Copy activity.

If you want to copy the data from SQL DW tables to  new tables with Data Factor, you need at least two steps:

*

*copy the data from the SQL DW tables to Blob storage(create the csv
files).

*Load these csv files to SQL DW and create new tables.

Reference tutorials:

*

*Copy and transform data in Azure Synapse Analytics (formerly Azure
SQL Data Warehouse) by using Azure Data Factory

*Copy and transform data in Azure Blob storage by using Azure Data
Factory
Data Factory is good at transfer big data. Reference Copy performance of Data Factory. I think it may faster than SELECT - INTO Clause (Transact-SQL).
Hope this helps.


text:
Q: Machine learning and images of different size Lets say I have a machine learning system that has learned to identify whether or not an image contains an object (for example a car).
My question is the following, what to do when the system receives images of different sizes? the training set for example could be composed of images of 1000x700 px, but the real world is not so uniform, and one can expect images for 700x1000, 700x400 ...
The first impulse would be to resize the image to have the same size as the training set, but that feels dirty and not really useful.
Am I missing something obvious here? Also, even for the training set, I assume that it does not really  make sense to assume that every image would be of a fixed size (again, lets assume 1000x700 px).
Also, if one uses the sliding window technique, the same problem might arise, as it is not easy to determine what is the correct window size.
I imagine that this must be a relatively common problem, so there must be a set of common solutions to it, any ideas?

A: Yes.  The common solutions are

*

*Resize and crop -- reduce or enlarge the image until both dimensions are at least the desired ones.  Then crop the photo to the common size.

*Crop -- extract a crop of the common size, padding if needed.

Now ... cropping is usually done with a series of cropped photos: all four corners and the center.  In (1) above, there would be only three images, not 5.