text:
Q: Starting Glassfish without Sudo I am currently having a problem starting Glassfish inside Eclipse on OS X. It just hangs whilst trying to start the domain.
I think the problem may lie with the permissions of Glassfish - When I use the 'start-domain domain1' command even in terminal, I must use 'sudo' otherwise I get a 'permissions denied' error. If I use 'sudo', then the server starts successfully from terminal.
I think this error may be carrying over into Eclipse - that is, the server is trying to start but is timing out because Eclipse is not starting the server with the correct permissions etc.
Is there any way to start the server via Eclipse by giving it root permissions? Or another solution, is there any way to change the Glassfish permissions so that it can be started without the 'sudo' command?
Thanks.

A: You should have installed the glassfish directory in your home folder (it's usually /home/user/ on linux - I haven't used OS X, but I think it's the same). Re-install glassfish and make sure you place it in your home path (it's the recommended path anyway). Then reconfigure eclipse with the path of the new install.
--
Hope it helps


text:
Q: Weakly null sequence in Schreier space Define the Schreier space $X:=\overline{c_{00}}^{\Vert\cdot\Vert}$ where $$\Vert x\Vert = \sup\bigg\{\sum_{i=1}^k|x_{n_i}|:k\le n_1<n_2\cdots <n_k\bigg\}.$$
Show that there exists a weakly null sequence $(x_n)\in X$ such that for any subsequence $(x_{n_m})$, the Cesaro sum $\frac{1}{m}\sum_{i=1}^m x_{n_i}\not\rightarrow 0$ as $m\rightarrow\infty$.
I know that $x_n\rightharpoonup 0$ iff $x_n^{(k)}\rightarrow 0$ as $n\rightarrow \infty $ since $c_{00}$ is dense in $X$. I've tried many different sequences with componentwise decay e.g. shifts of $(1,\frac{1}{2},\frac{1}{2},\frac{1}{2},\frac{1}{4},\frac{1}{4},\frac{1}{4},\frac{1}{4},\cdots)$ but none of them seem to work. Does anyone have an example?

A: Let $(e_n)$ be the standard sequence of Schauder basis elements. I.e $e_n(j)=\delta_n^j$, with $\delta$ the Kronecker-Delta function. Clearly this is a weakly null sequence, as pointwise it tends to $0$. Choose any subsequence $(e_{n_k})$. If we let $\lfloor x\rfloor$ denote the floor of any real number, then for any natural $m>1$ we know that
$$\|\frac{1}{m}\sum_{k=1}^me_{n_k}\|\geq\frac{1}{m}\sum_{j=1}^{\lfloor m/2\rfloor}|e_{n_{j+\lfloor m/2\rfloor}}(n_{j+\lfloor m/2\rfloor})|\geq 1/3,$$
which means that the Caesaro sums of $e_{n_k}$ cannot converge to $0$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make first_name and last_name required fields in user profile? I have a plugin and want to add feature to make first_name and last_name required fields.
When the user goes to their profile page, then they must add a first_name and last_name.
There are also some custom WooCommerce fields that I want to make required as well.
Is there a pre-save-profile hook/filter?
Thanks

A: You could check the $_POST variable when updating the user profile page.
I would hook into user_profile_update_errors and do something along those lines. This filter will not save to DB if errors are found.
add_filter('user_profile_update_errors', 'wpse_236014_check_fields', 10, 3);
function wpse_236014_check_fields($errors, $update, $user) {

  // Use the $_POST variable to check required fields

  if( empty($_POST['first_name']) )
    // add an error message to the WP_Errors object
    $errors->add( 'first_name_required',__('First name is required, please add one before saving.') );

  if( empty($_POST['last_name']) )
    // add an error message to the WP_Errors object
    $errors->add( 'last_name_required',__('Last name is required, please add one before saving.') );

  // Add as many checks as you have required fields here

  if( empty( $errors->errors ) ){

    // Save your custom fields here if no errors are found
    // Just skip this if you don't need to do extra work.
    // Fields will save if no errors are found

  }

}

EXTRA
There is also 2 hooks that you could use when saving custom fields added to the profile page. I'll refer you to the codex if you want more specifications as I'm pretty sure you won't need those for your specific use case as I believe WooCommerce custom fields should appear in the $_POST variable as well.

*

*edit_user_profile_update -- This one is used any time a profile page is edited.

*personal_options_update -- This one is triggered when a user visit their own profile


text:
Q: I'd like to search CoreData records, over many fields I'd like to perform an NSFetchRequest. I want to look through all objects with a specific NSEntityDescription, but just look for text in all the fields in that entity.
I'd like to do this, because I want to have a simple search field in my app. So if a user types in "Joe Cincinnati", they would expect to get back all records that have the text "Joe" and "Cincinnati", regardless of which fields they show up in. Also, the record must have both "Joe" and "Cincinnati" in their fields somewhere, it just doesn't matter where.

A: Without designing specifically for this kind of search, you're stuck with either using complex multi-part predicates or with doing repeated fetches to cover each search term/string attribute pair. For M search terms and N string attributes you end up with either one predicate with M x N components or doing M x N separate fetches. Both of these options suck.
But with some advance work you can sidestep that issue. Here are a couple of options to consider:
Add a new "searchText" field to your entity
Add a new string attribute to your entity description called searchText. This field is made up of all the text from every other string attribute, but in a normalized form (e.g. lower case) in a single location. Any time data in another string field changes, you update searchText. When searching, you only use this attribute. Your predicate has the same number of components as the number of search terms, which should be much faster.
In this case your predicate would be a compound AND predicate where each term's format is something like @"searchText contains %@".
Or...
Add a new "SearchText" entity
Create a new entity type called SearchText, which has a single string attribute. Set up a one-to-many relationship from your current entity type to the new SearchText type. Each instance of your entity type will relate to one SearchText instance for every possible search term. This still requires a multi-part predicate, but since the text field is much shorter the results should be much faster.
In this case you still have a compound AND predicate, though in this case each part's format would be something like @"any searchStrings = %@" (assuming the new to-many relationship is called searchStrings).

A: What you describe would be a rather extensive predicate, but you can create a generic solution by examining the NSEntityDescription and iterating over the attributes. You can check the type as you only care about strings. For each string you should create a predicate. Then you can create a compound predicate from them.


text:
Q: Aerospike query language operate command I am trying to run aerospike query language operate command given at Operate on a record

aql> OPERATE INCR(mybin,1) ON
  test.demo where PK = 'key1'

But I get the following error

ERROR: 404: COMMAND NOT FOUND : OPERATE

My client version is as follows:

Aerospike Query Client Version 3.13.0.1 C Client Version 4.1.6

Eventually, I am trying to increment a record value.

A: Make sure that you're using Aerospike Tools >= 3.15.0.3 . CDT operations and others were added in that release; see the release notes.

A: Type help on aql prompt. Those are all the commands available to you along with examples on how to use them.
$ aql
aql> help


text:
Q: Android implementation for socialauth Is there any android implementation for socialauth http://code.google.com/p/socialauth/
I need to be able to import contacts from  Google, Yahoo or Hotmail in my android application.
Thanks,
- Philip

A: Yes, an android implementation has been released recently
http://code.google.com/p/socialauth-android/


text:
Q: Content-Length header needed error when it is supplied I am trying to use spotify's Oauth2 but when I try to get the token the response says "411 POST requests require a Content-length header. That's all we know." but I have added the header to my post request.
#[get("/?<code>")]
fn spotify_oauth(code: String) -> String {
    println!("{}", code);
    let client = reqwest::Client::new();
    let url = format!("https://accounts.spotify.com/api/token/?grant_type=authorization_code&code={}&redirect_uri=http://localhost:8000", code);
    let res = client.post(&url)
        .header(reqwest::header::Authorization("Basic MYAUTH=".to_owned()))
        .header(reqwest::header::ContentType(reqwest::mime::APPLICATION_WWW_FORM_URLENCODED))
        .header(reqwest::header::ContentLength(0))
        .send().unwrap().text().unwrap();

    res
}

Thank you.


text:
Q: jQuery Drag & Drop Plugin Effected by BootStrap CSS I am running into a strange issue where my jQuery Drag & Drop simulation plugin is not working when BootStrap's CSS file is called in the header.
Here are two fiddles with the EXACT same code except for Bootstrap's CSS file being called:
With BootStrap CSS (Doesn't Work):
http://jsfiddle.net/3os4yhen/1/
Without BootStrap CSS (Working):
http://jsfiddle.net/zy3h3doo/1/
Does anyone have any idea what I can disable in that CSS file to keep using in the rest of my page?
Thank you so much!
Here is the full HTML:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>jQuery Simulate Extended Plugin - jsFiddle demo</title>

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/gosigner.css">

<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/dataTables.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/dropzone.css">

            <button id="testme">Simulate Drop</button>

A: It's the :
-webkit-box-sizing: border-box;
box-sizing: border-box;

..that the bootstrap is giving you.  A quick and easy override is:
-webkit-box-sizing: none !important;
box-sizing: none !important;

A: I decided to go line-by-line in the bootstrap.css file commenting out styles to see which is affecting the performance:
Line 1068 of bootstrap.css:
* {
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
}

When this is commented out, the Simulate Drop button works


text:
Q: Server to Server OAuth with Netlify API using "Authorization Code Grant" I'm trying to do Server to Server auth with netlify.com
I can find examples for authentication on behalf of users, but the type of authentication that I want to do - "Authorization Code Grant" has no examples.
I've been looking at this link for answers.
Netlify OAuth2
I'm also unsure whether I should be setting up an OAuth App on Netlify or a Personal Access Token.
My current code (RUBY) is returning a status 200 + HTML page.
Code that I am currently attempting to Auth with
def auth_get(client_id)
  # /authorize
  uri = URI('https://app.netlify.com')

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Get.new("/api/v1/authorize?grant_type=authorization_code&client_id=#{client_id}")
  response = http.request(request)
end

When I run the HTML page, I get an error.

Page not found
You might not have permissions to see this page.


text:
Q: AWS API gateway High Availability setup in us-east-1 and us-east-2 I want to setup API gateway services in two regions for HA. The primary is in east1. On health check failure it sould route to east 2.
Followed this article (below) to setup the same.
https://aws.amazon.com/blogs/compute/building-a-multi-region-serverless-application-with-amazon-api-gateway-and-aws-lambda/
What we did
1) setup my api services in both east 1 & east 2
2) both apis are created as regional(not cloud front)
3) created two certificates in each region with single custom domain name
   say api-ha-example.com. Mapped to with each of its reginal certificate(ACM)
4) The custom domains are created in each region
5) two cname records exsits now in R53 with same name "api-ha-example.com" and,
   value of each regional API end point. Show here.
  1)api-ha-example.com --->  https://xxxxx.execute-api.us-east-1.amazonaws.com/initdev ----> Primary
   2)api-ha-example.com --->  https://xxxxx.execute-api.us-east-2.amazonaws.com/initdev ----> secondary

Health check is set to 200 status for primary for now
The problem
-----------
I am able to hit the indivisual API enpoints directly. But when i hit with the domain name https://api-ha-example.com/
I dont get anything. site cant be reached. ping test says, cant reolve the domain to server.Anything missing in my settings? Followed the steps as per blog
https://aws.amazon.com/blogs/compute/building-a-multi-region-serverless-application-with-amazon-api-gateway-and-aws-lambda/

Anyone faced this issue?

A: You have configured this in DNS:
api-ha-example.com CNAME https://xxxxx.execute-api.us-east-1.amazonaws.com/initdev ;; primary
api-ha-example.com CNAME https://xxxxx.execute-api.us-east-2.amazonaws.com/initdev ;; secondary

DNS CNAME records are hostnames, only -- they have no support for either schemes or paths, so the https:// at the beginning and /initdev at the end of the CNAME records need to be removed.


text:
Q: python how to set a thread limit? I was wondering how I could limit something like this too use only 10 threads at one time
with open("data.txt") as f:
    for line in f:
        lines = line.rstrip("\n\r")
        t1 = Thread(target=Checker, args=("company"))
        t1.start()

A: Use Python's ThreadPoolExecutor with max_workers argument set to 10.
Something like this:`
pool = ThreadPoolExecutor(max_workers=10)
with open("data.txt") as f:
    for line in f:
        lines = line.rstrip("\n\r")
        pool.submit(Checker,"company")

pool.shutdown(wait=True)

The pool will automatically allocate threads as needed, limiting maximum number of allocation to 10. The first argument in pool.submit() is the function name, the arguments are simply passed as comma-separated values.
pool.shutdown(wait=True) waits for all threads to complete execution.

A: Use the ThreadPoolExecutor and tell it that you want 10 threads.
def your_function_processing_one_line(line):
    pass  # your computations

with concurrent.futures.ThreadPoolExecutor(10) as executor:
    result = executor.map(your_function_processing_one_line, [line for line in f])

...and you will have all the results in result.

A: I wrote this nested loop to cap threads to a variable.
This code relies on a preset array of commands to process.
I have borrowed some elements from other answers for thread launch.
import os, sys, datetime, logging, thread, threading, time
from random import randint

# set number of threads
threadcount = 20

# alltests is an array of test data

numbertests = len(alltests)
testcounter = numbertests

# run tests
for test in alltests:
    # launch worker thread
    def worker():
        """thread worker function"""
        os.system(command)
        return
    threads = []
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()
    testcounter -= 1
    # cap the threads if over limit
    while threading.active_count() >= threadcount:
        threads = threading.active_count()
        string = "Excessive threads, pausing 5 secs - " + str(threads)
        print (string)
        logging.info(string)
        time.sleep(5)

# monitor for threads winding down
while threading.active_count() != 1:
    threads = threading.active_count()
    string = "Active threads running - " + str(threads)
    print (string)
    logging.info(string)
    time.sleep(5)

A: (for both Python 2.6+ and Python 3)
Use the threadPool from multiprocessing module:
from multiprocessing.pool import ThreadPool

The only thing is that it is not well documented...


text:
Q: xts indexing lag error I have a question about indexing with xts. I understand that when I use SPY['2002-10-17/'], I can get all of the data in my xts object from 2002-10-17 to the last date. This however is not true if I write an ifelse statement and do the same call. Below is code:
library(quantmod)
getSymbols('SPY',from='2002-01-01')
SPY=Cl(SPY) #pull only the closes
returns=(SPY-lag(SPY,1))/(lag(SPY,1)) #returns calculation
head(SPY['2002-10-17/']) #This works and starts at 2002-10-17
head(ifelse(returns>0,1,0)['2002-10-17/']) #this for some odd reason starts at 2002-10-18

Can anyone tell me why this is the case. I am truly befuddled.
As Joshua suggested here is the output from sessionInfo()
> sessionInfo()
R version 3.2.0 (2015-04-16)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] quantmod_0.4-3 TTR_0.22-0     xts_0.9-7      zoo_1.7-12

loaded via a namespace (and not attached):
[1] tools_3.2.0     grid_3.2.0      lattice_0.20-31

A: I can confirm this behavior in xts_0.9-7. It's a bug that has been fixed in the development version.
The bug is in the logical operator (>) dropping the timezone attribute on the xts object. That causes the index to be offset by however many hours your local timezone is offset from UTC. So, the logical operator is essentially changing the interpretation of the index of the object created by the logical operator.
> head((returns > 0)['2002-10-17/'])
           SPY.Close
2002-10-18      TRUE
2002-10-21      TRUE
2002-10-22     FALSE
2002-10-23      TRUE
2002-10-24     FALSE
2002-10-25      TRUE
> indexTZ(returns)
[1] "UTC"
> indexTZ(returns > 0)
[1] ""


text:
Q: Android RadioGroup Get Checked RadioButton Index (Position) in Two-way DataBinding Following is my current solution:
<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:onCheckedChanged="@{(group, buttonId) -> student.setGenderIndex(group.indexOfChild(group.findViewById(buttonId)))}"
    android:orientation="horizontal">

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:checked="@{student.genderIndex == 0}"
        android:text="Male" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="@{student.genderIndex == 1}"
        android:text="Female" />

</RadioGroup>

This works fine, but I'm wondering if there is a better way to do this. And then I find out that there is a built-in two-way attribute for RadioGroup: android:checkedButton (from Official Documentation), however it is the id not the index I want:
public static final int checkedButton

The id of the child radio button that should be checked by default within this radio group.

May be an integer value, such as "100".

Constant Value: 16843080 (0x01010148)

I still try (to make my binding expression shorter) but doesn't work:
android:onCheckedChanged="@{(group, buttonId) -> student.setGenderIndex(group.indexOfChild(group.checkedButton))}"

Says "Could not find accessor android.widget.RadioGroup.checkedButton"

A: Add onCheckedChanged like this
<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onCheckedChanged="@{vm.onSplitTypeChanged}">

    <RadioButton
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/email" />

    <RadioButton
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/sms" />
</RadioGroup>

Then in your view model implement onSplitTypeChanged like this
fun onSplitTypeChanged(radioGroup: RadioGroup?, id: Int) {
        val checked = radioGroup?.findViewById<RadioButton>(id)
        val index = radioGroup?.indexOfChild(checked)
    }


text:
Q: How to extend "Create with reference" dialog in VA01/02 We would like to extend the "Create with reference" dialog in the transactions VA01 and VA02 with an additional tab.

The functionality is very similar to the tab "Order". When the user clicks on the "Item Selection" button I need to add more data to the next screen.
Is it possible to copy the "Order" tab and adjust it to our requirements?
Addition:
As suggested I started to modify the function group V45C. But as soon as I add the additional tab the programs logic seems to mess up. As soon as the dialog opens I alsways get an error to enter a reference.

It turned out to be quite difficult to debug in that place as I can't enter the function code /h. I assume that the new corresponding fcode is not handled properly so I get this error message.
Do you have any suggestions on where to handle the new fcode and display the dynpro for the tab?
Thanks in advance!


text:
Q: cdk watch command forces full deploy with unrelated error on file change I'm developing a little CDKv2 script to instantiate a few AWS services.
I have some lambda code deployed in the lambda/ folder and the frontend stored in a bucket populated using the frontend/ folder in the source.
I've noticed that whenever I make a change to any of the file inside these two, cdk watch return the following error and falls back to perform a full redeploy (which is significantly slow).
Could not perform a hotswap deployment, because the CloudFormation template could not be resolved: Parameter or resource 'DomainPrefix' could not be found for evaluation
Falling back to doing a full deployment

Is there any way to make changes in these folders only trigger updating the related bucket content or the related lambda?
Following here the stack.ts for quick reference, just in case here you can take a look at the repo.
export class CdkAuthWebappStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const domainPrefixParam = new CfnParameter(this, 'DomainPrefix', {
      type: 'String',
      description: 'You have to set it in google cloud as well', //(TODO: add link to explain properly)
      default: process.env.DOMAIN_NAME || ''
    })

    const googleClientIdParam = new CfnParameter(this, 'GoogleClientId', {
      type: 'String',
      description: 'From google project',
      noEcho: true,
      default: process.env.GOOGLE_CLIENT_ID || ''
    })

    const googleClientSecretParam = new CfnParameter(this, 'GoogleClientSecret', {
      type: 'String',
      description: 'From google project',
      noEcho: true,
      default: process.env.GOOGLE_CLIENT_SECRET || ''
    })

    if(!domainPrefixParam.value || !googleClientIdParam.value || !googleClientSecretParam.value){
      throw new Error('Make sure you initialized DomainPrefix, GoogleClientId and GoogleClientSecret in the stack parameters')
    }

    const s3frontend = new s3.Bucket(this, 'Bucket', {
      bucketName: domainPrefixParam.valueAsString+'-frontend-bucket',
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      encryption: s3.BucketEncryption.S3_MANAGED,
      enforceSSL: true,
      versioned: false,
      removalPolicy: cdk.RemovalPolicy.DESTROY,
      autoDeleteObjects: true,
      websiteIndexDocument: "index.html",
    });

    //TODO: fare in modo che questa origin access identity non sia legacy quando deployo
    const cfdistributionoriginaccessidentity = new cloudfront.OriginAccessIdentity(this, 'CFOriginAccessIdentity', {
      comment: "Used to give bucket read to cloudfront"
    })

    const cfdistribution = new cloudfront.CloudFrontWebDistribution(this, 'CFDistributionFrontend', {
      originConfigs: [
        {
          s3OriginSource: {
            s3BucketSource: s3frontend,
            originAccessIdentity: cfdistributionoriginaccessidentity
          },
          behaviors: [{
            isDefaultBehavior: true,
            allowedMethods: cloudfront.CloudFrontAllowedMethods.GET_HEAD_OPTIONS,
            forwardedValues: {
              queryString: true,
              cookies: { forward: 'all' }
            },
            minTtl: cdk.Duration.seconds(0),
            defaultTtl: cdk.Duration.seconds(3600),
            maxTtl: cdk.Duration.seconds(86400)
          }]
        }
      ]
    })

    s3frontend.grantRead(cfdistributionoriginaccessidentity)

    const cfdistributionpolicy = new iam.PolicyStatement({
      effect: iam.Effect.ALLOW,
      actions: ['cloudfront:CreateInvalidation'],
      resources: [`"arn:aws:cloudfront::${this.account}:distribution/${cfdistribution.distributionId}"`]
    });

    const userpool = new cognito.UserPool(this, 'WebAppUserPool', {
      userPoolName: 'web-app-user-pool',
      selfSignUpEnabled: false
    })

    const userpoolidentityprovidergoogle = new cognito.UserPoolIdentityProviderGoogle(this, 'WebAppUserPoolIdentityGoogle', {
      clientId: googleClientIdParam.valueAsString,
      clientSecret: googleClientSecretParam.valueAsString,
      userPool: userpool,
      attributeMapping: {
        email: cognito.ProviderAttribute.GOOGLE_EMAIL
      },
      scopes: [ 'email' ]
    })

    // this is used to make the hostedui reachable
    userpool.addDomain('Domain', {
      cognitoDomain: {
        domainPrefix: domainPrefixParam.valueAsString
      }
    })

    const CLOUDFRONT_PUBLIC_URL = `https://${cfdistribution.distributionDomainName}/`

    const client = userpool.addClient('Client', {
      oAuth: {
        flows: {
          authorizationCodeGrant: true
        },
        callbackUrls: [
          CLOUDFRONT_PUBLIC_URL
        ],
        logoutUrls: [
          CLOUDFRONT_PUBLIC_URL
        ],
        scopes: [
          cognito.OAuthScope.EMAIL,
          cognito.OAuthScope.OPENID,
          cognito.OAuthScope.PHONE
        ]
      },
      supportedIdentityProviders: [
        cognito.UserPoolClientIdentityProvider.GOOGLE
      ]
    })

    client.node.addDependency(userpoolidentityprovidergoogle)

    // defines an AWS Lambda resource
    const securedlambda = new lambda.Function(this, 'AuhtorizedRequestsHandler', {
      runtime: lambda.Runtime.NODEJS_14_X,
      code: lambda.Code.fromAsset('lambda'),
      handler: 'secured.handler'
    });

    const lambdaapiintegration = new apigw.LambdaIntegration(securedlambda)

    const backendapigw = new apigw.RestApi(this, 'AuthorizedRequestAPI', {
      restApiName: domainPrefixParam.valueAsString,
      defaultCorsPreflightOptions: {
        "allowOrigins": apigw.Cors.ALL_ORIGINS,
        "allowMethods": apigw.Cors.ALL_METHODS,
      }
    })

    const backendapiauthorizer = new apigw.CognitoUserPoolsAuthorizer(this, 'BackendAPIAuthorizer', {
      cognitoUserPools: [userpool]
    })

    const authorizedresource = backendapigw.root.addMethod('GET', lambdaapiintegration, {
      authorizer: backendapiauthorizer,
      authorizationType: apigw.AuthorizationType.COGNITO
    })

    const s3deploymentfrontend = new s3deployment.BucketDeployment(this, 'DeployFrontEnd', {
      sources: [
        s3deployment.Source.asset('./frontend'),
        s3deployment.Source.data('constants.js', `const constants = {domainPrefix:'${domainPrefixParam.valueAsString}', region:'${this.region}', cognito_client_id:'${client.userPoolClientId}', apigw_id:'${backendapigw.restApiId}'}`)
      ],
      destinationBucket: s3frontend,
      distribution: cfdistribution
    })

    new cdk.CfnOutput(this, 'YourPublicCloudFrontURL', {
      value: CLOUDFRONT_PUBLIC_URL,
      description: 'Navigate to the URL to access your deployed application'
    })
  }
}

A: Recording the solution from the comments:
Cause:
cdk watch apparently does not work with template parameters.  I guess this is because the default --hotswap option bypasses CloudFormation and deploys instead via SDK commands.
Solution:

*

*Remove the CfnParamters from the template.  CDK recommends not using parameters in any case.

*Perhaps cdk watch --no-hotswap would also work?


text:
Q: Calculate Area Element on a Prolate Spheroid's Surface I am trying to calculate a partial surface of a prolate spheroid in terms of the polar and azimuthal angles. I have been searching the internet for quite some time, but without finding a solution or an idea how to solve it that I understood.
So, here is what I think is the closest I got to a solution.
The general form of a spheroid:
$$\frac{x^2+y^2}{a^2}+\frac{z^2}{c^2}=1$$ with $c>a$ making it prolate.
It can be parameterised in the following form
$$x=a \> \cos(\phi) \> \sin(\theta)$$
$$y=a \> \sin(\phi) \> \sin(\theta)$$
$$z=c \> \cos(\theta)$$
with $\phi \in [0, 2\pi]$ and $\theta \in [0, \pi]$.
If I determine the coefficients of the first fundamental form $S = \int_{\phi_0}^{\phi_1}d\phi\int_{\theta_0}^{\theta_1}\sqrt{EG-F^2} \> d\theta$, they turn out to be
$$E = a^2 \> \sin^2(\theta)$$
$$F = 0$$
$$G = \frac{a^2+c^2+(a^2-c^2) \> \cos(2 \> \theta)}{2}$$
This was actually the approach as described on Wolfram Mathworld for a general spheroid. If the coefficients are plugged into the above equation for $S$, it results in $$S = \frac{a}{\sqrt{2}}\int_{\phi_0}^{\phi_1}d\phi\int_{\theta_0}^{\theta_1}\sqrt{a^2+c^2+(a^2-c^2) \> \cos(2 \> \theta)}\>\sin(\theta) \> d\theta$$
This equation can also be found on Wolfram, but is said to be the conventional form for the oblate spheroid ($a>c$). Apparently, the integral $\int_{\theta_0}^{\theta_1}\sqrt{a^2+c^2+(a^2-c^2) \> \cos(2 \> \theta)}\>\sin(\theta) \> d\theta$ can be solved to $$\dfrac{-c^2\ln\left(\left|c\sqrt{\left(a^2-c^2\right)\cos^2\left(x\right)+c^2}+\sqrt{a^2-c^2}\left|c\right|\cos\left(x\right)\right|\right)-c\sqrt{a^2-c^2}\cos\left(x\right)\sqrt{\frac{\left(a^2-c^2\right)\cos^2\left(x\right)}{c^2}+1}}{\sqrt{2}\sqrt{a-c}\sqrt{c+a}}$$
This works well indeed for oblate spheroids. I used the ke!san Online Calculator to confirm.
Now, what do I have to do differently to find a similar function $S(\phi, \theta)$ for a prolate spheroid? Simply flipping $c$ and $a$ did not seem to do the trick. The parameterisation will stay the same as it is independent of the ratio of $c$ and $a$. Therefore, the fundamental coefficients should change neither.
I hope you can push me in the right direction. Any help is much appreciated!


text:
Q: Equivalent formulation of linear logic with more axioms and less inference rules We can formulate classical (sequent) logic with only the structural inference rules including cut, and a collection of axioms like $A, B \vdash A \wedge B$. This is equivalent to the usual sequent calculus of classical logic, in the sense that the provable sequents are the same.
Can we do the same with classical linear logic? Assuming only Ax: $\frac{}{A \vdash A}$ and Cut: $\frac{\Gamma \vdash A, \Delta\quad\Xi,A \vdash \Phi}{\Gamma, \Xi \vdash \Delta, \Phi}$, and a collection of sequents as axioms, can we recover the full MALL? Of the four binary connectives, we can easily come up with the elimination axiom for $\&$ and $⅋$ (\lpar is not supported by MO), and the introduction axiom for $\otimes$ and $\oplus$. However, I'm having difficulty with the other side. It seems that if we allow ourselves additionally the rules for $\multimap$, then I think the elimination axiom for $\otimes$ would be $A \multimap (B \multimap C) \vdash (A \otimes B) \multimap C$. But I'm not able to proceed any further.
Also, I haven't considered negation yet. Perhaps it will be better to regard negation as an involution on the formulae, which might give us a way to relate the different connectives.
Is there any previous work on this? Or can it be proven that such a formulation is impossible? (This might be achieved by demonstrating that sequents as opposed to rules never impose enough constraints on the logic.)


text:
Q: Veracode Cryptography issue Recently we done a static security scan using Veracode on one of the applications.
The report indicate an issue

Use of a Broken or Risky Cryptographic Algorithm (CWE ID 327)

It is shown for following code snippet
byte[] CalculateHash(byte[] publicKey) {
        SHA1CryptoServiceProvider hashGenerator = new SHA1CryptoServiceProvider();
        Byte[] hashInArray = new Byte[32];
        PrivateKey.CopyTo(hashInArray,0);            // Combine public key and private key
        publicKey.CopyTo(hashInArray,16);
        return hashGenerator.ComputeHash(hashInArray); // Calculate hash
    }

In description it describe SHA1 as a weak algorithm.
I modified the code and used SHA256 instead of SHA1 and performed veracode scanning again but it still show same issue.
What is an alternative for this? any suggestions?


text:
Q: [python pandas]Is that possible to set style permanently? Via modify pandas files?
Something like change set default style?
Display Maximum columns and rows. Highlights na value as red etc.
I don't

A: Use these pandas set options to display more or less rows/columns.
import pandas as pd
pd.set_option('display.max_rows', 50)
pd.set_option('display.max_columns', 50)
pd.set_option('display.width', 100)


text:
Q: Animating UIview from top to bottom and vice versa I have a UIView at X=0 and Y=0 location with the height of 110 and UIButton at the bottom of the screen with the height of 50, i want to show both by animating but the UIView must animate from top to to its height and UIButton from bottom to its height, i am totally new with this please help me how to do it.

A: basic animation which may fit your requirement
[UIView transitionWithView:view
                  duration:0.5
                   options:UIViewAnimationOptionTransitionNone
                animations:^{
                   //update your frame here;
                }
                completion:nil];

Please go thru Apple Documentation and stack overflow

A: Following code worked for me to show a search view on top.
if (!isSearchActive) {
    [UIView animateWithDuration:0.4
                          delay:0.1
                        options: UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         searchView.frame   =   CGRectMake(0, 56, mainWidth, 50);
                     }
                     completion:^(BOOL finished){
                     }];
    isSearchActive=YES;
}
else{
    [UIView animateWithDuration:0.3
                          delay:0.1
                        options: UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         searchView.frame   =   CGRectMake(0, 56, mainWidth, 0);
                     }
                     completion:^(BOOL finished){
                     }];
    isSearchActive=NO;
}

Call this code on click of any button to show and hide the view.

A: Try this for top to bottom Animation:
- (CAAnimation*)movedown;
{
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"position.y";
    animation.fromValue = @600;
    animation.toValue = @50;
    animation.duration = 0.25;

    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

    [trashView.layer addAnimation:animation forKey:@"basic"];
    trashView.layer.position =CGPointMake(0,-20);
    return animation;
}

and Code for Bottom to Top:
- (CAAnimation*)moveup;
{
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"position.y";
    animation.fromValue = @-500;
    animation.toValue = @10;
    animation.duration = 0.25;

    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

    [trashView.layer addAnimation:animation forKey:@"basic"];
    trashView.layer.position =CGPointMake(0,20);
    return animation;

}

for first block of code you can use to animate view but you have to replace your viewcontroller at trashview in code.
and second block use for button but you have to replace your button at trashview.
but you can set value of animation according to your need.

A:    private func startAnimation() {
            let animation = CABasicAnimation(keyPath: "position.y")
            animation.fromValue = 10  //Top Y
            animation.toValue = 204  //Bottom Y
            animation.duration = 15 * 0.10 //duration * speed
            animation.repeatCount = 100
            animation.autoreverses = false
            animation.isRemovedOnCompletion = true
            animation.fillMode = .forwards
            self.yourView.layer.add(animation, forKey: "position.y")
        }

  private func stopAnimation() {
        self.yourView.layer.removeAllAnimations()
    }


text:
Q: Completion time of "_invalidate_internal" in Matplotlib increases linearly over extended periods. What is this function doing? I am running a Python Tkinter GUI application for multiple days (ideally it will run continuously without needing to be restarted). After a few days, the program typically crashes with no explanation or error messages. I have used cProfile to profile the animation functionality of our Matplotlib graphs and search for possible slow-down points. The results clearly showed that the only function which increased in execution time over the program run period was this one:
/usr/lib/python3/dist-packages/matplotlib/transforms.py:134(_invalidate_internal)
I've looked at the Matplotlib source code (https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/transforms.py), but I haven't been able to figure out what this function is doing. What does _invalidate_internal do, and is there anything I can do to prevent it from taking so long to execute?
For more context, our program has several animated matplotlib plots which graph inputs from sensor data over time. We plot the n most recent data points on each frame so that it gives the effect of a scrolling graph. Here is the animation code:
def animate(ii):

while True:
    most_recent_time_graphed = param_dict[param_list[0]] #first, pulls up first plot
    most_recent = reader.query_by_num(table="SensorData", num=1)
    reader.commit()         #if identical, do not animate
    #then checks that plot's time list
    if  (len(most_recent) == 0):
        break

    #time_reader = datetime.strptime(most_recent[0][0], "%m/%d/%Y %H:%M:%S")
    time_reader = datetime.datetime.fromtimestamp(most_recent[0][0])
    if (len(most_recent_time_graphed.tList) != 0) and (time_reader == most_recent_time_graphed.tList[0]):
        for i, param in enumerate(param_list, 1):
            current_text = live_dict[param]
            current_text.label.config(text=most_recent[0][i], fg="black", bg="white")
        break #checks if the timestamp is exactly the same as prior, i.e. no new data points have been logged in this frame
    #do I have to add an else?

    else:
        config_settings = csv_read()
        c0, c1, c2 = config_dict['enable_text'], config_dict['num_config'], config_dict['provider_config']
        c3, c4, c5 = config_dict['email_config'], config_dict['upper_config'], config_dict['lower_config']
        for i, key in enumerate(param_dict, 1):
            current_plot = param_dict[key]
            current_param_val = float(most_recent[0][i])
            current_text = live_dict[key] #update to live text data summary
            if current_param_val > float(config_settings[c4][i-1]) or current_param_val < float(config_settings[c5][i-1]):
                #only send text if enable_text is True
                if config_settings[c0] == [str(True)]:
                ###sends text if new problem arises or every 5  minutes
                    if allIsGood[key] and Minute[key] == None:
                        print('new problem')
                        Minute[key] = datetime.now().minute
                        minuta[key] = Minute[key]
                        pCheck(float(config_settings[c4][i-1]),float(config_settings[c5][i-1]),key,current_param_val,config_settings[c1],config_settings[c2]) #uncomment to test emergency texts
                    elif allIsGood[key] == False and abs(Minute[key] - datetime.now().minute) % 5 == 0 and not (minuta[key] == datetime.now().minute):
                        print('same problem')
                        minuta[key] = datetime.now().minute
                        pCheck(float(config_settings[c4][i-1]),float(config_settings[c5][i-1]),key,current_param_val,config_settings[c1],config_settings[c2]) #uncomment to test emergency texts
                        #pass

                    #setting the parameter to not ok
                    allIsGood[key] = False

                current_text.label.config(text=most_recent[0][i], fg="red", bg="white")
                current_plot.plot_color = 'r'

            else:
                current_text.label.config(text=most_recent[0][i], fg="black", bg="white")
                current_plot.plot_color = 'g'

                ###setting the parameter back to true and sending "ok" text
                if allIsGood[key] == False:
                    Minute[key] = None
                    allOk(key,config_settings[c1],config_settings[c2])
                    pass

                allIsGood[key] = True

            data_stream = current_plot.incoming_data
            time_stream = current_plot.tList
            data_stream.insert(0, most_recent[0][i])
            #time_f = datetime.strptime(most_recent[0][0], "%m/%d/%Y %H:%M:%S")
            time_f = datetime.datetime.fromtimestamp(most_recent[0][0])
            time_stream.insert(0, time_f)
            if len(data_stream) < 20: #graph updates, growing to show 20 points
                current_plot.make_plot()
            else:                      #there are 20 points and more available, so animation occurs
                data_stream.pop()
                time_stream.pop()
                current_plot.make_plot()
        break


text:
Q: Getting Excon::Errors::SocketError while reading images from one S3 and to write to another? We have a staging server setup to use a different S3 bucket from our production server, but that requires us to manually sync the images between the buckets in order to see images on staging. As we have tens of thousands of images (growing daily), this is not viable.
Is there anyway to configure Carrierwave to read images from our production S3, but write any new images to staging S3 (so as to not contaminate our production image store)?

UPDATE: I've tried my hand at creating a custom storage engine for CarrierWave that would do this (see this gist--basically identical to the fog storage engine except for line 228), but I'm getting this error when trying to fetch images:
 Excon::Errors::SocketError (hostname does not match the server certificate (OpenSSL::SSL::SSLError)):
   lib/carrier_wave/storage/dual_fog.rb:214:in `exists?'
   lib/carrier_wave/storage/dual_fog.rb:228:in `public_url'
   lib/carrier_wave/storage/dual_fog.rb:267:in `url'

Anyone know why that is? As you can see from the code in the gist, I want this solution to be able to read from staging, and fallback to production if no image is found on staging. All write operations should only go to staging, however.

A: There are several ways to use S3. If you have dots in your bucket and want to do SSL, you'll need to force your URLs to look like this: https://s3.amazonaws.com/staging.asset.domain.com/blah. You cannot use https://yourdomain.com/blah because amazon doesn't have your cert. You also cannot use https://staging.asset.domain.com.s3.amazonaws.com/blah because the certs only go one level deep. (i.e. if your bucket had no dots, it would work.)


text:
Q: What is the difference between creating database role and application role? I want to have a role called ValidUsers.
My application will check if the user belongs to this group. If so then allow him to access the application.
Now when I right click roles under the database, I can see database role and application role. What is the difference between these and which fits into my use case?

A: Application Roles are a mechanism where you allow a client application to connect the user via their own login (either Windows Authentication or SQL Server Authentication) - once the user has connected the application executes sp_setapprole to switch security context into the app role.
The app role would have appropriate permissions as needed in the database.  The user's login would only have CONNECT permission.
This prevents connections from seeing data in the database unless they know the password for the app role.
Take a look at the Microsoft Docs for more details and examples.


text:
Q: How to do MAC layer padding I am trying to send udp frames through windows sockets to a DUT but the device won't respond.
I found out that the frames which I was sending needs to be of minimum 60 bytes(MAC+IP+UDP+Payload) in length.
I have searched a lot on enabling MAC layer padding and have not found anything.
I do not want to use winpcap here.


text:
Q: How to store output of Sqoop list-tables command to text file? Sqoop list-tables command display the list of tables from particular database to console. I want to store that output in to text file. Can someone help ?

A: Redirect your sqoop command output to a file. Below is the sample Sqoop command to redirect to a file
sqoop list-tables --connect jdbc:mysql://localhost/learning --username root --password-file "/Learning/sqoop/.password" > tables


text:
Q: Add a progress bar to an existing code (Keep the latest file of each group and delete the rest) I created a PowerShell file using information from internet.
It allows me to keep the latest file of each day and delete the rest
$sourceFolder = 'C:\mypath'
$filePrefix   = 'U_07_'

Get-ChildItem -Path $sourceFolder -Filter "$filePrefix*.csv" -File |
    Where-Object { $_.BaseName -match '_\d{14}$' } |
    Group-Object -Property @{Expression = { $_.LastWriteTime.Date }} |
        ForEach-Object {
            $_.Group |
            Sort-Object -Property LastWriteTime -Descending |
            Select-Object -Skip 1 |
            Remove-Item -Force
        }

I would like to add a progress bar to the script i made. While it seems easy to do a progress bar with a simple code to delete files, when it comes to manage groups i cannot figure out how to incorporate a progress bar in it.
Below my attempt :
$sourceFolder = 'C:\mypath'                                                                    # put the path to the folder where your files are here
$filePrefix   = 'U_07_'
$Events = Get-EventLog -LogName system

Get-ChildItem -Path $sourceFolder -Filter "$filePrefix*.csv" -File |
    Where-Object { $_.BaseName -match '_\d{14}$' } |
    Group-Object -Property @{Expression = { $_.LastWriteTime.Date }} |
        $Events | ForEach-Object -Begin {
        Clear-Host
        $i= 0
        } -Process{
            $_.Group |
            Sort-Object -Property LastWriteTime -Descending |
            Select-Object -Skip 1 |
            Remove-Item -Force
            $i=$i+1
            Write-Progress -Activity "Deleting Files" -Status "Progress:" -PercentComplete ($i/$Events.count*100)
        } -End

And the error i get  :
At C:\Users\Bob\Desktop\Script\test.ps1:13 char:9
+         $Events | ForEach-Object -Begin {
+         ~~~~~~~
Expressions are only allowed as the first element of a pipeline.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline

Hoping somebody can guide me in the right direction.
Thanks a lot for your help.
Best regards.

A: You have two things going on here. First, you can't pipe Group-Object into $Events. Remove the pipe suffix | from the preceeding line to fix the error.
Second, I missed this in my original answer but you have a trailing -End argument of your last Foreach-Object. You either need to remove the argument or provide a ScriptBlock as this is what the -End parameter requires.

Edit 2: For a global progress bar
Based on your comments, and after re-reading your original sample, I'm not clear why you're iterating over the System event log to remove files from the filesystem when you're not using any of the event data or basing your progress bar off that. I'm going to omit this since there's no reason to use it based on what you've provided.
If you want a global progress bar per your comment (this wasn't in your question), it complicates things a bit but here's how you do it:
$sourceFolder = 'C:\mypath'
$filePrefix = 'U_07_'

$filesToDelete = Get-ChildItem -Path $sourceFolder -Filter "$filePrefix*.csv" -File |
  Where-Object { $_.BaseName -match '_\d{14}$' } |
  Group-Object -Property @{Expression = { $_.LastWriteTime.Date } } |
  ForEach-Object { $_.Group | Sort-Object -Descending LastWriteTime | Select-Object -Skip 1 }

$filesToDelete | ForEach-Object -Begin {
  $i = 0
} -Process {
  Write-Progress -Activity "Deleting Files" -Status "Progress:" -PercentComplete ($i++ / $filesToDelete.Count * 100)
  Remove-Item $_ -Force
} -End {
  Write-Progress -Activity "Deleting Files" -Completed
}

Basically, set $filesToDelete to the actual files and not the file groups. Notice I iterate over each group in the first ForEach-Object, Sort-Object descending against LastWriteTime, then skip the first object. This will grab all but the most recent file for each date-group for deletion.
We could just pipe the Select-Object -Skip 1 to Remove-Item -Force within in the first ForEach-Object loop like so (multi-line for readability):
| ForEach-Object {
  $_.Group | Sort-Object -Descending LastWriteTime |
  Select-Object -Skip 1 | Remove-Item -Force
}

but since you want the progress bar we needed $filesToDelete so we can reference the total file count for the progress bar. Now that we've initialized our fileset, we need to iterate over the files again to remove them, using the -Begin block to set the initial counter and the -End block to mark the progress bar -Completed.
The -Process block updates the progress bar, basing the percentage off of the total files to delete instead of the number of events in the event log, then performs the item removal.
To test this, add -WhatIf to Remove-Item and it will tell the files it would have deleted, without actually deleting them.

Note: Updating the progress bar does carry some overhead and if you notice an issue with it taking longer than expected to deleted a large number of small files (I mean in the thousands, for example), you can either disable the progress bar with $ProgressPreference = 'SilentlyContinue' or modify the -Process block to only update the progress every few files or so.

My original answer indicated that your code wasn't incrementing $i, but you've updated your example. Still, if you make use of the unary operator ++ you can simplify what you currently have, though this change is not necessary for your code to function:
Write-Progress -Activity "Deleting Files" -Status "Progress:" -PercentComplete ( $i++/$Events.count*100 )

Read below for some more information on ++/-- and +=/-=.

In case you are unfamiliar, ++ and -- are unary operators common in several languages which add or subtract 1 from the referenced variable. The actual behavior is nuanced, and can differ between languages but I'll explain the behavior in PowerShell here (-- subtracts instead of adds):

*

*$var++ means "use the value of $var, then increment it by 1"

*++$var means "increment $var by 1, then use the new value"

Curiously, while these are arithmetic operators they behave a bit like assignment operators when used on their own. $var++ will not output to the console, it updates in place and does not return the result. You can, however, achieve this with variable squeezing by wrapping the increment in parentheses: ( $var++ )
Despite the above behavior, you do not need to squeeze ++ or -- within an expression or equation where its value would be referenced or assigned. This is why we don't need to wrap the $i++ in its own set of parentheses in Write-Progress above.
While I'm on the topic, a related assignment operator is += and -=:

*

*$var += 2 is shorthand for "add 2 to the value of $var"

*

*The amount to increment/decrement by can be any number

Unlike ++ and --, you would need to squeeze this expression to return its value at the time of assignment as you would when assigning any other variable a value.


text:
Q: Process Builder: Is "evaluate a record multiple times" inherited to sub-processes? When creating a Lightning Process, you can choose the flag "Allow process to evaluate a record multiple times in a single transaction". If a process A invokes a sub-process B, does the setting on process A affect process B?
When this recursion flag is active on process A but not on process B, or the other way around, how does process B behave?
(All process work on the same object.)

A: When you have a sub-process, it will get triggered when the main process calls it. So, if your main process gets evaluated again, and the criteria to trigger the sub-process is still true, the sub process will fire.


text:
Q: Memory Allocation Java Anomaly I'm learning Java from a book called "Java 2: The Complete Reference".
The output according to the book is:
Total memory is: 1048568
Initial free memory: 751392
Free memory after garbage collection: 841424
Free memory after allocation: 824000
Memory used by allocation: 17424
Free memory after collecting discarded Integers: 842640
My output is:
Total memory is : 121634816
Initial free memory : 120142456
Free memory after garbage collection : 7677000
Free memory after allocation : 7635040
Memory used by allocation : 41960
Free memory after collecting discarded integers : 7677960
My problem is the above boldly mentioned part. The "initial free memory" mentioned in the output of the book is less than "free memory after garbage collection" whereas in my output "initial free memory" is way more than that of "free memory after garbage collection".
class MemoryDemo
{
    public static void main(String[] args)
    {
        Runtime r = Runtime.getRuntime();
        long mem1, mem2;
        Integer someInts[] = new Integer[1000];

        System.out.println("Total memory is : " + r.totalMemory());

        mem1 = r.freeMemory();
        System.out.println("Initial free memory : " + mem1);

        r.gc();
        mem1 = r.freeMemory();
        System.out.println("Free memory after garbage collection : " + mem1);

        for(int i = 0; i < 1000; i++)
            someInts[i] = new Integer(i);

        mem2 = r.freeMemory();
        System.out.println("Free memory after allocation : " + mem2);

        System.out.println("Memory used by allocation : " + (mem1 - mem2));

        for(int i = 0; i < 1000; i++)
            someInts[i] = null;

        r.gc();
        mem2 = r.freeMemory();
        System.out.println("Free memory after collecting discarded integers :" + mem2);
    }
}

I need explanation for this bit and I'm attaching a link for downloading the book in the description. The code is on 406 page of book.
http://iiti.ac.in/people/~tanimad/JavaTheCompleteReference.pdf

A: The memory size of a Java Virtual Machine is not a fixed quantity.  You can set it at JVM startup.  The default setting may vary from implementation to implementation and from version to version.  The default may well depend on the size of the actual computer memory.

A: This is not an error or a mistake. Your computer has more memory than the author of the books computer had at the the time the book was written.


text:
Q: Split "" in a str py so i got this question and it´s I have a str like this:
"Factura,FE8868""Valor,795,000.00,850,000.00,140,000.00,1,450,000.00""Total,3,235,000.00""CECO,101,0,111,105""PLANILLAS,21999/21300/21304/23975/23946/25706/25714/23966/23977/23913/23941"

And what i want to split every "" to get sometime like this: (A variable for each split result)
n1 = "Factura,FE8868"
n2 = "Valor,795,000.00,850,000.00,140,000.00,1,450,000.00"
n3 = "Total,3,235,000.00"
n4 = "CECO,101,0,111,105"
n5 = "PLANILLAS,21999/21300/21304/23975/23946/25706/25714/23966/23977/23913/23941"

Note, if i try to declarate a variable with the whole str before split it, get an error due a variable is var = "some in here" and this one would looks like var = " "some""thing""here" "
How could i do it?

A: A few ways you can achieve this.
Use single quotes: ' (assuming you don't have any ' in the string itself)
var = '" "some""thing""here" "'

Use triple-quotes (either ''' or """)
var = """"" "some""thing""here" """"

You can also do this by escaping " with \" when they're part of the string (but probably the least aesthetic solution):
var = "\" \"some\"\"thing\"\"here\" \""

data = '"Factura,FE8868""Valor,795,000.00,850,000.00,140,000.00,1,450,000.00""Total,3,235,000.00""CECO,101,0,111,105""PLANILLAS,21999/21300/21304/23975/23946/25706/25714/23966/23977/23913/23941"'

# split('"') on the original string does not result in
# what you want based on your question (e.g. leading " is
# considered a 'split' that ends up being an empty string
# Because the string you gave us begins with a leading "
# and ending ", one way to do what you want is to split
# and then remove any empty fields in the resulting split

n1, n2, n3, n4, n5 = [i for i in data.split('"') if i]

print(n1)
print(n2)
print(n3)
print(n4)
print(n5)

A: First, when you write your code, use single quotes when declaring the string. That way, the double quotes in the string won't make python thing the string has finished.
Then you can split your string easily. Try this:
s = '"Factura,FE8868""Valor,795,000.00,850,000.00,140,000.00,1,450,000.00""Total,3,235,000.00""CECO,101,0,111,105""PLANILLAS,21999/21300/21304/23975/23946/25706/25714/23966/23977/23913/23941"'
s.split('""')


text:
Q: SQL error: Invalid identifier I am an SQL rookie and I would very much appreciate some assistance on this rather basic issue.
select comp_table.*
from (select column_1,avg(column_2) as "avg"
      from table_1, group by column_1) comp_table

→ returns correct records with 2 columns named column_1 and avg
But if I change to:
select comp_table.avg
from (select column_1,avg(column_2) as "avg"
      from table_1, group by column_1) comp_table

→ returns Error: Invalid identifier "avg"
The thing is I only need to select the avg column, so I cannot do select comp_table.*. Can you guys please help?
Also, if you could kindly provide some tuning tips for the query, that would be awesome.

A: When the column name is not enclosed in "double quotes", the name is normalized to uppercase; therefore, you were asking for column "AVG", whereas the column name is actually "avg":
select comp_table."avg"
from (select column_1,avg(column_2) as "avg"
  from table_1, group by column_1) comp_table

A: What database server are you using?  AVG is a built-in function in all the ones I know of, so you would need to escape it correctly - which depends on database server.  In MS SQL Server it's [avg]

A: I don't know which DBMS you're using, but some will get upset that you are using .avg (because avg is reserved) and require you to escape it.
Try changing it from avg to average, just as a test:
SELECT comp_table.average
FROM (SELECT column_1, avg(column_2) as average
      FROM table_1, GROUP BY column_1) comp_table


text:
Q: Invalid latlng object - React Leaflet   const [geoData, setGeoData] = useState([]);

  useEffect(() => {
    (async () => {
      const forGeoCode = await axios(
        "https://api.opencagedata.com/geocode/v1/json?q=United%20States&key={accessToken}&language=en&pretty=1"
      );
      setGeoData(forGeoCode.data.results[0].geometry);
    })();
  }, []);
  console.log(geoData.geometry);
  return (

      <Map center={[52.6376, -1.135171]} zoom={12}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='© OpenStreetMap contributors'
        />
        <Marker position={[geoData.lat, geoData.lng]} />
      </Map>

The above code gives me the following error: Error: Invalid LatLng object: (undefined, undefined)
console.log prints in longitude and latitude but i'm still getting error.
Expected behavior: Take United States as input and return its longitudes and latitudes and plot it on map

A: You initialize geoData like array empty []
You should initialize:
const [geoData, setGeoData] = useState({lat:null,lng:null});

And in return of your component, you should change that Marker only paint when geoData lat and lng are different to null (it would be when you receive data in response axios):
return (

      <Map center={[52.6376, -1.135171]} zoom={12}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='© OpenStreetMap contributors'
        />
        {geoData.lat && geoData.lng && <Marker position={[geoData.lat, geoData.lng]} />}
      </Map>

And in useEffect I recommend you to use promise with then and catch to improve user experience. Only in then you must to use setGeoData and overwrite properties lat and lng
useEffect(() => {
      axios.get(
        "https://api.opencagedata.com/geocode/v1/json?q=United%20States&key={accessToken}&language=en&pretty=1"
      ).then(response => {
       // I expect in response object geometry, change by the correct route
       setGeoData(response.data.geometry);
      }).catch(err => {
        console.log("error",err);
      });
  }, []);

-------- NEXT QUESTION --------
If you want to edit styles of map.
As you can see in docs in React-Leaflet: Link here
You can add props like className or style.
The result it would be
<Map style={{width:"400px",height:"600px"}}>
...

A: interface Coords {
  lat: number;
  lng: number;
}

const [geoData, setGeoData] = useState<Coords>({
    lat: 52.6376,
    lng: -1.135171,
  });

You need to initialize the values of lat and lng. Hope this helps. thank you.


text:
Q: getting a keyerror 'item' i got an issue with BeautifulSoup
Traceback (most recent call last):
  File "C:\Users\Милена\Documents\html\pricetracker bot\main.py", line 24, in <module>
    price=soup.select_one('div[class="current-price"]')['item']
  File "C:\Users\Милена\AppData\Local\Programs\Python\Python39\lib\site-packages\bs4\element.py", line 1406, in __getitem__
    return self.attrs[key]
KeyError: 'item'

I am totally new to python and telegram-bot, so I don't know what issues I have. Did I make a mistake in the code below or with div itself?
from dotenv import load_dotenv
load_dotenv()

import os
import requests
from bs4 import BeautifulSoup

BASE_URL='https://www.sulpak.kz/'
TOKEN=os.getenv('TOKEN')
CHAT_ID=os.getenv('CHAT_ID')
TELEGRAM_API_SEND_MSG=f'https://api.telegram.org/bot{TOKEN}/sendMessage'

items = [
    'g/noutbuk_asus_zenbook_um431da_am020t_r785uw_90nb0pb3_m01810_62_1747',
    'g/smartfon_samsung__galaxy_note20_gray_sm_n980fzagskz_77_2514'
]

for item in items:
    url=BASE_URL + item
    r = requests.get(url)
    soup=BeautifulSoup(r.text, 'html.parser')

    name = soup.select_one('h1[class="product-container-title"]').get_text()
    price=soup.select_one('div[class="current-price"]')['item']

    data = {
        'chat_id': CHAT_ID,
        'text': f'*${price}*\n[{name}]({url})',
        'parse_mode': 'Markdown'
    }

    r = requests.post(TELEGRAM_API_SEND_MSG, data=data)

A: Your problem is likely due to soup.select_one('div[class="current-price"]') not returning an object that contains an item with the key item.  So when you apply ['item'] to that return value, you are getting that error.  I'd recommend that you assign the value soup.select_one('div[class="current-price"]') to a variable, and then check first to see if it contains the key item, and then do whatever is appropriate in the case where it does not. For example:
priceDiv=soup.select_one('div[class="current-price"]')
if 'item' not in priceDiv:
    ... do here whatever is appropriate when `item` is not found ...
price = priceDiv['item']


text:
Q: Asynchronous Powershell Script I'm trying to run a function in the background. This function needs to wait a period of time always. I've tried to solve the problem with start-job. But without success (the logs are empty).
My Function
Start-Job { a1 }
function a1()
{
  $timer = [diagnostics.stopwatch]::startnew()
  while ($timer.elapsed.totalseconds -lt 30)
  {
    writelog "TESTTESTTEST" $timer.elapsed.totalseconds
    start-sleep -seconds 5
  }
  $timer.stop()
}

The log
function writelog([string]$func, [string] $Message, [string] $Value)
{
  $loggingpath = $LogPath+(Get-Date -displayhint date -Format yyyyMMdd)+".txt"
  Add-Content -Path $loggingpath -Value (" ")
  Add-Content -Path $loggingpath -Value ("Date:" + (Get-Date))
  Add-Content -Path $loggingpath -Value ("Function:" + ($func))
}

If I run the code with out start-job everything is working fine!

A: Start-Job runs the passed script block in a separate worker process. In this case that process does not have a definition of a1. You need to define both a1 and writelog either in a referenced script (file) or inline in the script block (along with any other dependencies like $LogPath).
Eg. the following does add to the file:
$j = start-job { Add-Content -Path "$env:TEMP\JobDemo.txt" -value "A message at $([datetime]::Now)" }
$j | wait-job
$j | Receive-Job
Get-Content -Path "$env:TEMP\JobDemo.txt"


text:
Q: Python Fabric capture interactive dialog output I would like to use Fabric to set the password for a user on a remote server.
Let's say I have a user named 'john' and I want to set a default password '123' for him.
Ideally I would like to do this:
run 'passwd john' on remote machine
detect when linux prompts for 'Enter new UNIX password:'
automatically enters the password
detect when linux prompts for 'Retype new UNIX password:'
automatically reenters the password

This is what I have tried:
result = run('passwd {}'.format(username))

The problem with this statement is that 'result' does not capture when Linux prompts for entering password. It only returns after the passwords are entered.
Is there a way to automate interactive prompts like this?

A: You can use fexpect for interactive prompts.

A: you can use prompts
password = '123'
with settings(prompts={
                  'Enter new UNIX password: ': password,
                  'Retype new UNIX password: ': password
              }):
    run('passwd {}'.format(username))


text:
Q: Fill a null value by finding similar strings, pandas I want to create a neural network that finds video game sales, using this dataframe:https://www.kaggle.com/gregorut/videogamesales
Is there a way to fill the null values of the Year column by finding similar named games from the Name column and putting their corresponding year to the null values.
That is the head of the dataframe
                      Name           Platform       Year            Genre       Publisher

     1                Wii Sports        Wii         2006.0          Sports      Nintendo
     2         Super Mario Bros.        NES         1985.0          Platform    Nintendo
     3            Mario Kart Wii        Wii         2008.0          Racing      Nintendo
     4         Wii Sports Resort        Wii         2009.0          Sports      Nintendo
     5  Pokemon Red/Pokemon Blue        GB          1996.0      Role-Playing    Nintendo

     NA_Sales    EU_Sales    JP_Sales    Other_Sales         Global_Sales

        41.49       29.02       3.77            8.46                82.74
        29.08        3.58       6.81            0.77                40.24
        15.85       12.88       3.79            3.31                35.82
        15.75       11.01       3.28            2.96                33.00
        11.27        8.89       10.22           1.00                31.37

A: My suggestion is use 'K-Nearest Neighbour' algorithm over your dataframe column name 'Year' and 'Name'. It will fill null values in 'Year' column.

A: You can use Word2Vec for creating vectors for word embedding similarity. Then, you can make a multi-class prediction for  Year column using those word embedding vector.


text:
Q: css hover img not work on other class opacity I've this HTML file. I'm trying to implement :hover property so when I pass over .linux-face element the .info element set opacity to 0.
I'm trying to get out of this for about 30 minutes. I've also try to map :hover to other class but nothing seems working.
<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@300;700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="main.css" />
        <title> Linus Torvald aka Linux </title>

 Linus Torvald

Linus Torvald smiling face :)

  Hello, World!

That's my scss file:
#main {
    display: flex;
    justify-content: center;
}
.main-title {
    font-family: 'Josefin Sans', sans-serif;
}

.linux-face {
    &:hover {
        .info{
            opacity:0;
    }
}}

If I try something like
.linux-face:hover {
    opacity: 0;
}

the hover effect on .linux-face works fine.
Also this work fine
.container:hover {
    .info {
        opacity: 0;
    }
}

A: .linux-face {
    &:hover {
       .info {
          opacity: 0;
       }
    }
 }

gets compiled into
.linux-face:hover .info { opacity: 0; }

but .linux-face is an img element so you are actually targeting a nested element inside the image which clearly doesn't exist —
if your goal is to change the opacity of the .info element when you hover the image then you can't simply do it with the given markup: the most you could do is .image-section:hover + .info { opacity: 0 } so it will work if you hover either the image or the caption paragraph.

As a side note you could use a more meaningful and semantic markup

Linus Torvald smiling face


text:
Q: An isomorphism between the fields $\mathbb{Q}(e)$ and $\mathbb{Q}(\pi)$ How can i prove that $\mathbb{Q}(e)\cong \mathbb{Q}(\pi)$?
Also, is this isomorphism a valid one?
We have that $\mathbb{Q}(e)=\left \{ \cfrac{f(e)}{g(e)} \mid f(x),g(x)\in\mathbb{Q}[x], g(e)\neq0 \right \} $ and $\mathbb{Q}(\pi)=\left \{ \cfrac{f(\pi)}{g(\pi)} \mid f(x),g(x)\in\mathbb{Q}[x], g(\pi)\neq0 \right \} $.
Then  I consider the homomorphism $\phi:\mathbb{Q}(e)\to\mathbb{Q}(\pi)$, where $\cfrac{f(e)}{g(e)}\mapsto \cfrac{f(\pi)}{g(\pi)}$.
The upper homomorphism is obviously surjective by the definition of the fields.
Moreover, $\ker\phi=\left \{ 0 \right \}$, because if $\cfrac{f(e)}{g(e)}\in\ker\phi$ we have that $\cfrac{f(\pi)}{g(\pi)}=0\Rightarrow f(\pi)=0$. So if $f(x)$ is a non-zero polynomial we have that $\pi$ is not transcendental over $\mathbb{Q}$, which is a contradiction and so $f(x)=0\Rightarrow  \cfrac{f(e)}{g(e)}=0$
If $\phi$ is an isomorphism, is there another proof, more general and abstract?

A: It follows easily from the definition that a number $\alpha \in \mathbb C$ is a transcendental number iff $\mathbb{Q}(\alpha) \cong \mathbb{Q}(X)$, the field of rational functions over $\mathbb{Q}$.
Therefore, $\mathbb{Q}(e) \cong \mathbb{Q}(X)\cong \mathbb{Q}(\pi) $.


text:
Q: NSMutableSet intput is not in the same order as output I have added objects into a NSMutableSet with this code:
_theQuestionsSet = [[NSMutableSet alloc]initWithObjects:@802, @229, @522, @712, @628, @84, @412, @726, @284, @699, @1765, @1754, @1528, @2230, @2005, @1494, @1348, @2132, @2040, @2183, nil];
NSLog(@"%@", _theQuestionsSet);

Why is the output not in the same order as inserted?
2013-03-28 16:41:50.178 xxxxxxxx[4011:c07] {(
412,
1754,
628,
726,
1528,
284,
1348,
84,
2005,
699,
522,
712,
1494,
2132,
2230,
1765,
2040,
802,
2183,
229
)}

A: Because it's not ordered. Use NSMutableOrderedSet if you need that.

A: Because an NSMutableSet has no order. An array is ordered; a set is not. (An ordered set sort of bridges the gap, but that's not what you're using.)
Read the fine documentation:
https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSSet_Class/Reference/Reference.html
What's the first sentence?

The NSSet, NSMutableSet, and NSCountedSet classes declare the programmatic interface to an unordered collection of objects.

Unordered. End of story.
See also my book:
http://www.apeth.com/iOSBook/ch10.html#_nsset_and_friends

You can walk through (enumerate) a set with the for...in construct, though the order is of course undefined.

The order is undefined.
(It sounds from your original question as if what you really want is an NSMutableArray that you then shuffle. I have code for that! But that would be a different question.)

A: NSMutableSet order is not maintained. Use NSMutableOrderedSet or NSMutableArray to maintain order


text:
Q: Catching the TERM signal in Gevent based applications I wrote a simple daemon in Python which is based on Gevent. The daemon needs to do some cleanup before it exists, so it is necessary that it can handle the TERM signal, preform its cleanup and exit gracefully. In a single threaded daemon which is not based on Gevent, I used the Python's signal module to set a signal handler for the TERM signal. The signal handler throws an user defined exception which is called TermSignal. The main thread of the daemon can just catch the TermSignal exception, do its cleanup and exit.
This solution did not work as expected when I tried to implement it in a daemon based on Gevent. The daemon has a main greenlet that calls joinall on the workers greenlets. the joinall call is wrapped in try/except block which catches the KeyboardInterrupt, which allows the daemon to preform its cleanup when it runs without daemonizing. However, when I implemented the solution above and sent a TERM signal to the process, I could see in the console window that one of the worker greenlets raised the TermSignal exception instead of the main greenlet. This uncaught exception did not proagate to the main greenlet, despite the face that I called joinall with raise_error parameter set to True. The result was that one of the worker greenlets crashed due to the exception, but the daemon did not exit at all.

A: After I did some searching I found the solution. As mentioned here, Gevent's monkey patching does not patch Python's built-in signal.signal function. In order for my solution to work, the main greenlet must call gevent.signal instead of signal.signal in order to set the handler. Also, gevent.signal expects handler functions which accept no arguments, unlike signal.signal which expects handler functions which accept 2 arguments. Since I don't care about these arguments anyway, I changed my term handler to look like this:
def _term_handler(*_):
    raise TermSignal()

So that the same term handle can be used in Gevent application and in regular Python applications. Although the same handler can be used in both cases, it needs to be set by the appropriate function (signal.signal or gevent.signal)


text:
Q: Creating a dynamic scroll-down layout Facebook-style I'm trying to figure out how to make a non static layout like Facabook.
Basically when the user scrolls down on the activity he can't reach the end of the page because this one keep loading the videos that other users have uploaded in the past.
Something like Vines or Facebook.
I'm new to programming and a new user in stack overflow and I'd like to hear from more experienced users some suggestions/ideas or simply where to find the related material.
Deket

A: What you need is an endless scroll Listener, please take a look at this:
https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews
just add this project to yours and use it like this:
yourListView.setOnScrollListener(new EndlessScrollListener() {
        @Override
        public void onLoadMore(int page, int totalItemsCount) {

            ... your asynchTask
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            super.onScrollStateChanged(view, scrollState);
        }
    });


text:
Q: start websphere server from RAD hangs at "Server server1 open for e-business" I did the RAD set up recently and trying to start websphere server.
In the log, it hangs at the following line and get terminated after timeout:
Server server1 open for e-business

A: Thanks for the help.
In my case, I did following configuration which solved the issue and server started.
Double click on the server (in the servers tab).
In Server connection types and administrative ports select Automatically determine connection settings and save the changes.

A: Your workspace folder/name could be the issue.
the WAS installation itself. When moved it to C:\was8 everything started to work properly. The default puts it into c:\Program Files... and that was hanging at 23%
a. Please use websphere jre to replace sun hotspot vm to launch the eclipse, like below setting in the eclipse.ini
-vm
D:/IBM/WebSphere/AppServer/java/bin/javaw.exe

b. Please make sure there is not a specail character (like 23%) in the websphere path or eclipse workpsace.

A: Copy the jar com.ibm.ws.orb_8.5.0.jar from C:\IBM\WebSphere\AppServer\runtimes
to C:\development\endorsed and in eclipse.ini add this just JVM param (under -vmargs)
-Djava.endorsed.dirs=C:\development\endorsed


text:
Q: SQL Server cancel rounding the result of multipication I'd appreciate if you could look into the following SQL code and tell me how to make SQL server NOT to round the result of the multipication of tje 4th select column:
    select  --tmp1.[Session.Call_TYPE_Assigned] CR,
            tmp2.cnt_match / cast(tmp1.cnt as float)   as precision,
            tmp1.cnt as cnt,
            tmp2.cnt_match / cast(tmp1.cnt as float) * tmp1.cnt

    from
    ( select [Session.Call_TYPE_Assigned],COUNT(*) as cnt from
    dbo.CEA_CR CEA_CR
    where CEA_CR.cycle = '4' and CEA_CR.version = '1'
    group by [Session.Call_TYPE_Assigned] )  as tmp1
    ,
    (select [Session.Call_TYPE_Assigned],COUNT(*) as cnt_match from
    dbo.CEA_CR CEA_CR
    where  [Session.Did_Call_Type_happen_on_this_call]= 'Yes' and CEA_CR.cycle = '4' and CEA_CR.version = '1'
    group by [Session.Call_TYPE_Assigned])  tmp2
    where tmp1.[Session.Call_TYPE_Assigned] = tmp2.[Session.Call_TYPE_Assigned]

the result set look like this
0.666666666666667
3
2
while 2 is not the product of 0.6 * 3
thanks

A: I would think either:
convert(float,tmp2.cnt_match / cast(tmp1.cnt as float) * tmp1.cnt)

as the last line of the select or
convert(float,[precision] * tmp1.cnt)

as the last line of the select might work.


text:
Q: How to secure other controller using FOSUserbundle? I'm trying to study the FOSUserBundle. I follow the steps of their documentation (link) and I successfully created a login form and registration. Now, I'm creating another controller name TodoController and I want to secure that TodoController. It needs the user to login first before they show the page of todo. How can I secure the TodoController?

A: FOSUserBundle only extend the Symfony security layer, but all other Symfony security stuff remains the same, so you can use the default access control from symfony security
access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN }

You will find it mentioned in the link you provided, but you can read more about it here http://symfony.com/doc/current/security/access_control.html
Or if you want something more flexible and more powerful you can take a look at JMSSecurityExtraBundle http://jmsyst.com/bundles/JMSSecurityExtraBundle/1.2/annotations
Hope this helps,
Alexandru Cosoi


text:
Q: Ресурсы приложения на Андроиде Недавно обратил внимание на ресурсоемкость приложения на Андроиде. Даже простейшее приложение типа "Hello, Android" занимает мегабайты. Откуда набегает эта масса?
$ procrank

280   15304K   15304K    2941K    1772K  com.example.hello

A: Память выделяется под кучу (heap) - динамическая память, jvm резервирует определенное ее количество, чтобы реже приходилось ее выделять, т.к. процедура сия достаточно ресурсоемкая. Кроме того, android и linux соответственно резервирует процессу часть оперативной памяти, которая используется в качестве кэша этого процесса (доступ быстрее чем к диску).
Показанные цифры не означают, что памяти на самом деле используется N, они лишь гарантируют, что памяти не используется больше чем N.


text:
Q: Can you help me removing index.php in Rewrite Rule? Here's my code in .htaccess
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^([0-9]+)/$ index.index?pm=$1 [L]

It doesnt work using this link:
http://localhost/display/1001

but it does when you add ? before the number
http://localhost/display/?1001

A: Your question is unclear, you did not provide enough information about your actual situation and what you are trying to achieve. So we have to do a bit of guess work here and hope that this is what you are looking for:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?display/(\d+)/?$ /index.php?pm=$1 [END,QSA]

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.
This rule will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.
And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).


text:
Q: XAML icons in menu items look shifted I would like to use Visual Studio 2022 Image Library in my project. The one that the VS2022 IDE uses (surprise!). But when I add an icon to a menu item, it doesn't look as pretty as it does in a VS menu:
<MenuItem.Icon>
  <Rectangle Width="16" Height="16">
    <Rectangle.Fill>
      <DrawingBrush>
        <DrawingBrush.Drawing>
          <DrawingGroup>
            <GeometryDrawing Brush="{DynamicResource canvas}" Geometry="F1M16,16H0V0H16Z" />
            <DrawingGroup Opacity="{DynamicResource cls-1}">
              <GeometryDrawing Brush="{DynamicResource light-defaultgrey-10}" Geometry="F1M14.5,4.5v10H3.5V7.95A4.984,4.984,0,0,0,8,3a4.966,4.966,0,0,0-.254-1.5H11.5Z" />
              <GeometryDrawing Brush="{DynamicResource light-defaultgrey}" Geometry="F1M15,4.5v10l-.5.5H3.5L3,14.5V8a4.988,4.988,0,0,0,1-.1V14H14V5H11V2H7.9a4.968,4.968,0,0,0-.321-1H11.5l.354.146,3,3Z" />
            </DrawingGroup>
            <GeometryDrawing Brush="{DynamicResource light-yellow}" Geometry="F1M3,2,3,0H4L4,2l-.5.5Zm.5,2.5L3,5V7H4V5Zm1-1L5,4,7,4V3L5,3Zm-2,0L2,3,0,3V4L2,4Zm1.708-.7h.708L6.328,1.378,5.62.671,4.208,2.088ZM2.792,4.206H2.085L.673,5.623l.707.706L2.793,4.913Zm1.414,0v.708L5.623,6.328l.706-.708L4.913,4.208ZM2.794,2.792V2.085L1.378.673.671,1.38,2.088,2.793Z" />
          </DrawingGroup>
        </DrawingBrush.Drawing>
      </DrawingBrush>
    </Rectangle.Fill>
  </Rectangle>
</MenuItem.Icon>

Compare the IDE's and my renders (scaled):

As you can see, my icons seem to be shifted horizontally by a fraction of a pixel. Perhaps it's just because Microsoft guys used PNG instead of XAML.
I've tried adding SnapsToDevicePixels wherever possible, but it doesn't change anything. Obviously, specifying a correct offset will be enough for the solution, but I don't know that offset. And I don't want to look through the Magnifier every time I add a new icon to make sure I need to subtract a hundredth of a pixel from the offset I guessed.
Could you suggest an elegant solution to removing the subpixel effect when rendering these XAML icons?


text:
Q: Printer not printing but recognized by computer I currently have an hp laserjet 1022 on my ubuntu 14.04. When I tried to print from pdf is said usr/lib/cups/backend/hp not available. Is there a way to fix this?

A: The HP website does not list Linux as an available operating system for the HP 1022.  You may be able to use it with some applications but some may give problems like the one you are experiencing with PDF file printing.
If you can print from Libreoffice with the current printer setup, just import it into Libroffice.  The file will be imported as an image file and can only be saved in an image file format, but you will be able to print without the need to invest in a PDF file conversion program like Able2Extract (7 day free trial thru Software Center).


text:
Q: How to append multiple entries to JSON Array in MySQL? I am using MySQL 8 and trying to update JSON data type in a mysql table
My table t1 looks as below:
# id    group   names
1100000 group1  [{"name": "name1", "type": "user"}, {"name": "name2", "type": "user"}, {"name": "techDept", "type": "dept"}]

The JSON format has two types - user and dept
Now, I have a list of users userlist as below:
SET @userlist = '["user4", "user5"]';

I want to append @userlist to the JSON Array:
UPDATE t1 SET names = JSON_ARRAY_APPEND(names, '$', JSON_OBJECT('name', @userlist, 'type', 'user'))
WHERE `group` = 'group1';

The query is working but it is incorrectly adding data as below:
[{"name": "name1", "type": "user"},
{"name": "name2", "type": "user"},
{"name": "["user4", "user5"]", "type": "user"}
{"name": "techDept", "type": "dept"}]

Desired Output:
[{"name": "name1", "type": "user"},
{"name": "name2", "type": "user"},
{"name": "user4", "type": "user"},
{"name": "user5", "type": "user"},
{"name": "techDept", "type": "dept"}]

A: UPDATE t1
JOIN ( SELECT JSON_ARRAYAGG(JSON_OBJECT('name', username, 'type', 'user')) userlist
       FROM JSON_TABLE (@userlist,
                        '$[*]' COLUMNS (username VARCHAR(255) PATH '$')) jsontable ) jsontable
SET t1.names = JSON_MERGE_PRESERVE(t1.names, jsontable.userlist)
WHERE t1.`group` = 'group1';

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=da25f6643c623d197a220931489864e2


text:
Q: Why Plot3D shows differently with almost the same data I really can't understand this.
I wrote two functions, one with Compile called funcom, one with librarylink to link a fortran subroutine called funcfortran. And they do exactly the same thing! So I Plot the result first
plotfor=Plot3D[funcfortran[w, 0.06, -1, 1, 1, \[Pi]/2., 2., 3., ky], {w, 0,
  10}, {ky, -0.1, 0.1}, PlotRange -> All, MaxRecursion -> 7,
 Mesh -> All]

This is output from topview

Well, this may not seem that wrong, But look at the plot result of funcom with exactly the same parameter
plotcom=Plot3D[funcom[w, 0.06, -1, 1, 1, \[Pi]/2., 2., 3., ky], {w, 0,
      10}, {ky, -0.1, 0.1}, PlotRange -> All, MaxRecursion -> 7,
     Mesh -> All]

different !!!
They contains almost the same point data, this can be verified after we extract the data and compared the difference
Sort[DeleteDuplicates@
   Abs@Flatten[
     Cases[%58, x_GraphicsComplex :> x[[1]]][[1]] -
      Cases[%66, x_GraphicsComplex :> x[[1]]][[1]]], Greater][[1 ;; 3]
 ]

The top three biggest differen
{8.00339*10^-8, 7.99922*10^-8, 7.99703*10^-8}

If I plot it on larger region, the plot of funcfortran is unacceptable, see following and corresponding Mesh->All version
Plot3D[funcfortran[w, 0.06, -1, 1, 1, \[Pi]/2, 2, 3., ky], {w, 0,
  10}, {ky, -\[Pi], \[Pi]}, PlotRange -> All, MaxRecursion -> 7]

and this is what funcom got

Again, the point data contained in these two plot is almost the same, funcfortran contains 8260 points and funcom contains 8264 points
On the other hand, I can "stupidly" calculation funcfortran on a regular rectangular mesh, and ListPlot3D get pretty nice result.
Block[{datatmp, klist, n1, n2},
  n1 = n2 = 100;
  klist =
   Tuples[{Subdivide[-N@\[Pi], N@\[Pi], n1],
     Subdivide[-N@\[Pi], N@\[Pi], n2]}];
  datatmp =
   Flatten[Outer[
     funcfortran[#1, 0.005, -1., 1., 1., \[Pi]/2., 2., 3., #2] &,
     Subdivide[0., 10., n1], Subdivide[-N@\[Pi], N@\[Pi], n2]], 1];
  data = Join[klist, Partition[datatmp, 1], 2]];

ListPlot3D[data, PlotRange -> All]

So, strange things, it seems that funcfortran has no problem, because ListPlot3D gives good result. But why Plot3D fails?

update
m_goldberg suggested that this maybe due to loss of precision of my fortran routine. But I want to demonstrate, How Plot3D is defective.
I choose a defective parameter region, and plot it
test = Plot3D[
  iterateG[w, 0.06, -1, 1, 1, \[Pi]/2, 2, 3., ky], {w, 2, 3}, {ky, 0,
   0.5}, PlotRange -> All, MaxRecursion -> 7, Mesh -> None,
  PlotPoints -> 50]

it outputs

To notice the two strange dark stripes.
Now we extract the data contained in test plot, and use ListPlot3D. As m_goldberg had pointed out, there is default interpolation, we can turn it off using InterpolationOrder -> 1
ListPlot3D[Cases[test, x_GraphicsComplex :> x[[1]]][[1]],
 InterpolationOrder -> 1, Mesh -> None]

outputs

It is smooth!! And this time, same data, different behaviour between Plot3D and ListPlot3D!!

update
I attached a zip (download here onedrive). Since librarylink is quite difficult to work with. So I have packed everything: .dll for win, .so for linux, source .f90, .nb etc. Hope everyone extract and open the .nb file should have no problem running it. Thank you for testing.

Summary
The bug hunting is over. The defective plot is due to my fortran code and off course my bad fortran coding. I wrote cmplx instead of dcmplx which cause the rounding of w parameter, loss of precision and finally the weird plot3d.
Many thanks for Jason B's kind help, I learned a lot of skill and insight for tracing such kind of bug. Also I recall that m_goldberg is the first one correctly pointed out that it must be due to loss of precision. I reget not pay enough attention to this. Finally thank all people who have concerned with this post and tried to help me.

A: Source of the problem (possibly)
Here is a clear indication that your Fortran library and the Mathematica function are behaving in fundamentally different ways.  I noticed the apparent high frequency oscillations in the difference functional, so I decided to see exactly how quickly they oscillate,
Plot[funcfortran[w, 0.06, -1.0, 1.0, 1.0, N[π/2], 2.0, 3., 0.2] -
    funcom[w + 0.06*I, π/2., 3., .2], {w, 2.75 - #, 2.75 + #},
   PlotPoints -> 800,
   ImageSize -> 400] & /@ {.001, .0001, .00001, .000001}

So now we zoom in and plot them together on this scale,
Plot[{funcfortran[2.75 + dw, 0.06, -1.0, 1.0, 1.0, N[π/2], 2.0,
   3., 0.2],
  funcom[2.75 + dw + 0.06*I, π/2., 3., .2]},
 {dw, -.000001, .000001},
 PlotPoints -> 200,
 ImageSize -> 400,
 PlotLegends -> {"Fortran", "Mathematica"}]

So somewhere, Fortran is doing some kind of rounding.  Perhaps you have some number defined with single precision?  Probably not that simple or you would have caught it, but basically as you vary w in increments of the order $10^{-7}$ then the Fortran function does not vary smoothly.  This is not the case for the ky parameter.
I would next check whether you get this behavior from Fortran directly, without using Mathematica.  If so, the problem is in your code there.  If not, it must have to do with the library linking function.
As I try to show below, I think it is this nonlinear behavior in the Fortran function that leads Mathematica to plot it incorrectly when using the adaptive grid created by ListPlot3D.  I assume that Plot3D is trying to come up with derivatives to better plot, but at some points along the w axis the derivative is infinite.
You point out that Plot adaptively samples the plot region, so let's just extract the points that you get for both functions,
fortranlist =
  Reap[Plot3D[
     Sow[{w, ky, funcfortran[w, 0.06, -1, 1, 1, π/2, 2, 3., ky]}];
      funcfortran[w, 0.06, -1, 1, 1, π/2, 2, 3., ky], {w, 0,
      10}, {ky, -π, π}, PlotRange -> All, MaxRecursion -> 7,
     PlotPoints -> 100]][[2, 1]];
funcomlist =
  Reap[Plot3D[Sow[{w, ky, funcom[w + 0.06*I, π/2., 3., ky]}];
     funcom[w + 0.06*I, π/2., 3., ky], {w, 0,
      10}, {ky, -π, π}, PlotRange -> All, MaxRecursion -> 7,
     PlotPoints -> 100]][[2, 1]];
fortranlist[[2]]
fortranlist = Delete[evalcoords, 2];

That last line is necessary because the second element of fortranlist looks like this,

For those who want to weigh in, but don't want to evaluate the Fortran library function, you could just download the lists above via:
funcomlist=Import["https://gist.githubusercontent.com/anonymous/34581877899db27e1cf4/raw/409c85ce8d34cd8f90344cbd0291c08f29c68d9e/funcom_pts.dat","Table"];
fortranlist=Import["https://gist.githubusercontent.com/anonymous/1d377c32f675847839d6/raw/00f79e303e5ec787107082516bffe3148af8380e/fortran_pts.dat","Table"];

But we can now check that the adaptive grid for the two functions is identical,
funcomlist[[All, ;; 2]] == fortranlist[[All, ;; 2]]
(* True *)

And we can plot the two lists and their differences
ListPlot3D[#, ImageSize -> 450, PlotRange -> All] & /@ {funcomlist,
  fortranlist,
  Transpose[{funcomlist[[All, 1]], funcomlist[[All, 2]],
    funcomlist[[All, 3]] - fortranlist[[All, 3]]}]}

And here is the density of grid points,
ListPlot[funcomlist[[All, ;; 2]]]

What I notice is that the regions where the differences between the function is largest is also the region with the highest density of grid points.  So in that region, Mathematica is trying to get many points so it can get a handle on the curvature in that region.  The Fortran function is not behaving well there, but this misbehavior is at a relatively small scale.  But the scale isn't that small.  The average value for the function is on the order of .1, and the differences are a factor of $10^{-6}$ smaller than that, but $10^{-6}$ is a good deal larger than machine precision.   So Plot3D is trying to get a handle on the higher order derivatives in that region, and isn't doing such a great job.
Why are there such large differences between the functions?  I'm not going to check through your Fortran code, but somewhere it has a difference.
So in this case, the adaptive sampling is working against you.  It is preferentially sampling a region where the precision of the Fortran function is less than optimal.  No amount of increasing MaxRecursion or PlotPoints will fix this, because they will just increase the sampling in that region.
Another point is that, at least in version 10, the interpolation algorithms for plotting functions like ListContourPlot, ListPlot3D, etc, do a much better job when given a rectangular grid than they do when given a list of tuples like {x, y, f[x, y]}.  See my question here.  And all Plot3D seems to do with the data it generates is to give it to ListPlot3D.  So you already know that you get a much better plot simply from creating a list and plotting it, but I would suggest not structuring that list in the form of tuples, but instead as a grid.
ListPlot3D[
 Table[funcfortran[w, 0.06, -1, 1, 1, π/2, 2, 3.,
   ky], {ky, -π, π, .05}, {w, 0, 10, .1}],
 DataRange -> {{0, 10}, {-π, π}}]

It produces a better plot than Plot3D, and does it faster.  I'd be interested in hearing what @user21 thinks of this issue, I believe he works directly with the underlying functions here.
Edit
To your final point, I don't think that Cases is giving you every point that is plotted by Plot3D.  Consider this:
fortranlist2 = Reap[

    fortranplot =
      Plot3D[Sow[{w, ky,
         funcfortran[w, 0.06, -1, 1, 1, π/2, 2, 3., ky]}];
       funcfortran[w, 0.06, -1, 1, 1, π/2, 2, 3., ky], {w, 2,
        3}, {ky, 0, 0.5}, PlotRange -> All, MaxRecursion -> 7,
       Mesh -> None, PlotPoints -> 50];
    ][[2, 1]];
fortranlist2 = Delete[fortranlist2, 2];
fortranlist2b = Cases[fortranplot, x_GraphicsComplex :> x[[1]]][[1]];

fortranlist2 was generated while plotting, using the Reap and Sow method, while fortranlist2b was generated using Cases off of the graphics object.  We can see that there is a lot more information in the first one,
Length /@ {fortranlist2, fortranlist2b}
(* {10337, 2584} *)

They both seem to conform to an almost rectangular grid, but clearly Plot3D corresponds to the data in the Reap and Sow method,
{fortranplot, ListPlot3D[fortranlist2, Mesh -> None],
 ListPlot3D[fortranlist2b, Mesh -> None]}

If you evaluate the differences between the Mathematica and Fortran functions at the grid points defined above, then you see where your stripes come from
diff = {#1, #2,
     funcfortran[#1, 0.06, -1, 1, 1, π/2, 2, 3., #2] -
      funcom[#1 + 0.06*I, π/2., 3., #2]} & @@@
   fortranlist2[[All, ;; 2]];

ListPlot3D[diff]


text:
Q: How to control formatting of pipe format tables in bookdown, such as striping? Many thanks to Rstudio for the visual Rmarkdown editor.  I am using it to generate and preview bookdown content.  When I insert a table, it generates a pipe format table.  However I want to remove the alternate row shading which kable does by default.  There is plenty of documentation on using function kable_styling but I cannot use that - there is no object for the table, it is autogenerated in the visual editor.  I don't really want to load it into a dataframe - that seems the wrong route.
How can I switch off row shading for pipe format tables globally or more generally modify the options for tables generated in this way via the visual Rmarkdown editor or otherwise?
A minimal section of my table looks like this.  When I knit it in Rstudio as a Rmarkdown document it appears unstriped.  I would like it stripe-free in bookdown, and ideally to control other styling of it.
+------------------+------------+
| $A=\pi.r^2$      | 1          |
+------------------+------------+
| $\sqrt{b^2-4ac}$ | 2          |
+------------------+------------+
| $\sum{1/i}$      | 3          |
+------------------+------------+

Many thanks.