text:
Q: How to add a header line to a downloaded file How do I add column names upon downloading it into text file. I can already download a file but there is no column names inside my text file.
I am using GUI_DOWNLOAD call method function.

A: Declare a new internal table with all fields are CHAR type. Append header texts to the first row and append your data containing internal table to it.


text:
Q: cellRenderer single cell height How do you change the height of a single cell.
override protected function drawLayout():void {
    textField.width = this.width;
    height = 64;

    textField.height = height;
    textField.setTextFormat(tf);
    super.drawLayout();
}

How do I get the dataGrad to resize the entire row? I'm using a height of 64. but the idea is that it would be dynamic.

redpajama_set_name: RedPajamaStackExchange


text:
Q: font-url is resulting in asset prefix appearing twice in request for asset In a Rails 5 application we are trying to load a custom font. In development this works as expected but in staging with asset prefix set to either /static or static it is resulting in a 404 for the font as it requests /static/static/font_name.
We are using Webpack to compile assets, we've tried removing the prefix and compiling everything to public assets but none of the items load correctly at that point. If we check the server the font has been fingerprinted and is in the static directory for the application.
SCSS file for fonts
@font-face {
  font-family: 'neuzeits_book';
  src: font-url('neuzeits_book.eot');
  src: font-url('neuzeits_book.eot#iefix') format('embedded-opentype'),
       font-url('neuzeits_book.woff2') format('woff2'),
       font-url('neuzeits_book.woff') format('woff'),
       font-url('neuzeits_book.svg') format('svg'),
       font-url('neuzeits_book.ttf') format('truetype');
}

$font_body: 'neuzeits_book', arial;

The below is the generated css on staging.
@font-face {
    font-family: 'neuzeits_book';
    src: url(static/neuzeits_book-feb4879f32fd707ba88e9d1f9f2a5e901042ab66a3e01560d9b73f22ded85185.eot);
    src: url(static/neuzeits_book-feb4879f32fd707ba88e9d1f9f2a5e901042ab66a3e01560d9b73f22ded85185.eot#iefix) format("embedded-opentype"),url(static/neuzeits_book-874e588d20dc28011a445eb8f645f610b6a312a7217bab344d1394187d96334a.woff2) format("woff2"),url(static/neuzeits_book-1228efc2d44dc6f54667fcba56588d3ad66c689b73e64f382370c23ebaa00975.woff) format("woff"),url(static/neuzeits_book-903eaa19a9dc9ae8210827ebf4591347271825b13bb4d25efb1fdacb1f8b9dab.svg) format("svg"),url(static/neuzeits_book-a34d20b4bf82e78b20547e4d32a4846acefc2e1f96e30ed9186a1b1594963d32.ttf) format("truetype")
}

And the below is the configuration for the assets on staging.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
config.react.variant = :production

config.assets.compress = true
config.assets.compile = false
config.assets.digest = true
config.assets.enabled = true
config.assets.initialize_on_precompile = true
config.assets.prefix = '/static'
config.assets.paths << Rails.root.join('node_modules')
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')


text:
Q: type 'List' is not a subtype of type 'Map' Flutter I need help on the following error  type 'List' is not a subtype of type 'Map<String, dynamic>'
I tried every possible solution but I still cannot be able to solve it.
Future<List<Autogenerated>?> signInData() async {
    final prefs = await SharedPreferences.getInstance();
    final String? token = prefs.getString('token');

    try {
      Response response = await _dio.post('$_baseUrl/api/gateway',
          data: {
            "ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
            "PlatformId": "ios",
            "ClientUserId": "AhmedOmar",
            "VinNumber": VINumber
          },
          options: Options(
            headers: {
              "Content-Type": "application/json;charset=UTF-8",
              "Charset": 'utf-8',
              "Authorization": "Bearer $token",
            },
          ));
      print("data is here");
      print(json.encode(response.data));
      print(response.statusCode);
      if (response.statusCode == 200) {
        print("decoded");

        // return List<Autogenerated>.from(
        //     response.data.map((i) => Autogenerated.fromJson(i)));
        //return Autogenerated.fromJson(jsonDecode(json.encode(response.data)));
        return (response.data as List)
            .map((e) => Autogenerated.fromJson(e))
            .toList();
      } else if (response.statusCode == 500) {
        // call your refresh token api here and save it in shared preference
        print(response.statusCode);
        await getToken();
        signInData();
      } else {
        throw Exception('Failed to load data');
      }
    } catch (e) {
      print(e);
    }
  }

I am getting error in the following line:
 return (response.data as List)
            .map((e) => Autogenerated.fromJson(e))
            .toList();

My model class below
class Autogenerated {
  int? id;
  int? sourceId;
  int? serviceId;
  int? categoryId;
  String? category;
  String? description;
  int? serviceResponsePropertyId;
  int? mappingId;
  bool? isVisible;
  int? packageRequestId;
  int? sortOrder;
  Value? value;

  Autogenerated(
      {this.id,
      this.sourceId,
      this.serviceId,
      this.categoryId,
      this.category,
      this.description,
      this.serviceResponsePropertyId,
      this.mappingId,
      this.isVisible,
      this.packageRequestId,
      this.sortOrder,
      this.value});

  Autogenerated.fromJson(Map<String, dynamic> json) {
    id = json['Id'];
    sourceId = json['SourceId'];
    serviceId = json['ServiceId'];
    categoryId = json['CategoryId'];
    category = json['Category'];
    description = json['Description'];
    serviceResponsePropertyId = json['ServiceResponsePropertyId'];
    mappingId = json['MappingId'];
    isVisible = json['IsVisible'];
    packageRequestId = json['PackageRequestId'];
    sortOrder = json['SortOrder'];
    value = json['Value'] != null ? new Value.fromJson(json['Value']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['Id'] = this.id;
    data['SourceId'] = this.sourceId;
    data['ServiceId'] = this.serviceId;
    data['CategoryId'] = this.categoryId;
    data['Category'] = this.category;
    data['Description'] = this.description;
    data['ServiceResponsePropertyId'] = this.serviceResponsePropertyId;
    data['MappingId'] = this.mappingId;
    data['IsVisible'] = this.isVisible;
    data['PackageRequestId'] = this.packageRequestId;
    data['SortOrder'] = this.sortOrder;
    if (this.value != null) {
      data['Value'] = this.value!.toJson();
    }
    return data;
  }
}

class Value {
  String? make;
  String? type;
  String? model;
  int? year;
  String? body;
  String? driveType;
  String? fueType;

  Value(
      {this.make,
      this.type,
      this.model,
      this.year,
      this.body,
      this.driveType,
      this.fueType});

  Value.fromJson(Map<String, dynamic> json) {
    make = json['make'];
    type = json['type'];
    model = json['model'];
    year = json['year'];
    body = json['body'];
    driveType = json['drive_type'];
    fueType = json['fue_type'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['make'] = this.make;
    data['type'] = this.type;
    data['model'] = this.model;
    data['year'] = this.year;
    data['body'] = this.body;
    data['drive_type'] = this.driveType;
    data['fue_type'] = this.fueType;
    return data;
  }
}

My response from API(It's long, I just shorten it)
[
    {
        "Id": 0,
        "SourceId": 0,
        "ServiceId": 11,
        "CategoryId": 5,
        "Category": "Valuation",
        "Description": "AdjustedValues",
        "Value": [],
        "ServiceResponsePropertyId": 474,
        "MappingId": 0,
        "IsVisible": true,
        "PackageRequestId": 13853506,
        "SortOrder": 1
    },
    {
        "Id": 0,
        "SourceId": 0,
        "ServiceId": 11,
        "CategoryId": 1,
        "Category": "General",
        "Description": "ServiceStatus",
        "Value": {
            "StatusCode": 1,
            "StatusDescription": "Ok",
            "StatusDetail": "",
            "RestServiceStatus": null,
            "ServiceResource": null
        },
        "ServiceResponsePropertyId": 475,
        "MappingId": 0,
        "IsVisible": false,
        "PackageRequestId": 13853506,
        "SortOrder": 1
    },
    {
        "Id": 0,
        "SourceId": 0,
        "ServiceId": 6,
        "CategoryId": 1,
        "Category": "General",
        "Description": "CarId",
        "Value": 120354,
        "ServiceResponsePropertyId": 100,
        "MappingId": 0,
        "IsVisible": false,
        "PackageRequestId": 13853506,
        "SortOrder": 1
    },
    {
        "Id": 0,
        "SourceId": 0,
        "ServiceId": 6,
        "CategoryId": 1,
        "Category": "General",
        "Description": "Year",
        "Value": 2017,
        "ServiceResponsePropertyId": 103,
        "MappingId": 0,
        "IsVisible": true,
        "PackageRequestId": 13853506,
        "SortOrder": 6
    },
    {
        "Id": 0,
        "SourceId": 0,
        "ServiceId": 6,
        "CategoryId": 1,
        "Category": "General",
        "Description": "Full Model Description",
        "Value": "2017 AUDI A3 Sedan 1.0T FSI S tronic [2016-2017]",
        "ServiceResponsePropertyId": 104,
        "MappingId": 0,
        "IsVisible": false,
        "PackageRequestId": 13853506,
        "SortOrder": 1
    },

I cannot display data in lisview and I think it is because of this error. Please can you check there and please assist. Thank you in advance.

A: The error probably has been mis-attributed to the method Autogenerated.fromJson.
Problem
The method Value.fromJson() expects a Map<String, dynamic>:
Value.fromJson(Map<String, dynamic> json).
But the response.data shows that Value can be many things:

*

*a List: "Value": []

*a String: "Value": "abc"

*a Map: "Value": { ... }

*a Int: "Value": 123
Note
The first Value item in your response.data is a List. Which explains why the code is complaining about expecting a Map but getting a List.
Solution
Value.fromJson(...) needs to be able to handle lists, Strings, Ints, Maps etc. Not only Maps.


text:
Q: Как использовать moveTo для Actor? как правильно использовать moveTo?
пытаюсь делать так, но актер не двигается
public class MyActions extends ApplicationAdapter {
    private Stage stage;
    private Actor actor;

    @Override
    public void create () {

        stage = new Stage();
        actor = new Actor(){
            {
                setSize(100, 100);
            }
            Sprite actorSprite = new Sprite(new Texture(Gdx.files.internal("badlogic.jpg")), 57, 10, (int)getWidth(), (int)getHeight());

            @Override
            public void draw(Batch batch, float parentAlpha) {
                actorSprite.draw(batch, parentAlpha);
            }
        };

        stage.addActor(actor);
        actor.addAction(Actions.moveTo(500, 500, 1));
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 1, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        actor.act(Gdx.graphics.getDeltaTime());
        //stage.act();
        stage.draw();
    }
}

поделитесь работающим примером


text:
Q: Defining absolute margin in nested div I hope I described it correctly when I stated "nested div".
I have an image in a div like this:
content -> content-inner -> column_left

I'm unable to make the image begin at 0 px (the very left side of the screen).
It seems I'm trapped in margin definition of the div.
The divs are defined like this (seen in Chrome Inspector):

#content {
    position: relative;
    left: 0px;
    top: 0px;
    z-index: 2;
    width: 100%;
    min-width: 280px;
    max-width: 980px;
    margin-left: auto;
    margin-right: auto;
    padding-top: 0px;
    padding-bottom: 0px;
}

#content-inner {
    margin-left: 20px;
    margin-right: 20px;
    background-color: #FFF;
}

.column_left {
    position: relative;
    left: 0px;
    top: 0px;
    width: 65%;
    margin-right: 5%;
    float: left;
}

I created a new div like this:
.inlineimage
{
float: left;
margin-left: 0px;
margin-right: 20px;
margin-bottom: 5px;
margin-top: 3px;
}

And then I assigned it to the image within the "column-left" div:

However, the image sticks to the border of the column (which is around 105 px).
How could I make the image stick to 0 px margin from the left side of the page?
Thank you.

A: You could position your .inlineimage container to position: relative; then position the img as
.inlineimage > img {
  position: absolute;
  left: 0;
  top: 0;
}

This way your image sticks to the top/left


text:
Q: Invalid property name on padding I have different padding values based on media queries. But, upon inspect, those padding values are not being implemented and it's returned invalid property values and I'm unsure why?

My scss:

.myAccount {
  padding: 140px 0 40px 0;
  @include media-breakpoint-up(md) {
    padding: 180px 0 100px 0;
  }
  @include media-breakpoint-up(lg) {
    padding: 200px 0 130px 0;
  }
  @include media-breakpoint-up(xl) {
    padding: 220px 0 120px 0;
  }
}

On large screens (i.e. 1200px), the default padding (140px 0 40px 0) is being applied, as the media query isn't kicking in.

A: This was incredibly hard to debug, pure luck helped me. When I've pasted your code into codepen I've realised that you have a zero-width space symbol right before zero in the first two padding declarations, check it out:

Removing those must resolve the issue


text:
Q: StartActivityForResult from a bounded Service I have a Service that is bounded to an Activity A, from this Service I need to call an Activity B and wait for the result.
I manage to call the activity B like that:
val intent = Intent(contextOfActivityA, ActivityB::class.java)
(contextOfActivityA as ComponentActivity).startActivityForResult(intent, 123)

The problem is that I don't know how to catch the result of the ActivityB.
If I use onActivityResult is never called:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (resultCode == Activity.RESULT_OK) {
        //result
    }

How can I do that? Bear in mind that I can control only the Service so I can't modify or handle the result call in the Activity A.
Thanks

A: This is not possible. Services run as stand-alone entities, have no UI and perform background activities. When a Service launches an Activity, the Activity runs in a task associated with UI. An Activity can launch another Activity and get a result back (using startActivityForResult()), but a Service is a whole different thing.


text:
Q: Storing and presenting data in logical and easy to use way Currently, I am parsing some UNSTRUCTURED text and CONVERT IT TO THIS:
Type1
Type1 Description1 - Type1 Specification1
Type1 Description2 - Type1 Specification2
Type1 Description3 - Type1 Specification3
..more descriptions and specifications

Type2
Type2 Description1 - Type2 Specification1
Type2 Description2 - Type2 Specification2
Type2 Description3 - Type2 Specification3
..more descriptions and specifications

..more Types

etc.
It is a String - spaces and returns delimited.
Although it is easy to read, I understand that this is not efficient way to do this. It is also pretty hard to disassemble it back to initial components(type, description, specification)
My questions:
A. What would be the most efficient way to store this data in memory, and with possibility to save to disk (not in the database) ?
I was thinking about XML, but I never worked with it
and hardly understand it's structure; but if you think
that is the only right way to do it, I guess I would
have to work on it!

B. What would be the best way to present this data in winform , considering that there might be multiple types and multiple type definitions?
Here, I am not sure. I can continue using textbox,
but it also does not seems to be the great way.
Maybe generate HTML and then plug it in? Seems inefficient.

A: A) Create a class that hold a description and a specification; not sure what it should be called.
Create your own type class that has a list of the above class.  (Try not to call it Type though, it would be confused with System.Type.)
As for storing it on a disk, XML isn't a bad idea, but it is simple enough that you can just put each Type on a single line in a file with a comma (or tab) separated list of description/specification pairs.  XML is easier to read in plain text, but more work for a computer to process and will use more space on disk.  I would use XML if there is a small amount of data, and I would consider the other options more if there is a lot of it and a person is rarely needing to look at the file.
B) I would use a TreeView.


text:
Q: Where does backend belong to in Zend Framework Do you have it as a separate Module, or just one separate Controller, or multiple Controllers without any logical separation from Frontend (except for Auth ofcourse), or something else?
Assuming that backend is reasonably complicated, i.e. something more than review/confirm/delete comments for your BLOG.

A: Definatly belongs in a new module then it is easy to create a separate layout in my opinion.
In a recent project a colleague created a separate admin controller in each module with the layout defined in an admin module. This way he could drop in/remove modules from the project with the main admin module autodetecting which modules are installed and creating menus based on the admin controller found in each pluggable module.
I have explained that poorly, but it's a good system.

A: I would create a separate module. Otherwise you might run into context issues because the ArticleController in the frontend should have other/limited functionalities then the administrative ArticleController and you end up implementing mixed controller classes (bad idea!) or prefix the administrative class.
So having multiple modules makes it easier to separate different concerns.
(Plus it will make it easier for you to implement an ACL and handle the corresponding resource/role definitions.)


text:
Q: How to generate a 3D array of data based on a 1D array of data and three 1D arrays of spatial coordinates I have 3D scattered data that I need to interpolate. My chosen interpolation method requires inputs of (x,y,z,v) where:
(x,y,z) spatial coordinates of original grid (1D or 3D arrays)
(v)     values of data (must be 3D array)
I currently have four 1D arrays for x,y,z, and v with lengths of L=5000 for 5000 unique data points.
Using the solution provided here,
Creating a numpy array of 3D coordinates from three 1D arrays
Numpy.meshgrid produces 3D arrays for each coordinate direction with 1.25 × 10^11 elements. I run out of memory using this approach.
Is there another method to map my 1D array of values, v, to a 3D array with the appropriate size of 5000 elements?


text:
Q: What is the C++ equivalent to this MATLAB code? In my project, I am responsible for migrating some MATLAB code to C++. The code below refers to serial communication from a computer to a microcontroller.  The function CreatePackage generates a package which is then sent to the microcontroller using MATLAB's fwrite(serial) function.
function package = CreatePackage(V)
for ii = 1:size(V,2)
    if V(ii) > 100
        V(ii) = 100;
    elseif V(ii) < -100
        V(ii) = -100;
    end
end

vel = zeros(1, 6);
for ii = 1:size(V,2)
    if V(ii) > 0
        vel(ii) = uint8(V(ii));
    else
        vel(ii) = uint8(128 + abs(V(ii)));
    end
end

package = ['BD' 16+[6, vel(1:6)], 'P' 10 13]+0;

And then, to send the package:
function SendPackage(S, Package)

for ii = 1:length(S)
    fwrite(S(ii), Package);
end

How can I create an array/vector in C++ to represent the package variable used in the MATLAB code above?
I have no experience with MATLAB so any help would be greatly apreciated.
Thank you!

A: The package variable is being streamed as 12, unsigned 8-bit integers in your MATLAB code, so I would use a char[12] array in C++.  You can double check sizeof(char) on your platform to ensure that char is only 1 byte.
Yes, MATLAB default data-type is a double, but that does not mean your vector V isn't filled with integer values.  You have to look at this data or the specs from your equipment to figure this out.
Whatever the values are coming in, you are setting/clipping the outgoing range to [-100, 100] and then offsetting them to the byte range [0, 255].
If you do not know a whole lot about MATLAB, you may be able to leverage what you know from C++ and use C as an interim.  MATLAB's fwrite functionality lines up with that of C's, and you can include these functions in C++ with the #include<cstdio.h> preprocessor directive.
Here is an example solution:
#include <cstdio.h>    // fwrite
#include <algorithm>  // min, max
...

void makeAndSendPackage(int * a6x1array, FILE * fHandles, int numHandles){

   char packageBuffer[13] = {'B','D',24,0,0,0,0,0,0,'P','\n','\r',0};

   for(int i=0;i<6;i++){
       int tmp = a6x1array[i];
       packageBuffer[i+3] = tmp<0: abs(max(-100,tmp))+144 ? min(100,tmp)+16;
   }

   for(int i=0;i<6;i++){
       fwrite(fHandles[i],"%s",packageBuffer);
   }

}

Let me know if you have questions about the above code.


text:
Q: How to create a carousel with wider centred-element? I need to build a carousel with following the design structure:

I have tried multiple libraries: react-slick, owl-slider, brainhubeu's react-carousel & tiny-slider. All of them seem to be designed for fixed width cards/sliders. Once I change dimension for my current active slider, its position gets lost.
Have you seen something similar anywhere? Any examples or ideas are welcomed (preferably React.js solutions).

A: Use the Owl carousel plugin. You can easily use it and it have instruction for installing using npm. after you created your slider, simply give the owl-item with active class the style you want. I have created the main css and HTML structure for you. just add the needed dependencies to your react project and use it.

$('.owl-carousel').owlCarousel({
    loop:true,
    margin:10,
    autoWidth:true,
    center:true,
    nav: false,
    autoplay: true,
    autoplayTimeout: 3000,
    autoplayHoverPause: true,
    responsiveClass:true,
    responsive:{
        0:{
            items:1
        },
        600:{
            items:4
        },
        1000:{
            items:5
        }
    }
})
body{
  direction: ltr
}

.owl-carousel .owl-stage{
  display: flex;
  justify-content: center;
  align-items: flex-end;
}

.owl-carousel .owl-item .item{
  width: 120px;
  min-height: 120px;
  background-color: lightblue;
}

.owl-carousel .owl-item.active.center .item {
  width: 160px;
  height: 200px;
  background-color: pink;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" />
<link  rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.css" />

1

2

3

4

5

6

7

8

9

10

11

12

A: check out this example with slick https://codepen.io/ealigam/pen/yEzQPP
I could bring it to pretty similar look as you describe by slightly adjusting
$('.slider').slick({
  centerMode: true,
  slidesToShow: 3,
  centerPadding: "15%",
  speed: 500
});


text:
Q: Solve an integral with the fundamental theorem of calculus
Determine $$\int_a^b \frac{f'(x)}{\cos^2(f(x))}\,e^{\tan(f(x))}\,dx$$ (for $\dfrac \pi 2+ k\pi \not\in f([a,b])$ for all $k \in \mathbb{Z}$) with the fundamental theorem of calculus.

My solution approach so far:
Let $F:[a,b]\to \mathbb{R}, F(x):=\tan(f(x))$. Then $F$ is continuously differentiable over $[a,b]$ with $F'(x)=\frac{f'(x)}{\cos^2(f(x))}$ for all $x\in [a,b]$.
I am not sure about the $e^{\tan(f(x))}$. If it didn't exist, I would just solve the integral with $F(b)-F(a)$. What do I do with the $e^{\tan(f(x))}?$

A: Let $u=\tan (f(x))$, then you have $du=\frac{f'(x)}{\cos^2(f(x))}dx$
Thus $$ \int_a^b \frac{f'(x)}{\cos^2(f(x))}\,e^{\tan(f(x))}\,dx =\int_{\tan(f(a))}^{\tan(f(b))} e^udu$$


text:
Q: Show the existence of a complex differentiable function defined outside $|z|=4$ with derivative $\frac{z}{(z-1)(z-2)(z-3)}$ My attempt
I wrote the given function as a sum of rational functions (via partial fraction decomposition), namely
$$
\frac{z}{(z-1)(z-2)(z-3)} = \frac{1/2}{z-1} + \frac{-2}{z-2} + \frac{3/2}{z-3}.
$$
This then allows me to formally integrate the function. In particular,  I find that
$$
F(z) = 1/2 \log(z-1) - 2 \log(z-2) + 3/2 \log(z-3)
$$
is a complex differentiable function on the set $\Omega = \{z \in \mathbb{C}: |z| > 4\}$ with the derivative we want.  So this seems  to answer the question, as far as I can tell.
The question then asks if there is a complex differentiable function on $\Omega$ whose derivative is
$$
\frac{z^2}{(z-1)(z-2)(z-3)}.
$$
Again, I can write this as a sum of rational functions and formally integrate to obtain the desired function on $\Omega$ with this particular derivative. Woo hoo.
My question
Is there more to this question that I'm not seeing? I was also able to write the first given derivative as a geometric series and show that this series converged for all $|z| > 3$, but I don't believe this helps me to say anything about the complex integral of this function.  In the case that it does, perhaps this is  an alternative avenue to head down?
Any insight/confirmation that I'm not overlooking something significant would be much appreciated.  Note that this an old question  that often appears on study guides for complex analysis comps (one being my own), so that's in part why I'm thinking (hoping?) there may be something deeper here. For possible historical context, the question seems to date back to 1978 (see number 7 here): http://math.rice.edu/~idu/Sp05/cx_ucb.pdf
Thanks for your time.

A: The key seems to be that the coefficients $1/2$, $-2$ and $3/2$ sum to 0. So if you choose branch cuts for the three logarithm such that the cuts coincide through the $|z|>4$ region, then jumps at the cuts will cancel each other out (the amount each raw logarithm jumps is always $2\pi i$) and leave a single continuous function on $\{C\in\mathbb C\mid |z|>4\}$.

A: Using Morera's theorem you can prove that your function has an antiderivative on any disk $D \subset \{z \in \Bbb{C} : |z| > 4\}$.
Morera's theorem states that if $f: D \to \Bbb{C}$ is a complex continuous function such that $\int_T f(z)dz=0$ on any triangle contained in $D$, then $f$ has an antiderivative.
The idea is that for any such disk your function is holomorphic on $D$, and the integral on any closed(usually triangles or rectangles are chosen) path is zero (Cauchy's theorem). Therefore, by Morera's theorem you can find a antiderivative of $f$ on $D$.
I do not know how to prove or disprove that there exists a antiderivative on your whole domain $\{z \in \Bbb{C} : |z| > 4\}$


text:
Q: Как правильно сделать колоду из карт, хранящихся в таблице? Итак у меня есть база данных вида

Далее я получаю любую карту типа tuple из бд с помощью метода:
def get_card_by_id(id):
    cur = db_bj.cursor()
    result = cur.execute(
        f'SELECT value,card_suit,sticker_id FROM cards WHERE id="{id}"').fetchone()
    print(result)
    return result

после этого хочу создать колоду используя namedtuple
from utils.db_api.handler import get_card_by_id

Card = namedtuple('Card', ['value', 'card_suit', 'sticker_id'])
new_deck = []
for i in range(0, 14):
    id = i
    card = get_card_by_id(id)
    value = card[0]
    card_suit = card[1]
    sticker_id = card[2]
    Card = Card(value, card_suit, sticker_id)
    new_deck.append(Card)
    print(new_deck)

но упираюсь в то, что не могу понять как надо это сделать правильно, чтобы потом поместить карты в класс Deck
class Deck(object):
    new_deck = []

    def __init__(self) -> None:
        self.cards = []
        self.refresh_deck()

    def refresh_deck(self) -> int:
        self.cards = list(map(Card, self.new_deck))

    def shuffle(self) -> None:
        shuffle(self.cards)

    def draw_card(self) -> Card:
        return self.cards.pop()

A: Что-то вроде того? Без доступа к Бд сложновато
def create_deck():
    new_deck = []
    for i in range(0, 14):
        id = i
        card = get_card_by_id(id)
        value = card[0]
        card_suit = card[1]
        sticker_id = card[2]
        Card = Card(value, card_suit, sticker_id)
        new_deck.append(Card)
        print(new_deck)
    return new_deck

deck = Deck()
deck.cards.append(create_deck())


text:
Q: Joomla empty user rows I have a issue with Joomla, I have multiple joomla instalations, and a short time ago I saw something strange. I have thousands and thousands of empty users regristerd on some of my sites.
The 3 sites that I know of. And the most of them are on different hosting providers.
http://i.imgur.com/A6vt0Gi.png (all the 60 pages are filled with empty users)
http://i.imgur.com/CHKxDkI.png (the database)
I searched on the internet, and I could't find a fix or a simular person that had this problem.
Maybe you guys now this problem?
Thank you very much :)
EDIT: I just had this problem with a new site on a testdomain (a domein that was newly generated and litterly was 30 min. old.) I don't think this is by bots.
And i checked for scripts in the system using RSFirewall.

A: It's Bot. check your site by findbot(http://www.abuseat.org/findbot.pl)


text:
Q: Why am I getting this Authentication required error even though I am using my client id and client secret for the Foursquare API? I getting back into Python and wanted to use the pyfoursquare package to access the Foursquare API. I'm trying to get information about venues using the venues method in the API class. I'm primarily trying to find out whether a venue page is verified with Foursquare or not. When I provide my client id, client secret, and venue id I keep getting back an error that states "Authentication required", which doesn't makes sense because I'm providing that information. Any help would be great. Thank you.
import pyfoursquare as foursquare
client_id = ""
client_secret = ""
callback = ""
auth = foursquare.OAuthHandler(client_id, client_secret, callback)
api = foursquare.API(auth)
result = api.venues("4e011a3e62843b639cfa9449")
print result[0].name

Let me know if you would like to see the error message. Thanks again.

A: I believe you are skipping the step of grabbing your OAuth2 access token, so you're not technically authenticated.
Have a look at the following instructions, under "How to Use It":
https://github.com/marcelcaraciolo/foursquare
The lines that might be useful to you are:
#First Redirect the user who wish to authenticate to.
#It will be create the authorization url for your app
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url

#If the user accepts, it will be redirected back
#to your registered REDIRECT_URI.
#It will give you a code as
#https://YOUR_REGISTERED_REDIRECT_URI/?code=CODE
code = raw_input('The code: ').strip()

#Now your server will make a request for
#the access token. You can save this
#for future access for your app for this user
access_token = auth.get_access_token(code)
print 'Your access token is ' + access_token


text:
Q: Modify string names in a data frame based on a condition I have a data frame with a variable called "Control_Category". The variable has six names in it, which for simplicity sake I am going to make generic:
df <- data.frame(Control_Category = c("Really Long Name One",
"Super Really Long Name Two",
"Another Really Flippin' Long Name Three",
",Seriously, It's a Fourth Long Name",
"Definitely a Fifth Long Name",
"Finally, This guy is done, number six"))

I'm using this to make a slight joke. So, while the names are long they are  tidy in that the values for each (1-6) are consistent. In this specific character vector of the data.frame, there are hundreds and hundreds of entries that match any one of those six.
What I need to do is to replace the long names with a short name. Therefore, where any of the above names are identified, replace that name with a shorter version, like:
One
Two
Three
Four
Five
Six
I tried a function using 'case_when' and it failed miserably. Any help would be appreciated.
Additional Information Based on Questions From Community
The order of the items doesn't matter. There isn't a designation of 1 - 6. There just happen to be six and I made six stupid long strings. The strings themselves are long.
So, anywhere "Super Really Long Name Two" exists, that value needs to be updated to something like 'TWO" or a "Short_Name" that that approximate "TWO". In reality, the category is called "Audit, Testing and Examination Results". The short name would ideally just be "AUDIT".

A: You could just use gsub() once for each replacement:
df$Control_Category <- gsub('Really Long Name One', 'One',  df$Control_Category)

You can repeat similar logic to handle the other five long/short name pairs.

A: Here's a larger data frame with long names:
set.seed(101)
long_names <- c("Really Long Name One",
                "Super Really Long Name Two",
                "Another Really Flippin' Long Name Three",
                ",Seriously, It's a Fourth Long Name",
                "Definitely a Fifth Long Name",
                "Finally, This guy is done, number six")

df <- data.frame(control_category=sample(long_names, 100, replace=TRUE))
head(df)

##                          control_category
## 1 Another Really Flippin' Long Name Three
## 2                    Really Long Name One
## 3            Definitely a Fifth Long Name
## 4     ,Seriously, It's a Fourth Long Name
## 5              Super Really Long Name Two
## 6              Super Really Long Name Two

Using the unique function will give you the category names:
category <- unique(df$control_category)
print(category)

## [1] Another Really Flippin' Long Name Three
## [2] Really Long Name One
## [3] Definitely a Fifth Long Name
## [4] ,Seriously, It's a Fourth Long Name
## [5] Super Really Long Name Two
## [6] Finally, This guy is done, number six
## 6 Levels: ,Seriously, It's a Fourth Long Name ...

Notice that the levels are in alphabetical order (see levels(category)). In this case, the simplest way is to change the order manually by looking at the current order. In this case, category[c(2, 5, 1, 4, 3, 6)] will give you the right order. Finally,
df$control_category <- factor(
    df$control_category,
    levels=category[c(2, 5, 1, 4, 3, 6)],
    labels=c("one", "two", "three", "four", "five", "six")
)
head(df)

##   control_category
## 1            three
## 2              one
## 3             five
## 4             four
## 5              two
## 6              two


text:
Q: Thoughts on implementation of weakly typed web service Not really sure if the title is the best describing title but anyways;
I'm doing some integration against an external system which offers some wcf services with a total of more than 300 methods. Each method takes an api key parameter and a xml string parameter.
I'm looking for some nice clean design on how to approach the xml string parameters.
Some of the methods have optional xml parameters, nested parameters and list elements.
Example:
        EntityManager.PerformCommand
    <PARAMETERS>
        <COMMANDID>Commands.ReadStatus</COMMANDID>
        <ENTITYID>ID of the entity</ENTITY> (optional - for single entity)
        <ENTITIES>
            <ENTITY>
               <ID>ID of entity #1</ID>
             </ENTITY>
             <ENTITY>
               <ID>ID of entity #n</ID>
            </ENTITY>
        </ENTITIES> (optional - use for multiple entities)
        <TIMEOUTDATETIME>2014-01-01 00:00:00.000</TIMEOUTDATETIME>
    </PARAMETERS>

While a different command could use some other parameters and syntax documented by the provider of this service.
So to my actual question; what would be a nice design for this?
I'd like to create a command queue processor and result processor working between the db and the external system and have my own implementation between UI and database.
But I don't have any good ideas on how to have the dynamic build from the UI and some validation on the XML before sending it to the external system.
As for now, I'ved typed the different XML parameters into strings with String.Format where I've passed my parameters. I also tested a fluent interface where I removed unpopulated elements, but it seems kind of tedious way of achiving what I want.
(Note below code is just for testing)
public class ParameterHelper
{
    private StringBuilder parameters = new StringBuilder();

    public ParameterHelper Initialize()
    {
        parameters.Clear();
        parameters.Append("<PARAMETERS>");
        return this;
    }

    public ParameterHelper NewLevel(string levelName)
    {
        parameters.AppendFormat("<{0}>", levelName.ToUpper());
        return this;
    }
    public ParameterHelper CloseLevel(string levelName)
    {
        parameters.AppendFormat("</{0}>", levelName.ToUpper());
        return this;
    }

    public ParameterHelper WithParameter(string parameterName, object parameterValue)
    {
        parameters.AppendFormat("<{0}>{1}</{0}>", parameterName.ToUpper(), parameterValue);
        return this;
    }

    public ParameterHelper List(string parameterName, IEnumerable<string> parameterValues)
    {
        foreach (string parameterValue in parameterValues)
        {
            parameters.AppendFormat("<{0}>{1}</{0}>", parameterName.ToUpper(), parameterValue);
        }
        return this;
    }

    public ParameterHelper Object(string stringParameterFormat, params object[] args )
    {

        parameters.AppendFormat(stringParameterFormat.ToUpper(), args);

        return this;
    }

    public ParameterHelper ObjectList(string outerParameterName, string innerParameterName, IEnumerable<string> parameterValues)
    {
        foreach (string parameterValue in parameterValues)
        {
            parameters.AppendFormat("<{0}><{1}>{2}</{1}></{0}>", outerParameterName.ToUpper(), innerParameterName.ToUpper(), parameterValue);
        }
        return this;
    }

    public ParameterHelper ParameterObject(List<ParameterObject> parameterObjects )
    {
        foreach (ParameterObject po in parameterObjects)
        {
            parameters.AppendFormat(po.ParameterStringFormat.ToUpper(), po.StringParameters.ToArray());
        }

        return this;
    }

    public string GetParameters()
    {
        parameters.Append("</PARAMETERS>");
        var xDoc = XElement.Parse(parameters.ToString());
        xDoc.Descendants().Where(x => string.IsNullOrEmpty(x.Value)).Remove();
        return xDoc.ToString();
    }

}

So this is me reaching out for someone with more experince than me.
Thank you.


text:
Q: Redux store doesn't update component props I'm trying to call a API from my store to update the state of a component, here getting the price of a crypto-curency.
I use a clone of my state in return (nextState here) and the log of nextState is well fill with goods price, but my component get only the initialState.
Here the code :
My component
import React from 'react';
import { StyleSheet, Text, View, Button, ImageBackground,TouchableOpacity, Image } from 'react-native';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import { connect } from 'react-redux'

class Bitcoin extends React.Component {
   constructor(props){
     super(props);
     this.state = {
    }
    }

componentDidMount() {
    const action = { type: 'PRICES', value: this.state.cryptos}
    this.props.dispatch(action)
    console.log(this.props.cryptos)
}

componentDidUpdate() {
    console.log("Component did Update : ")
    console.log(this.props.cryptos)
}

  render() {
return (
    <View>
        <Text style={styles.title}>Bitcoin !</Text>
        <Text> {this.props.cryptos[0].price} </Text>
    </View>
)
  }
}

const styles = StyleSheet.create({
title: {
    marginTop: wp("10%")
},
});

const mapStateToProps = (state) => {
return {
    cryptos: state.Crypto.cryptos
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    dispatch: (action) => { dispatch(action) }
}
}

export default connect(mapStateToProps, mapDispatchToProps)(Bitcoin)

My Reducer :
const initialState = {  cryptos: [
                    {
                        title: "Bitcoin",
                        id: "BTC",
                        price: 0
                    }, {
                        title: "Ethereum",
                        id: "ETH",
                        price: 0
                    }, {
                        title: "Ripple",
                        id: "XRP",
                        price: 0
                    }], toast: 0}

function Crypto(state = initialState, action) {
    let nextState
    switch (action.type) {
      case 'PRICES':
        nextState = {...state}
        fetch('https://min-api.cryptocompare.com/data/pricemulti?fsyms=ETH,BTC,XRP&tsyms=EUR&api_key=c3b60840403013f86c45f2ee97571ffdf60072fafff5c133ed587d91088451b6')
        .then((response) => response.json())
        .then((responseJson) => {
            nextState.cryptos[0].price = responseJson.BTC.EUR.toString()
            nextState.cryptos[1].price = responseJson.ETH.EUR.toString()
            nextState.cryptos[2].price = responseJson.XRP.EUR.toString()
            console.log("NextState :");
            console.log(nextState.cryptos);
            return nextState
        })
        .catch((error) => {
            console.error(error);
        });
        return nextState
    case 'TOAST':
        nextState = {...state}
    default:
        return state
    }
}

export default Crypto

A: Welcome to StackOverflow.
I guess you are new to Redux workflow. So here it is.
Actions describe an action. The reducer receive the action and specify how the store is changing.
Action must be plain javascript object. And reducer functions must be pure !
Here what is forbidden to do inside reducers :
  Mutate its arguments;
  Perform side effects like API calls and routing transitions;
  Call non-pure functions, e.g. Date.now() or Math.random().

In your example, by calling fetch. You're making an API Call.
I invite you to read this guide to know more about : How to introduce API call and asynchronous into your redux app. (https://redux.js.org/advanced/async-actions)


text:
Q: How to add SqlDependency for AngularJs with Entity Framework I'm creating a database notification web application with Angular, ASP.NET MVC 5 and Entity Framework. Since I don't have much knowledge I'm referring to the following article so I'm asking if some one can help bellow tutorial with Entity Framework will be very much appreciated.
http://www.codeproject.com/Articles/806919/SignalR-with-ASP-NET-MVC

A: Actually AngularJS is used in front end. This dependency should be included on backend. To add EF to your project, just run the following command in Visual Studio:
under menu Tools -> Library Package Manager -> Package Manager Console
Install-Package EntityFramework


text:
Q: Windows hotkeys are too slow to use I use some scripts to copy some strings which I frequently use. I assigned hotkeys to them, with which I can copy those string with keyboard shortcuts.
The problem is that Windows is taking way too long to run those scripts. From another Super User question (Slow Windows Desktop Keyboard Shortcuts), I understand that Windows queries all the existing windows if they have that hotkey before executing.
In my case, those windows definitely wouldn't exist because they close as soon as they copy strings to the clipboard. How can I disable Windows checking all existing windows for hotkey matches?


text:
Q: Changing ListBoxItem's Foreground from Code Behind in WPF In WPF is there a way to change the Foreground of specific ListBoxItem from code behind?
I have this ListBox:
    <ListBox x:Name="songsListBox" Background="{DynamicResource Gray}" Foreground="{DynamicResource TextColor}" HorizontalContentAlignment="Stretch" Style="{DynamicResource musicListBox}">
            <ListBox.ItemContainerStyle>
                    <Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
                            <EventSetter Event="MouseDoubleClick" Handler="ListBoxItem_MouseDoubleClick"/>
                            <Setter Property="Template">
                                    <Setter.Value>
                                            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                                                    <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                                                            <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                                    </Border>
                                                   <ControlTemplate.Triggers>
                                                           <MultiTrigger>
                                                                   <MultiTrigger.Conditions>
                                                                           <Condition Property="IsMouseOver" Value="true"/>
                                                                   </MultiTrigger.Conditions>
                                                                   <Setter Property="Background" TargetName="Bd" Value="{DynamicResource LigthGray}"/>
                                                                   <Setter Property="BorderBrush" TargetName="Bd" Value="{DynamicResource LigthGray}"/>
                                                           </MultiTrigger>
                                                           <MultiTrigger>
                                                                   <MultiTrigger.Conditions>
                                                                           <Condition Property="Selector.IsSelectionActive" Value="False"/>
                                                                           <Condition Property="IsSelected" Value="true"/>
                                                                   </MultiTrigger.Conditions>
                                                                   <Setter Property="BorderBrush" TargetName="Bd" Value="{x:Null}"/>
                                                                   <Setter Property="Background" Value="{DynamicResource LigthGray}"/>
                                                           </MultiTrigger>
                                                           <MultiTrigger>
                                                                   <MultiTrigger.Conditions>
                                                                           <Condition Property="Selector.IsSelectionActive" Value="True"/>
                                                                           <Condition Property="IsSelected" Value="true"/>
                                                                   </MultiTrigger.Conditions>
                                                                   <Setter Property="BorderBrush" TargetName="Bd" Value="{x:Null}"/>
                                                                   <Setter Property="Background" Value="{DynamicResource LigthGray}"/>
                                                           </MultiTrigger>
                                                           <Trigger Property="IsEnabled" Value="False">
                                                                   <Setter Property="TextElement.Foreground" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                                                           </Trigger>
                                                   </ControlTemplate.Triggers>
                                           </ControlTemplate>
                                   </Setter.Value>
                           </Setter>
                   </Style>
           </ListBox.ItemContainerStyle>
           <ListBox.ItemTemplate>
                   <DataTemplate>
                           <Grid>
                                   <Grid.ColumnDefinitions>
                                           <ColumnDefinition Width="35*"/>
                                           <ColumnDefinition Width="25*"/>
                                           <ColumnDefinition Width="30*"/>
                                           <ColumnDefinition Width="60"/>
                                   </Grid.ColumnDefinitions>

                                   <TextBlock Text="{Binding Name}" Padding="4,0,4,0" Grid.Column="0"/>
                                   <TextBlock Text="{Binding Artist}" Padding="4,0,4,0" Grid.Column="1"/>
                                   <TextBlock Text="{Binding Album}" Padding="4,0,4,0" Grid.Column="2"/>
                                   <TextBlock Text="{Binding Year}" Padding="4,0,4,0" Grid.Column="3"/>
                           </Grid>
                   </DataTemplate>
           </ListBox.ItemTemplate>
   </ListBox>

This ListBox is for showing a music library. I also have the same ListBox for a Queue.
I want to change foreground of ListBoxItem, when the song is playing in both ListBoxes. Is there any way to do it?
I don't want to have it using SelectedItem, because I would like to have a different color for the playing song than of the SelectedItem.

A: Assuming that the data model has a property IsPlaying, you could use the following DataTrigger to toggle the item container's foreground:
<ListView>
  <ListView.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
      <Setter Property="Foreground" Value="Black" />

      <Style.Triggers>
        <DataTrigger Binding="{Binding IsPlaying}" Value="True">
          <Setter Property="Foreground" Value="Red" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </ListView.ItemContainerStyle>
</ListView>


text:
Q: Prevent DOS attack with multithreaded code Let me give an overview of my question here:
There are ~ 4000 servers and millions of URLs per server. My code needs to hit each URL and write the response code to HDFS filesystem along with the URL.
Added some part here too :
Check the number of requests sent to a webpage
I am using a producer-consumer model here with 400 threads.  The code has caused a DOS attack to few web servers very recently, I am having a hard time figuring out where the issue here is :
Main class:
public void readURLS(final Path inputPath, final Path outputPath) {
    LOG.info("Looking for files to download, queue size: {}, DOWNLOAD_THREADS: {}", queueSize, producerThreads);
    final List<Path> files = HdfsUtils.listDirectory(inputPath, hadoopConf);
    final BlockingQueue<String> queue = new LinkedBlockingQueue<>(queueSize);
    final UrlConsumerWriter consumerWriter =
            new UrlConsumerWriter(queue, outputPath, hadoopConf);

    LOG.info("Starting download of {} files from: '{}'", files.size(), inputPath);
    final ExecutorService writerPool = DownloadUtils.createWriterPool();
    CompletableFuture<Void> producer = downloadFilesToQueue(files, queue)
            .thenRun(consumerWriter::notifyProducersDone);
    CompletableFuture<Void> consumer =
            CompletableFuture.runAsync(consumerWriter, writerPool)// Cancel download workers if write worker fails
                    .whenComplete((result, err) -> {
                        if (err != null) {
                            LOG.error("Consumer Write worker failed!", err);
                            producer.cancel(true);
                        }
                    });

    writerPool.shutdown();
    producer.join();
    consumer.join();
    LOG.info("Url Validation Job Complete!!!");
}

private CompletableFuture<Void> downloadFilesToQueue(
        final List<Path> files,
        final BlockingQueue<String> downloadQueue
) {
    final ExecutorService pool = DownloadUtils.createDownloadPool(producerThreads);

    final List<CompletableFuture<Void>> workers = files.stream()
            .map(file -> new UrlDownloadWorker(clock, file, hadoopConf, downloadQueue,
                    utils, (validatorImpl.emptyTable())))
            .map(worker -> CompletableFuture.runAsync(worker, pool))
            .collect(Collectors.toList());

    pool.shutdown();

    final CompletableFuture<Void> allDownloads = CompletableFuture.allOf(workers.toArray(new CompletableFuture[0]));

    // When one worker fails, cancel all the other immediately
    for (final CompletableFuture<Void> worker : workers) {
        worker.whenComplete((v, err) -> {
            if (err != null) {
                LOG.error("Download worker failed!", err);
                allDownloads.cancel(true);
            }
        });
    }

    return allDownloads;
}

PRODUCER CLASS:
@Override
    public void run() {
        LOG.info("Starting download worker for file: '{}'", file);
        long numLines = 0;

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                file.getFileSystem(hadoopConf).open(file), CHARSET))) {
            String line;
            while ((line = reader.readLine()) != null) {
               // LOG.info("Thread {} Reading file: '{}'",Thread.currentThread().getName(), file);

                if (Thread.interrupted()) {
                    throw new InterruptedException();
                }
                StringBuilder builder = new StringBuilder();

                //write into database
                final StatusCode statusCode = utils.validateURL(line);

                if (statusCode != null) {
                        queue.put(builder.append(line)
                                .append(",")
                                .append(statusCode.name()).toString());

                    builder.setLength(0);
                } else {
                    throw new UrlValidationException(
                            "Failed to validate url :'" + line + "'");
                }
                numLines++;
            }

        } catch (IOException e) {
            throw new DownloadException(file, e);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new DownloadException("Interrupted while downloading", file, e);
        }
        LOG.info("Download of {} lines complete for file: '{}'", numLines, file);
    }

UrlValidationUtils CLASS:
public final class UrlValidationUtils {
    private static final String WEBSITENOTCHECK = "uncheck.org";
    private final Map<String, StatusCode> blockedHosts = new ConcurrentHashMap<>();
    private static final int MAX_REDIRECT = 4;

    public StatusCode validateURL(String url) throws IOException {
        return validate(url, MAX_REDIRECT);
    }

    private StatusCode validate(String url, int maxRedirect) throws IOException {
        URL urlValue = new URL(url);
        HttpURLConnection con;

        if (url.contains(WEBSITENOTCHECK)) {
            blockedHosts.put(urlValue.getHost(), StatusCode.SUCCESS);
        }
        //first check if the host is already marked as invalid
//        if (blockedHosts.containsKey(urlValue.getHost())) {
//            return blockedHosts.get(urlValue.getHost());
//        }
        StatusCode statusCode;
        con = (HttpURLConnection) urlValue.openConnection();

        try {
            int resCode;
            con.setInstanceFollowRedirects(false);
            con.setConnectTimeout(3000); //set timeout to 3 seconds
            con.connect();
            resCode = con.getResponseCode();

            LOG.info("thread name {} connection id {} url {} ", Thread.currentThread().getName(), con.toString(), url);
            if (resCode == HttpURLConnection.HTTP_OK) {
                statusCode = StatusCode.SUCCESS;
            } else if (resCode == HttpURLConnection.HTTP_SEE_OTHER || resCode == HttpURLConnection.HTTP_MOVED_PERM
                    || resCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                String location = con.getHeaderField("Location");
                if (location.startsWith("/")) {
                    location = urlValue.getProtocol() + "://" + urlValue.getHost() + location;
                }
                statusCode = validateRedirect(location, maxRedirect - 1, con);

            } else {
                blockedHosts.put(urlValue.getHost(), StatusCode.FAIL);
                statusCode = StatusCode.FAIL;
            }
        } catch (UnknownHostException e) {
            blockedHosts.put(urlValue.getHost(), StatusCode.UNKOWNHOST);
            statusCode = StatusCode.UNKOWNHOST;
        } catch (ConnectException e) {
            blockedHosts.put(urlValue.getHost(), StatusCode.CONNECTION_ISSUE);
            statusCode = StatusCode.CONNECTION_ISSUE;
        } catch (IOException e) {
            //if an IOException is caught possible reason is SOCKETTIMEOUT
            blockedHosts.put(urlValue.getHost(), StatusCode.SOCKETTIMEOUT);
            statusCode = StatusCode.SOCKETTIMEOUT;
        }
        con.disconnect();
        LOG.info("thread name {} connection id {} url {} ", Thread.currentThread().getName(), con.toString(), url);

        return statusCode;
    }

    private StatusCode validateRedirect(String location, int redirectCount, HttpURLConnection connection)
            throws IOException {
        if (redirectCount >= 0) {
            connection.disconnect();
            return validate(location, redirectCount);
        }
        return StatusCode.FAIL;

    }

}

A: In order to not overload the servers, I suggest waiting a few milliseconds before hitting a batch of urls. For example, after hitting N urls, you could wait 20 ms, then hit the next N.. and so on. The size of the batch (N) would depend on how many requests you know your server can handle in a second. Do you have a Service Level Agreement for them in terms of performance?


text:
Q: Prove that in these conditions, $f(x)Let $f,g:[0,1]\longrightarrow\mathbb{R}$ be two continuous and differentiable functions in $[0,1]$ such that:
$$f(0)=0$$
$$g(0)=2$$
$$|f'(x)|,|g'(x)|\leq1:\forall x,y\in[0,1]$$
Then prove that $f(x)<g(x):\forall x\in[0,1)$ and $f(1)\leq g(1)$
I can see the geometric interpretation of this to be pretty straightforward, since we know that $g'(x)\geq-1$ and $f'(x)\leq1$, and they are two units apart at the start point, even considering the most extreme case they would only intersect in $x=1$.
However I'm trying to find an analytical proof for this. I have considered
$$h(x):=g(x)-f(x)$$
And trying to prove $h(x)\geq0:\forall x\in[0,1)$, but I can't quite get it. I have also thought that maybe Lagrange's theorem could be useful as the function is continuous and differentiable, but I'm not sure how to apply it to $h(x)$.

A: Note that $h(0) = 2 > 0$. Suppose that $h(c) = 0$ for some $c \in [0, 1)$. By the mean value theorem, we could then find a point $\alpha$ between $0$ and $c$ for which
$$h'(\alpha) = \frac{h(0) - h(c)}{0 - c} = \frac{2}{c} > 2$$
since $c < 1$. Do you see how this leads to a contradiction? Can you finish the proof from here?


text:
Q: Suppress "Frequency" text in PROC FREQ How can I get rid of the box inside the red circle

code:
data mydata;
input x y;
datalines;
    1 2
    3 4
    1 5
    3 2
;
run;

proc freq data=mydata;
    tables x*y /nopercent norow nocol;
run;

A: data mydata;
input x y;
datalines;
    1 2
    3 4
    1 5
    3 2
;
run;

/*Write new template to work folder */
ods path work.templat(update) sashelp.tmplmst(read);

/*Remove the "Frequency" header from the template */
proc template;
  edit Base.Freq.CrossTabFreqs;
    edit frequency;
      header="";
    end;
  end;
run;

proc freq data=mydata;
    tables x*y /nopercent norow nocol;
run;

A: As always with SAS there are multiple paths to the desirred result.
If you are willing to step away from proc freq you can achieve the required output using proc tabulate. This provides a simpler (and more concise) solution and does not require digging through the long and often confusing proc template documents.
proc tabulate data = mydata;
    /* Specify the variables to investigate */
    class x y;
    table
        /* Put x in the rows suppress its title and add a total row */
        x = "" all = "Total",
        /* Put y in the columns, request a total, request frequency count*/
        (y all = "Total") * n = "" /
            /* Put "x" in the top left box */
            box = "x"
            /* Put 0 instead of missing */
            misstext = "0";
run;

A: The only way I know how to do this is to edit the PROC FREQ template.  Since 9.3 or so, PROC FREQ has been rewritten as a basic table via PROC TEMPLATE, which is nice because it lets us edit nearly all aspects of it.
What I do is right click on the Results tree header in display manager - like so:

Then select "Templates".  This opens up the template list, which includes all templates you have installed (both style templates and table templates - most of the PROCs have a table template, though msot do not give you as much control as PROC FREQ does).
Then navigate to Sashelp.Tmplmst (Which is the major template store for most preinstalled templates), and open up Base, and then Freq.  This gives you a list of table templates that make up PROC FREQ.
In your case, you want to open CrossTabFreqs, which is what you're producing (A crosstab).  You could identify this by running ods trace on; then running your code; it will tell you in the log what the name of the template it's using is.
Open that and copy the contents of the template browser to the clipboard, then paste in a new window.  We will modify it, save it in a temporary location, and use it.
Add to the top of the program this line:
ods path work.templat(update) sashelp.tmplmst(read);

This tells SAS two things: first, when we update or write to the template store, do that in work; and two, to look in work first then in sashelp for templates.  This way when we create our new CrossTabFreqs template, it will come from work.
Now, look in the program for the location where it defines the Frequency block.  This is what you want to modify, since this is the instructions for SAS telling it what to print when it is showing frequencies (as opposed to percents or whatnot).  It will read as so:
  define Frequency;
     header = "Frequency";
     format = BEST7.;
     label = "Frequency Count";
     print;
     data_format_override;
  end;

You want to remove the header.  You can do that one of two ways: either remove the header line entirely, or my preferred option, change it to
  define Frequency;
     header = " ";
     format = BEST7.;
     label = "Frequency Count";
     print;
     data_format_override;
  end;

Then run the entire program (including the ods path statement).  Now, when you use PROC FREQ in this SAS session, it will have no text in the frequency table header.


text:
Q: How to show different language in matplotlib barchart? I'm trying to show a Barchart which will show the frequency of each character in Bangla Language in a particular text. But it shows empty box in horizontal positions.
def GTStat():
    charFreq = {'ক': 30041, 'খ': 22981, 'র': 20806, 'ট': 19265, 'প': 16943, 'ন': 15478, 'ত': 13840}
    plt.bar(range(len(charFreq)), list(charFreq.values()), align='center')
    plt.xticks(range(len(charFreq)), list(charFreq.keys()))
    plt.show()

But it shows empty box instead of characters

A: You can specify a font that supports your language like this:
def GTStat():
    charFreq = {'ক': 30041, 'খ': 22981, 'র': 20806, 'ট': 19265, 'প': 16943, 'ন': 15478, 'ত': 13840}
    plt.bar(range(len(charFreq)), list(charFreq.values()), align='center')
    plt.xticks(range(len(charFreq)), list(charFreq.keys()), name="Nikosh")
    plt.show()

Where you should place a font family name instead of Nikosh in code above.
If you are getting findfont: FontFamily not found you can follow instructions in this stackoverflow answer


text:
Q: "glm\glm.hpp: No such file or directory" error on linux Running this command:
g++ /workspace/2016FallCSE2022/Week15/glfw_examples/CarDriving2D/main.cpp -lGL -lglut -lGLEW -I/path/to/glm/headers

Results in this error:
In file included from /workspace/2016FallCSE2022/Week15/glfw_examples/CarDriving2D/GLSquare.h:9,
                 from /workspace/2016FallCSE2022/Week15/glfw_examples/CarDriving2D/CarDrivingGame.h:10,
                 from /workspace/2016FallCSE2022/Week15/glfw_examples/CarDriving2D/main.cpp:19:
/workspace/2016FallCSE2022/Week15/glfw_examples/CarDriving2D/Box2D.h:9:9: fatal error: glm\glm.hpp: No such file or directory
    9 | #include<glm\glm.hpp>
      |         ^~~~~~~~~~~~~
compilation terminated.

What is the error and how do I fix it?


text:
Q: Custom List of contacts - First Letter Icon colors reference I have a custom list of contacts on my app (from custom SqlLite table). I want to follow the Android's looks like, and show the contact icon like Android do when the standard Contact has not a picture (shows the first letter in a box with a background color).
I can see that Android have a different background color depending of the letter, im right?

Is there any color reference table for those letters? or maybe a programmatically why to get this color?
Thanks in advance!


text:
Q: Entity Framework Core Randomly Getting 'The connection was not closed. The connection's current state is open.' Creating my first full on project with ASP.Net Core and of course using all of the new xxx Core libraries like Entity Framework Core.  Things are going well and I like the Dependency Injection in most areas.  My issue is that I am inconsistently getting the error:

The connection was not closed. The connection's current state is open.

PayPeriod = await (from e in context.Employees
                   join s in context.PayPeriodStyles on e.PayPeriodStyleID equals s.ID
                   join p in context.PayPeriods on s.ID equals p.PayPeriodTypeID
                   where e.ID == employeeID
                   select p)
                   .AsNoTracking()
                   .FirstOrDefaultAsync();

My code is simple-ish and should not be a problem.  It does not always happen on say the 4th or 6th click but eventually it will happen.  I am trying to find a way around it.  I suppose I could catch it and pass back some failed flag so it will try it again, but that seems kludgey.
While researching this error, it seems everything points to using a using statement.  However, while learning ASP.Net Core, from here, they do not use any using statement so why should I.  It seems thanks to DI, that is no longer necessary I guess.
For further insight into the application, my client side is using KnockoutJS.  When the user clicks a calendar day, a method gets called to fill in all of the data of the calendar.  A portion of which is the PayPeriod they currently selected.
So everyone can see the entire process, here are the different code pieces.  I do not think it is anything other than the above.  But I am here asking for help so I want to give everything up front.
Client Side - Knockout - Starts the process off
self.BuildAndFillCalendar = function (isInitialCall) {
  $.ajax({
    type: "GET",
    url: "/api/v1/ProjectTime/BuildAndFillCalendar",
    contentType: "application/json; charset=utf-8",
    cache: false,
    data: { "givenDate": moment(self.Date()).format("MM-DD-YYYY"), "employeeID": self.EmployeeID }
  }).done(function (result) {
    self.Calendar(new ACalendarModel(result));
  }).fail(function (jqXHR, textStatus, errorThrown) {
    alert("BuildCalendar Error: " + errorThrown);
  });
};

The MVC Controller catching the above GET request
[HttpGet]
[Route("BuildAndFillCalendar")]
public async Task<IActionResult> BuildAndFillCalendarAsync(DateTime givenDate, int employeeID) {
  ACalendar Result = await Repo.BuildAndFillCalendarAsync(givenDate, employeeID);

  return Ok(Result);
}

The actual logic to make the database calls and put things together
public async Task<ACalendar> BuildAndFillCalendarAsync(DateTime givenDate, int employeeID) {
  ACalendar Result = null;

  try {
    // Build the Month for the given date
    await Task.Run(() => {
      Result = new ACalendar(givenDate);
    });

    // Gather the Employees specific Pay Period for the given date
    AlmanacResponse<PayPeriodWindow> CalendarWindow = await GetEmployeePayPeriodWindowAsync(givenDate, employeeID);

    Result.PayPeriod = CalendarWindow.Result;

    // Gather the Employees ProjectTime records for the given visible Month
    var Times = await context.ProjectTimes
      .Include(x => x.Project)
      .Where(x => x.EmployeeID == employeeID && x.Date >= CalendarWindow.Result.FirstDayOnCalendar && x.Date <= CalendarWindow.Result.LastDayOnCalendar)
      .AsNoTracking()
      .ToListAsync();

    // Add the ProjectTime entries to the Calendar
    foreach (var t in Times)
      Result.AddProjectTime(t);
  } catch (Exception e) {
    logger.LogError(1, e, "Unable to build the Employees Project Time Calendar");
  }

  return Result;
}

The sub-call from the previous code set where the error occurs (also first code shown in this question)
public async Task<AlmanacResponse<PayPeriodWindow>> GetEmployeePayPeriodWindowAsync(DateTime givenDate, int employeeID) {
  var Result = new AlmanacResponse<PayPeriodWindow>();

  try {
    PayPeriod PayPeriod = await (from e in context.Employees
                                 join s in context.PayPeriodStyles on e.PayPeriodStyleID equals s.ID
                                 join p in context.PayPeriods on s.ID equals p.PayPeriodTypeID
                                 where e.ID == employeeID
                                 select p)
                                 .AsNoTracking()
                                 .FirstOrDefaultAsync();

    Result.Result = await GetPayPeriodWindow(PayPeriod, givenDate);
    Result.WasSuccessful = true;
  } catch (Exception e) {
    Result.AddMessage(e, nameof(GetEmployeePayPeriodWindowAsync));
    logger.LogError(1, e, "Unable to gather Employees Pay Period Window");
  }

  return Result;
}

The PayPeriod Object
public class PayPeriod : AuditableBase {

  public bool IsActive { get; set; }

  public PayPeriodStyle PayPeriodType { get; set; }
  public int PayPeriodTypeID { get; set; }

  public DateTime FirstDate { get; set; }
  public DateTime? SecondDate { get; set; }

  public decimal WorkDayHours { get; set; }
}

So, are there certain situations where I should use a using statement?  If so, point me to the docs for that.
Is it something to do with my EF configuration?
Is it because the call is originating from AJAX?


text:
Q: trouble in understanding outliers' influence on K-means
When outliers are present, the resulting cluster centroids may not be as representative as they otherwise would be and thus, the SSE will be higher as well.

However, I don't understand this sentence.
Look at the following picture. The original centroid is marked as "A" and the outlier is marked as red. It is clear that the original centroid "A" is better than the outlier when considering SSE. Thank you !

A: Imagine we have a dataset containing 2 clusters that are nice, Gaussian point clouds. We want to find 2 clusters in the data using K-means. However, say there's also a single outlier, located very far from either of the 'true' clusters. Maybe millions of times further away from any other point than any other points are to each other. If we chose the centroids to be the centers of the true clusters (the best 'representative' configuration), the value of the loss function would be very high. The loss function is the sum of squared distances from each point to its assigned cluster centroid. It would be high because the outlier is so far from the nearest centroid. Therefore, K-means would reduce the loss function by choosing the outlier itself to be one of centroids, and placing the other centroid somewhere in the middle of the remaining data. This configuration is clearly not representative of the the underlying distribution, but a pathological situation caused by the presence of a single outlier.

A: Here is a new paper on this topic:
http://www.math.uconn.edu/~gan/ggpaper/gan2017kmor.pdf
I think this is very relevant for people who might like to use a proper outlier treatment.


text:
Q: why does async inside computed make infinity loops (vue)? My computed of component like this :
export default {
  computed: {
    dataDoctorPerPage: async function () {
        const start = this.pagination.page * this.pagination.rowsPerPage - this.pagination.rowsPerPage;
        const end = start + this.pagination.rowsPerPage - 1;
        const doctors = this.dataDoctor
        const newDoctors = {}
        let key = 0
        for(let item in doctors) {
            if(key >= start && key <= end) {
                for (let i = 0; i < doctors[item].length; i++) {
                    const params = {
                        hospitalId: doctors[item][i].hospital_id,
                        doctorId: doctors[item][i].doctor_id,
                    }
                    await this.getDataSchedule(params) /* call async */
                    // console.log(this.dataSchedule)
                }
                newDoctors[item] = doctors[item]
            }
            key++
        }
        return newDoctors
    }
  }
}

If the dataDoctorPerPage called it will run the script
await this.getDataSchedule(params) will call async/api by vuex store. My problem is there. when I call await this.getDataSchedule(params), it will loop without stopping
My vuex store like this :
const actions = {
  async getDataSchedule ({ commit }, payload) {
    const result = await api.getDataSchedule(payload)
    const items = result.data
    commit('setDataSchedule', { items: items })
  },
}

How can I solve this problem?
Whether there can not run async in computed?

A: Computed should not use async. If you want to do that, you need another library for it. https://alligator.io/vuejs/async-computed-properties/
But what you want to do is use an asynchronous method (in the component or store) and set the data somewhere (in the component's data or store's state), then have your computed value reference that.


text: Q: Is there any advantage in K-Fold over leave-one-subject-out cross validation? I experienced in a predictive model for a dataset I have from experiments on human subjects, that the error of the prediction in 10-fold cross validation is less than leave-one-subject-out (leave-one-person-out). I think leave-one-person out has advantage over the K-Fold CV since it takes intra-individual variability into account and thus has higher generalization power than K-Fold. However I am not sure if I am missing any advantage of K-Fold over leave-one-subject-out.


text:
Q: Dozer exclude nested field Is it possible to exclude a child of a field? e.g. A field "item" contains another "subItem". How can I exlude the "subItem" being mapped?
<mapping>
    <class-a>test.ClassA</class-a>
    <class-b>test.ClassB</class-b>
    <field-exclude>
        item.subItem
        item.subItem
    </field-exclude>
</mapping>

Thanks for any sugestions.

A: Unfortunately no, but there is a trick. You can define contextual mapping for your Item class:
<mapping>
    <class-a>test.ClassA</class-a>
    <class-b>test.ClassB</class-b>
    <field map-id="itemExcludeSubitem">
        item
        item
    </field>
</mapping>
<mapping map-id="itemExcludeSubitem">
    <class-a>test.ItemA</class-a>
    <class-b>test.ItemB</class-b>
    <field-exclude>
        subItem
        subItem
    </field-exclude>
</mapping>


text:
Q: User Input to set dynamic variable Python I made a simple random.choice code by myself. But there is a major problem with it. I can't take user input to dynamically set variables.
import pygame
import pygame_menu
import random

kolay_secim = ["agac","odun","baba"]
orta_secim = ["zar","okey","tavla"]
zor_secim = ["emekli","yasli","deli"]
zorluk_secimi=input('Hangi zorlukta oynamak istiyorsunuz? (kolay,orta,zor)')
if zorluk_secimi == kolay :
    print(random.choice(kolay_secim))

elif zorluk_secimi  == orta :
    print(random.choice(orta_secim))

elif zorluk_secimi == zor :
    print(random.choice(zor_secim))

else:
    print("Gecersiz Zorluk Secimi yazima dikkat ediniz.")

What I'm trying to achieve is taking a user input and setting that as zorluk_secimi and after that if it matches to a category it will pick a random word from that category.

A: Try changing:
  zorluk_secimi == kolay
  zorluk_secimi  == orta
  zorluk_secimi == zor

respectively to:
  zorluk_secimi == 'kolay'
  zorluk_secimi  == 'orta'
  zorluk_secimi == 'zor'


text:
Q: Grab value of tail of file in bash script and store as variable I can't work out what I'm doing wrong. What I actually want to do, is run this command in my bash script, and grab the value back:
tail -1 com-html.log | grep 'Min: ,'

This works when manually running:
tail -1 com-html.log | grep 'Min: ,'
Min: , MAX:

Yet I can't get it to work in a bash script: (I've simplified it, in case the pipe bit was an issue)
#!/bin/bash

test = $(tail -1 com-html.log)

echo "test: $test";

What am I doing wrong? Bash is pretty new to me - so please be gentle =)
As per the suggestions below - I've even tried:
    test=$(tail -1 com-html.log | grep 'Min: ,');
    echo "test: $test"

    if [ -z "$test"]
    then
        echo "hmmm test is empty"
    fi

But it always just shows:
hmmm test is empty

I must be missing something silly
I've tried a few methods:
    test=$(tail -1 com-html.log | grep 'Min: ,')
    echo "test: $test";

    test=$(tail com-html.log | grep 'Min: ,')
    echo "test: $test";

and even the simplest just to see if I get any value:
    test=$(tail -1 com-html.log)
    echo "test: $test";

All of them have $test as empty
UPDATE: OMG this is why you shouldn't do too much coding for one day. You miss silly stuff! So this script is keeping an eye on load for the server, and also RAM. If it detects either are too high, it'll kill the script and wait for it to go back down before restarting. So I have stuff like:
    if [ -n "$(ps -ef | grep -v grep | grep 'get-html-all-domains.cgi')" ];
    then : ;
    else
        echo "nohup perl get-html-all-domains.cgi $tld new $forks $per_page > com-html.log"
        nohup perl get-html-all-domains.cgi $tld new $forks $per_page > com-html.log &  # restart it...
    fi

Now that works - but when it triggers, the output into com-html.log isn't instantaneous (as it has to get the value from the DB and then decide there is nothing to run). So to get around it, I changed the line:
nohup perl get-html-all-domains.cgi $tld new $forks $per_page > com-html.log &

to:
nohup perl get-html-all-domains.cgi $tld new $forks $per_page >> com-html.log &

(notice >> instead of just > now, so it's appending and not overwriting it completely)
Then this at the end to check if the last line is what we are looking for:
    if [ -n "$(tail -2 com-html.log | grep 'Min: ,')" ]
    then
        echo "2: Seems to be at end... lets stop :)"
        echo -ne '\007'
        exit 0

    fi

A: tail -1 only shows the last line of com-html.log.
So if the grep string (Min: ,) isn't on the last line, test will be empty.
Last line to variable
test=$(tail -1 com-html.log)
echo "test: $test";

Any line that contains Min: ,
test=$(grep 'Min: ,' < test.log)
echo "test: $test";

Last line; if containing Min: , Try it online!
test=$(tail -1 com-html.log | grep 'Min: ,')
echo "test: $test";


text:
Q: I am trying to implement a onTap() fucntion in PopUpMenu but I am unable to do so
*

*When one of the item from the PopMenuItem I want it to perform some particular task.

*I tried implement but it is not doing anything I tried implementing the onTap() function but it was giving me error as constant required.

*This is the code

import 'package:flutter/material.dart';
import 'package:ssrpa/ui/forgot_password.dart';
import 'package:ssrpa/admin/admin_page2.dart';

class PopUpMenu extends StatelessWidget {
  VoidCallback onEnable;
  VoidCallback onDisable;
  VoidCallback onDelete;

  PopUpMenu({this.onEnable, this.onDisable, this.onDelete});

  void showMenuSelection(String value) {
    switch (value) {
      case 'Enable':
        onEnable();
        break;
      case 'Disable':
        onDisable();
        break;
      case 'Delete':
        onDelete();
        break;
    // Other cases for other menu options
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      padding: EdgeInsets.zero,
      icon: Icon(Icons.more_vert),
      onSelected: showMenuSelection,
      itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
        const PopupMenuItem<String>(
            value: 'Enable User',
            child: ListTile(
                title: Text('Enable User'))),
        const PopupMenuItem<String>(
            value: 'Disable User',
            child: ListTile(
                title: Text('Disable User'))),
        const PopupMenuItem<String>(
            value: 'Delete User',
            child: ListTile(
                title: Text('Delete User')))

      ]
    );
  }
}

*

*Can I call the function that is defined in other program when one of the menu is selected from the PopMenuItem.

*The screenshot is shown below.

A: the value strings you send in popup menu item is not match with your switch cases
import 'package:flutter/material.dart';
import 'package:ssrpa/ui/forgot_password.dart';
import 'package:ssrpa/admin/admin_page2.dart';

class PopUpMenu extends StatelessWidget {
  VoidCallback onEnable;
  VoidCallback onDisable;
  VoidCallback onDelete;

  PopUpMenu({this.onEnable, this.onDisable, this.onDelete});

  void showMenuSelection(String value) {
    switch (value) {
      case 'Enable User':
        onEnable();
        break;
      case 'Disable User':
        onDisable();
        break;
      case 'Delete User':
        onDelete();
        break;
    // Other cases for other menu options
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      padding: EdgeInsets.zero,
      icon: Icon(Icons.more_vert),
      onSelected: showMenuSelection,
      itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
        const PopupMenuItem<String>(
            value: 'Enable User',
            child: ListTile(
                title: Text('Enable User'))),
        const PopupMenuItem<String>(
            value: 'Disable User',
            child: ListTile(
                title: Text('Disable User'))),
        const PopupMenuItem<String>(
            value: 'Delete User',
            child: ListTile(
                title: Text('Delete User')))

      ]
    );
  }
}


text:
Q: Is it possible to run a background thread when my app was closed I want some operations to be performed in background when my app was closed. is it possible in ios

A: Short answer; YES it is possible to have an application running in the background.
If you close the application by pressing the home button, the application is "freezed" unless you specify it should run in the background. But there are some limitations, see my explanation below.
If you kill the application, it is not possible for it to run in the background. No application will survive when you kill it. Killing is done like this; double-click the home button and then long press the application. Finally you press the application. This will kill the application.
The biggest limitation is that your application needs to be of certain type, otherwise it is not allowed to execute in the background. This is specified in the Info.plist file. Specifically you need to add the UIBackgroundModes in the Info.plist file. If it another type of application and try to run in the background, the application will be rejected for publishing in Appstore.
These are the types of applications that are allowed to execute in the background:

*

*Audio applications

*Location applications

*VoIP applications

*Newsstands applications

*Applications that polls external accessories

Then there are certain rules that the application needs to follow certain rules. Everything is explained here.


text:
Q: oracle join string to number not working by adding regexp_like oracle join string to number not working by adding regexp_like. For example,
Foo                           Bar
--------------                ------------
id varchar2(20)               id number(20,0)

Foo id can be number or any string (not number), e.g., 123, hello, world, 555, etc.
select foo.id,bar.id from Foo foo
left join Bar bar on (regexp_like(foo.id, '^[0-9]+$') and foo.id=bar.id)

error:
ERROR at line 1:
ORA-01722: invalid number

foo.id=bar.id is evaluated only when foo.id is a number, right?
The following is working fine for mysql
select foo.id,bar.id from Foo foo
left join Bar bar on (foo.id=bar.id)

But it causes the ORA-01722: invalid number for oracle. That is why "regexp_like" is added in join condition.

A: Something like this:
select foo.id
       , bar.id
from Foo foo
left join Bar bar on foo.id = to_char(bar.id);

Here is the DEMO

A: Requires Oracle 12.2 or later:
select foo.id,bar.id
from   foo
       left join bar on bar.id = to_number(foo.id default 0 on conversion error);

(I expected it to work with default null on conversion error but it crashes the session.)
Regarding your question about why the original attempt using regexp_like doesn't work, it worked for me in 12.2.0.1. Probably in your case it was evaluating foo.id = bar.id first. It may be possible to hint or rewrite the query to force the regex to be applied first.


text:
Q: Bar button item background color Can I change the background color, NOT tint, of the bottom bar button?
I have 3 buttons in the bottom bar and I want make orange color whole the middle button with the white image on it(1/3 of the bottom bar).
Here is a screenshot:

How can I do it? Everywhere in Google about tint, but I do not want tint, I want to change background

A: Look at the reference. You are right, there isn't any backgroundColor related methods.
But the trick is you can use the setBackgroundImage(_:forState:barMetrics:) method with a plain orange image.


text:
Q: How to add hours and minutes to a time in string form? How can we add time interval to a time in string form.
$time = '10 : 00 : AM'; //initial time
$interval = '01 : 30'; //interval to be added

$newtime = $time + $interval;//how to do this

echo $newtime; //required: 11 : 30 : AM

A: The odd layouts of the text times make this a little fiddly but this will work
<?php
$in = '10 : 00 : AM';
$interval = '01 : 30';

$dt = DateTime::createFromFormat('H : i : A', $in);

$interval = str_replace([' ',':'],['','H'], $interval);
$interval = 'PT'. $interval . 'M';

$dt->add(new DateInterval($interval));

echo $dt->format('H:i:s') . PHP_EOL;


text:
Q: Modifying href using jQuery generating inconsistent results When leveraging jQuery to modify the href for a given link - using 'prop' or 'attr' - the call succeeds.  I can see the link change in developer tools, if I right click on the link and select "Open link in new tab" it works flawlessly.
BUT
If I attempt to simply click on the link, in the same tab, it, for whatever reason, keeps sending me to the old (non-modified) link as if it's cached on the browser or something.  This occurs in Firefox and Chrome.
Anyone seen this before?