text:
Q: How to relabel consul sd config to get service discovery stats based on consul metadata? This is how 2 services among many in consul look like:
    "1": {
        "ID": "1",
        "Service": "Service X",
        "Meta": {
              "country": "USA"
        },
        "Port": 0,
        "Address": "1.1.1.1",
        "Weights": {
            "Passing": 1,
            "Warning": 1
        },
        "EnableTagOverride": false
    }

    "2": {
        "ID": "2",
        "Service": "Service Y",
        "Meta": {
              "country": "CANADA"
        },
        "Port": 0,
        "Address": "2.2.2.2",
        "Weights": {
            "Passing": 1,
            "Warning": 1
        },
        "EnableTagOverride": false
    }

Each of these services has health checks.
My goal is to find all healthy services based on consul KV. Like, find all services that are "passing" in "USA", or find all "critical" services in "CANADA".
I have tried a few options, the problem I get into is that all metrics have each relabel that is mentioned in config.yaml
QUERY 1
consul_health_service_status{status="passing", instance="USA"}
OUTPUT

consul_health_service_status{check="service:1",instance="USA",job="consul",node="machine",service_id="1",service_name="Service
  X",status="passing"} 1
consul_health_service_status{check="service:2",instance="USA",job="consul",node="machine",service_id="2",service_name="Service
  Y",status="passing"} 1

QUERY 2
consul_health_service_status{status="passing", instance="CANADA"}
OUTPUT

consul_health_service_status{check="service:1",instance="CANADA",job="consul",node="machine",service_id="1",service_name="Service
  X",status="passing"} 1
consul_health_service_status{check="service:2",instance="CANADA",job="consul",node="machine",service_id="2",service_name="Service
  Y",status="passing"} 1

CONFIG
scrape_configs:
  - job_name: 'prometheus'
    static_configs:
    - targets: ['localhost:9090']

  - job_name: 'consul'
    consul_sd_configs:
      - server: 'localhost:8500'
        services: []
    relabel_configs:
      - source_labels: [__meta_consul_service_metadata_country]
        target_label: instance
      - source_labels: ['__meta_consul_address']
        separator: ';'
        target_label:  '__address__'
        replacement: 'localhost:9107'
        action: 'replace'

I would loved to see an output like:
QUERY 1
consul_health_service_status{status="passing", instance="USA"}
OUTPUT

consul_health_service_status{check="service:1",instance="USA",job="consul",node="machine",service_id="1",service_name="Service
  X",status="passing"} 1

QUERY 2
consul_health_service_status{status="passing", instance="CANADA"}
OUTPUT

consul_health_service_status{check="service:2",instance="CANADA",job="consul",node="machine",service_id="2",service_name="Service
  Y",status="passing"} 1


text:
Q: Writing to a file parallely while processing in a loop in python I have a CSV data of 65K. I need to do some processing for each csv line which generates a string at the end. I have to write/append that string in a file.
Psuedo Code:
for row in csv_data:
   processed_string = ...
   file_pointer.write(processed_string + '\n')

How can I make this write operation run in parallel such that main processing operation does  not have to include time taken for writing to file? I tried using batch writing (store n lines and then write them at the same time). But it would be really great if you can suggest me some method that can do this parallely. Thanks!
Edit: There are 65K records in a csv file. I am processing it which generate a string (multiline about 10-12). I have to write it to a file. For 65K records, getting a results with 10-15 lines each. Normally code takes 10 mins to run. But adding this file operations increses time to +2-3 mins. So if I can do it parallely without affecting code execution?
Here is the code part.
for i in range(len(queries)): # 65K runs
    Logs.log_query(i, name, version)

    # processed_results = Some processing ...

    # Final Answer
    s = final_results(name, version, processed_results) # Returns a multiline string
    f.write(s + '\n')

"""
EXAMPLE OUTPUT:
-----------------
[0] NAME: Adobe Acrobat Reader DC | VERSION: 21.005
FAISS RESULTS (with cutoff 0.63)
     id                                               name                         version   eol_date extended_eol_date                   major_version minor_version    score
1486469                            Adobe Acrobat Reader DC                    21.005.20054 07-04-2020        07-07-2020                              21           005 0.966597
 327901                            Adobe Acrobat Reader DC                    21.005.20048 07-04-2020        07-07-2020                              21           005 0.961541
 327904                            Adobe Acrobat Reader DC                    21.007.20095 07-04-2020        07-07-2020                              21           007 0.960825
 327905                            Adobe Acrobat Reader DC                    21.007.20099 07-04-2020        07-07-2020                              21           007 0.960557
 327902                            Adobe Acrobat Reader DC                    21.005.20060 07-04-2020        07-07-2020                              21           005 0.958580
 327900                            Adobe Acrobat Reader DC                    21.001.20145 07-04-2020        07-07-2020                              21           001 0.956085
 327903                            Adobe Acrobat Reader DC                    21.007.20091 07-04-2020        07-07-2020                              21           007 0.954148
1486465                            Adobe Acrobat Reader DC                    20.006.20034 07-04-2020        07-07-2020                              20           006 0.941820
1486459                            Adobe Acrobat Reader DC                    19.012.20035 07-04-2020        07-07-2020                              19           012 0.928502
1486466                            Adobe Acrobat Reader DC                    20.012.20048 07-04-2020        07-07-2020                              20           012 0.928366
1486458                            Adobe Acrobat Reader DC                    19.012.20034 07-04-2020        07-07-2020                              19           012 0.925761
1486461                            Adobe Acrobat Reader DC                    19.021.20047 07-04-2020        07-07-2020                              19           021 0.922519
1486463                            Adobe Acrobat Reader DC                    19.021.20049 07-04-2020        07-07-2020                              19           021 0.919659
1486462                            Adobe Acrobat Reader DC                    19.021.20048 07-04-2020        07-07-2020                              19           021 0.917590
1486464                            Adobe Acrobat Reader DC                    19.021.20061 07-04-2020        07-07-2020                              19           021 0.912260
1486460                            Adobe Acrobat Reader DC                    19.012.20040 07-04-2020        07-07-2020                              19           012 0.909160
1486457                            Adobe Acrobat Reader DC                    15.008.20082 07-04-2020        07-07-2020                              15           008 0.902536
 327899                                   Adobe Acrobat DC                    21.007.20099 07-04-2020        07-07-2020                              21           007 0.895940
1277732                        Acrobat Reader DC (classic)                            2015 07-07-2020                 *                            2015           NaN 0.875471

OPEN SEARCH RESULTS (with cutoff 13)
{ "score": 67.98198, "id": 327901, "name": Adobe Acrobat Reader DC, "version": 21.005.20048, "eol_date": 2020-04-07, "extended_eol_date": 2020-07-07 }
{ "score": 66.63623, "id": 327902, "name": Adobe Acrobat Reader DC, "version": 21.005.20060, "eol_date": 2020-04-07, "extended_eol_date": 2020-07-07 }
{ "score": 65.96028, "id": 1486469, "name": Adobe Acrobat Reader DC, "version": 21.005.20054, "eol_date": 2020-04-07, "extended_eol_date": 2020-07-07 }
FINAL ANSWER [OPENSEARCH]
{ "score": 67.98198, "id": 327901, "name": Adobe Acrobat Reader DC, "version": 21.005.20048, "eol_date": 2020-04-07, "extended_eol_date": 2020-07-07 }
----------------------------------------------------------------------------------------------------

"""

A:
Q : " Writing to a file parallely while processing in a loop in python ... "

A :Frankly speaking, the file-I/O is not your performance-related enemy.

"With all due respect to the colleagues, Python (since ever) used GIL-lock to avoid any level of concurrent execution ( actually re-SERIAL-ising the code-execution flow into dancing among any amount of threads, lending about 100 [ms] of code-interpretation time to one-AFTER-another-AFTER-another, thus only increasing the interpreter's overhead times ( and devastating all pre-fetches into CPU-core caches on each turn ... paying the full mem-I/O costs on each next re-fetch(es) ). So threading is ANTI-pattern in python (except, I may accept, for network-(long)-transport latency masking ) – user3666197 44 mins ago "

Given about the 65k files, listed in CSV, ought get processed ASAP, the performance-tuned orchestration is the goal, file-I/O being just a negligible ( and by-design well latency-maskable ) part thereof ( which does not mean, we can't screw it even more ( if trying to organise it in another performance-devastating ANTI-pattern ), can we? )

Tip #1 : avoid & resist to use any low-hanging fruit SLOCs if The Performance is the goal

If the code starts with a cheapest-ever iterator-clause, be it a mock-up for aRow in aCsvDataSET: ...or the real-code for i in range( len( queries ) ): ... - these (besides being known for ages to be awfully slow part of the python code-interpretation capabilites, the second one being even an iterator-on-range()-iterator in Py3 and even a silent RAM-killer in Py2 ecosystem for any larger sized ranges) look nice in "structured-programming" evangelisation, as they form a syntax-compliant separation of a deeper-level part of the code, yet it does so at an awfully high costs impacts due to repetitively paid overhead-costs accumulation. A finally injected need to "coordinate" unordered concurrent file-I/O operations, not necessary in principle at all, if done smart, are one such example of adverse performance impacts if such a trivial SLOC's ( and similarly poor design decisions' ) are being used.
Better way?

*

*a ) avoid the top-level (slow & overhead-expensive) looping

*b ) "split" the 65k-parameter space into not much more blocks than how many memory-I/O-channels are present on your physical device ( the scoring process, I can guess from the posted text, is memory-I/O intensive, as some model has to go through all the texts for scoring to happen )

*c ) spawn n_jobs-many process workers, that will joblib.Parallel( n_jobs = ... )( delayed( <_scoring_fun_> )( block_start, block_end, ...<_params_>... ) ) and run the scoring_fun(...) for such distributed block-part of the 65k-long parameter space.

*d ) having computed the scores and related outputs, each worker-process can and shall file-I/O its own results in its private, exclusively owned, conflicts-prevented output file

*e ) having finished all partial block-parts' processing, the main-Python process can just join the already ( just-[CONCURRENTLY] created, smoothly & non-blocking-ly O/S-buffered / interleaved-flow, real-hardware-deposited ) stored outputs, if such a need is ...,
and
finito - we are done ( knowing there is no faster way to compute the same block-of-tasks, that are principally embarrasingly independent, besides the need to orchestrate them collision-free with minimised-add-on-costs).

If interested in tweaking a real-system End-to-End processing-performance,start with lstopo-mapnext verify the number of physical memory-I/O-channelsandmay a bit experiment with Python joblib.Parallel()-process instantiation, under-subscribing or over-subscribing the n_jobs a bit lower or a bit above the number of physical memory-I/O-channels. If the actual processing has some, hidden to us, maskable latencies, there might be chances to spawn more n_jobs-workers, until the End-to-End processing performance keeps steadily growing, until a system-noise hides any such further performance-tweaking effects
A Bonus part - why un-managed sources of latency kill The Performance

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i do zero down time deployment on cluster environment? I need to deploy a major deployment on my system (more that 15 ear file ) , my system is high available system  , So how can I do this deployment with zero downtime ?
my application server is IBM-WAS

A: After updating the applications, you can utilize the "Rollout Update" feature. Rather than saving and synchronizing the nodes after updating, you can use this feature which automatically performs the following tasks to enable the changes to propagate to all deployment targets while maintaining high availability (assuming you have a horizontal cluster, such that cluster members exist on multiple nodes):

*

*Save session changes to the master configuration

*For each node in the cluster (one at a time, to enable continuous availability):

*

*Stop the cluster members on the node

*Synchronize the node

*Start the application servers (which automatically starts the application)


text:
Q: Solidworks issue: Error message 'there has to be at least one component for a flow analysis' pops up on clicking 'check geometry' This is so frustrating- I have a fully closed solid body that I want to do a quick flow analysis of.
I go to Tools/Flow Simulation (a Solidworks add-in)/Tools/Check Geometry.
Even Solidworks says my 'geometry' is 'one closed body'. I don't know what to do as I really have to model this, would be grateful for any help.
Here is a screenshot of the error message: (https://i.stack.imgur.com/fb5ro.jpg)
I've gone back to change my body and export another STL file multiple times, no changes.
When I initially import the file, it comes with some other bodies that I delete before trying the geometry analysis- this shouldn't be the issue though if Solidworks says there is only one body there?
I'm also new to Solidworks so the fix could also be simple.


text:
Q: (PHP) file_get_contents - Contents url after questionmark? First of all, i'm new to PHP. I've got the following code-snippet and it works pretty well.
<?php

$html = file_get_contents('http://www.example.com/');
preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i',$html, $matches );

foreach ($matches[1] as $match) {
    echo '<img src="' . $match . '" />';
}
?>

Now i want to add the  file_get_contents url after a questionmark in the filename like:
http://www.example.com/getfile.php?http://www.url.com/images/

How to do this? Is this cURL?

A: Solution:
Changing:
$html = file_get_contents('http://www.example.com/');

to
$html = file_get_contents($_GET["url"]);

works! :)


text:
Q: Cookie session driver won't save any validation error or flash data I am having a hard time with the cookie session driver in Laravel.
I have a simple form with a validation in place. This is my method for saving this form data:
public function store()
{
    $this->validate(request(), [
        'name'        => 'required',
        'title'       => 'required',
        'description' => 'required|max:600',
        'image'       => 'required|file|mimes:jpeg,png',
    ]);

    $member = TeamMember::create(request()->all());
    $member->addImage(request()->file('image'));

    return redirect()->route('backoffice.team-members');
}

Pretty simple.
The problem is that, when using the cookie session driver, if I save this form with a description that's 1024 characters long, I'll get redirected back but with no flash data and no $errors in the view for the next request to handle.
Example:

This is a POST after using this line:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce gravida eros ut leo commodo luctus. Nulla neque dui, laoreet quis felis in, porta tincidunt felis. Phasellus in lacus et sem condimentum ornare. Praesent vitae nisi tempus, gravida tortor eu, convallis dui. Cras lacinia posuere scelerisque. Vestibulum tincidunt purus id sollicitudin varius. Sed eros urna, mattis nec nunc eu, finibus suscipit ipsum. Aliquam varius faucibus congue. Vivamus convallis imperdiet sem a commodo. Proin cursus feugiat sem a pharetra. Curabitur rhoncus non quam sit amet lacinia. Sed ut nisl id odio faucibus vehicula vel ut erat. Vestibulum ut iaculis magna. Quisque sit amet massa sodales, suscipit nisl eu, dapibus elit. Morbi posuere ligula pretium commodo semper. Nam odio elit, rutrum finibus tortor eget, viverra viverra metus. Proin tincidunt tempor ex pretium rhoncus. Proin egestas erat sed eros congue, mollis gravida magna bibendum. Pellentesque vel bibendum nunc. Orci varius natoque penatibus et magnis dis viverra fusce.

In the description field. 1024 bytes to be exact.
Instead, if I just fill the field with some more dummy data but nothing too crazy:

If I change the session driver to file:

... it works.
But this does not fix my problem. I do need to use the cookie driver for session as the production website is running in 3 different datacenters to achieve high availability. Using the cookie for the session allows the user to hit any of the 3 servers and still continue with it's request without having to use any sticky session or any central session driver.
Using the database as a driver—which is also in a cluster with HA—is not an option as this is a really high traffic website and that would be a write per request which doesn't sound appealing at all. I would like to prevent that at any cost.
There is anyway this can be solved?
I must say this is the backoffice of the website, but soon the user in the frontend will be able to also write more than 1024 characters in a textarea... so if I just change the driver for the backoffice doesn't help, as we will run into the same for our users.

A: The browser has limitation of cookie. It's too large for the browser to store the cookie while you use cookie as the session driver. You can check the browser cookie limitation here http://browsercookielimits.iain.guru/
Recommendation:
Use redis as the session driver.
Steps:
1.After installed Redis server, add the predis/predis package:
composer require predis/predis

2.Change your configuration file config/database.php:
'redis' => [

    'client' => 'predis',

    'default' => [
        'host' => env('REDIS_HOST', 'localhost'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', 6379),
        'database' => 0,
    ],

],

A: The cookie session driver is not suitable for applications that must store any significant amount of data in the user's session. Browsers typically limit data stored in one cookie to around 4 KB (4096 bytes). As we found, we can easily exhaust this capacity by attempting to store a 1024-character-long string in the session cookie—the "Lorem ipsum..." string in the question contains only ASCII characters, and each ASCII character is represented using 4 bytes, so 1024 × 4 = 4096 bytes.
As we can see, we quickly begin to run out of space when we need to store additional items in one session cookie, such as the serialization metadata for PHP values, or when the data contains UTF-8 characters that consume more than 4 bytes per character. To continue to use cookies to store session data greater than 4 KB, we'd need to write a custom session driver that partitions session data across multiple cookies for each response and then reassembles them on each request. For good reason, no existing packages do this that I'm aware of. This brings me to my next point...
I want to strongly discourage the use of cookies for storing a full session (instead of just a session ID). This approach can expose security vulnerabilities, adds overhead to requests and responses (including requests for static assets on the same domain), risks desynchronizing data (right-click app tab → Duplicate to see what happers), complicates tests and debugging, and causes problems when storing certain kinds of data.
For the distributed application in the question, we have four options:

*

*Store the session data on a central server accessed by each application instance

*Store the session state at each site, and replicate it between sites

*Use "sticky" sessions to anchor a user to one site after starting a session

*Write a non-trivial amount of code to implement a custom session driver that allows the client to pass session state without using cookies, or one that partitions cookies

I think we can reasonably eliminate the fourth option. Unless we have a very good reason to avoid using the first three approaches, and for typical applications we usually don't, we cannot justify the amount of work, complexity, and overhead needed to build a system to transfer session data back and forth across HTTP when the first three options are standard, widely-accepted solutions.
Based on the information in the question, it sounds to me like you already understand the concepts and implications behind the other three options, so I won't elaborate on explanations for each one (but do comment to let me know if I should).
For applications without advanced infrastructure requirements, I recommend the third approach: sticky sessions. These are relatively easy to set up and usually require configuration on the load balancer so that once a client starts a session with an application server, the load balancer routes any subsequent requests to the same server until the session ends. For high-availability, we can combine this approach with the Redis session driver and Redis servers configured for master-slave replication between the datacenters, and, optionally, Redis Sentinel to automate failover. Redis suits session data well and offers better performance than a relational database. If we have multiple application instances at each data center, Redis provides a central location for session data for all instances at one site.
For completeness, and to directly answer the question, here's an overview for the development needed to create a cookie-based session driver that handles session data greater than 4 KB. Again, I recommend one of the other approaches described above:

*

*First, we'll need to create a new class that implements PHP's SessionHandlerInterface (check out Laravel's cookie session handler for a starting point—we can probably extend this class).

*The write() method of this class will need to serialize the session $data and then split the data into chunks smaller than 4 KB (for some browsers, less that 4093 bytes). Be sure to account for multibyte characters. Before splitting the data, we may also want to encrypt it if the session contains sensitive information or if we don't want clever users to mess with the values. Then, the method should add a new cookie for each chunk of the session data. Each cookie will need to contain the sequence in its name, and we can add an additional cookie that contains the number of chunks.

*The read() method will perform these operations in reverse. First, it will reassemble each chunk from the cookies in the request using the value of the cookie that contains the number of chunks, and then, optionally, decrypt the data if we encrypted it.

*The destroy() method should clear the contents of each cookie that contains a chunk.

*Then we'll choose a name for the session driver, such as cookie-extended, and, in a service provider's boot() method, register it as an available driver using :
Session::extend('cookie-extended', ...);

We'll need to instruct the application, in config/session.php or in .env, to use the new driver for user sessions.
If you do decide to go down this path, be sure to test the implementation in every browser you plan to support, as different browsers impose their own limitations on the size and quantity of cookies. Even if we've increased the amount of session data we can store as cookies, we're still limited to the maximum number of cookies a browser will accept per domain.
As a final note, storing sessions in the database may not impact performance as much as you think. It could be worth measuring the actual load created by this simple solution before investing many hours optimizing for a concern that might not be a real issue.


text:
Q: WSS with proxy using port 443 browser client connect to websocket server on port 6001 I'm using "laravel websocket if beyondcode" for the browser client to WebSocket serve on port 6001. but when I change the browser client request from using port 80/443 it's not connecting to the WebSocket server.
Browser client request URL:
wss://test.example.com:443/app/ABCDEFG?protocol=7&client=js&version=7.0.3&flash=false

code added in  tag
SSLProxyEngine on
ProxyPreserveHost On
ProxyPass /app wss://test.example.com:6001/$1
ProxyPassReverse /app wss://test.example.com:6001/$1
ProxyRequests off

can anyone help me with this?

A: This is the final working code that is worked in my centos.
Add this below code before the closing of <VirtualHost *:443> tag
<IfModule mod_proxy.c>
    ProxyRequests Off
    SSLProxyEngine On

    # Ensure WebSocket protocol is forwarded correctly
    RewriteEngine on
    RewriteCond %{HTTP:UPGRADE} ^Websocket$ [NC]
    RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
    RewriteRule /app/(.*) wss://%{HTTP:HOST}:6001/app/$1 [P]
</IfModule>

Below is my pusher setting
window.pusher = new Pusher(process.env.MIX_PUSHER_APP_KEY, {
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: false,
    wsHost: window.location.hostname,
    // commented this because it should be use default port 80/443
    //wsPort: process.env.MIX_LARAVEL_WEBSOCKETS_PORT,
    //wssPort:process.env.MIX_LARAVEL_WEBSOCKETS_PORT,
    enabledTransports: ['ws', 'wss'],
    forceTLS: true,
});


text:
Q: How does reflect get the returned structure pointer package main

import (
    "fmt"
    "reflect"
)

type Blog struct {
    Name string
}

func (blog *Blog) Test() (*Blog){
    fmt.Println("this is Test method")
    blog.Name = "robin"
    return blog
}

func main() {
    var o interface{} = &Blog{}
    v := reflect.ValueOf(o)
    m := v.MethodByName("Test")
    rets := m.Call([]reflect.Value{})
    fmt.Println(rets)
}

I got the following output:

*

*this is Test method

*[]

Why is there no Blog struct and how to get the value of the Blog Name?

A: package main

import (
    "fmt"
    "reflect"
)

type Blog struct {
    Name string
}

func (blog *Blog) Test() *Blog {
    fmt.Println("this is Test method")
    blog.Name = "robin"
    return blog
}

func main() {
    rv := reflect.ValueOf(&Blog{})
    rm := rv.MethodByName("Test")

    results := rm.Call(nil)
    fmt.Printf("%#v\n", results)

    blogPointer := results[0]
    fmt.Printf("%#v\n", blogPointer)

    blogValue := blogPointer.Elem()
    fmt.Printf("%#v\n", blogValue)

    nameFieldValue := blogValue.FieldByName("Name")
    fmt.Printf("%#v\n", nameFieldValue)

    name := nameFieldValue.String()
    fmt.Println(name)
}

https://play.golang.org/p/iyUw-Sp97-

A: first we call the function returned by the interface and then we can fetch its value using Elem() method call to the pointer to interface
package main

import (
    "fmt"
    "reflect"
)

// Blog struct to hold the name of the author
type Blog struct {
    Name string
}

//Test functon to to test the blog name
func (blog *Blog) Test() *Blog {
    fmt.Println("this is Test method")
    blog.Name = "robin"
    return blog
}

func main() {
    var o interface{} = &Blog{}
    v := reflect.ValueOf(o)
    m := v.MethodByName("Test")
    res := m.Call(nil)
    ptr := res[0]
    fieldValue := ptr.Elem().FieldByName("Name").String()
    fmt.Println(fieldValue)
}


text:
Q: MYSQL Update not updating database? I have a simple Form along side a PHP update query that simply isn't working! I know the PHP is working on the page as there are several validation checks that need to be passed before hand which are working perfectly. The form its self is inside the Colorbox Popup tool.
My HTML Form Code is:

<form action="#" method="post">
  <input type="hidden" name="user_id" value="<?php echo $user_id; ?>" />
  First Name:Enter your forename
  <input id="first_name" type="text" name="first_name" maxlength="50" placeholder="e.g. Joe" required autofocus/>

<input type="submit" id="update" name="update" value="Continue to Step 2!">
</form>

With the PHP Code as follows (this is above the HTML code on the page):
<?php
if($_POST['update']){

    $user_i            = $_POST['user_id'];
    $f_name            = $_POST['first_name'];
    $first_name        = ucfirst($f_name);

mysql_query("UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'") or die(mysql_error());
 } ?>

The actual submit appears to be working, with the Popup refreshing afterwards, but the database does not update! I have triple checked the syntax and the database fields. 'user' and 'first_name' and 'user_id' is correct.
Update: Because the popup box refreshes, I cannot view the error's from the 'or die(mysql_error()) unfortunately, other wise i might have been one step closer.
Any help would be hugely appreciated.
Many thanks in advance.

A: When you say pop-up box, I assume you are using ajax to communicate from the form to the server, which as you stated is difficult to view submitted data. If this is the case try:
error_log(serialize($_POST));

This will force an entry in your error log with the $_POST data in serialized format, so you can check the values you are submitting are populated correctly.
You will also want to sanitize the variables you are adding to the SQL:
$sql = "UPDATE user SET first_name = " . mysql_real_escape_string($first_name) . " WHERE user_id = " . mysql_real_escape_string($user_i) . " LIMIT 1";

mysql_query($sql);

A: I would:

*

*print_r($_POST); to view the POST data.

*Generate the SQL from a string so it can be printed for debugging purposes, like so:
$sql = "UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'";
echo $sql;
mysql_query($sql) or die(mysql_error());
One of these techniques will likely tell you why the PHP-generated SQL doesn't update your database record.

A: you set your user_id field by echo $user_id; but your variable name is set to $user_i = $_POST['user_id'];
therefore your user id field is not set and your Mysql command will fail.


text:
Q: XSL variable usage Hi I have one XSL variable
<xsl:variable name="QTime" select="response/lst/int[@name='QTime']"/>

Now I need to pass this to JavaScript function. Please help me how to do this...

For example

A: Simple:

The { and } are key here - when used in attributes, they are used by xslt as a short-hand to evaluate the contents under xslt rules. This is equivalent to:

    <xsl:attribute name="onmouseover">s(<xsl:value-of select="$numFound"/>);</xsl:attribute>

A: I'm guessing you're generating some HTML with your XSL transformation. Then, you can try this:
<xsl:element name="span">
    <xsl:attribute name="onmouseout">
        <xsl:text>c();</xsl:text>
    </xsl:attribute>
    <xsl:attribute name="onmouseover" select="concat('s(', $numFound, ');')" />
</xsl:element>


text:
Q: Woocommerce product quantity name, how can i change what is displayed? I've installed a plugin for my woocommerce's products which allow me to add prederminated quantity on a product, suddenly, in the front-end it's displayed "1400 items @$0.014 $20".
I've tried to change some parameters on the main php file, but i'm not sure i'm doing it right.
This part of php code come from the main folder of the plugin
if (!defined('ABSPATH'))
exit;
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins'))))
return;

if (!class_exists('WooFixedQuantity')) {

define("WOOFIXCONF_QTY_DESC", "{qty} items @{price} {total}");
define("WOOFIXCONF_SHOW_DISC", "yes");
define("WOOFIXCONF_SHOW_STOCK", "yes");
define("WOOFIXCONF_CHECK_STOCK", "no");
define("WOOFIXCONF_DEFAULT_ROLE", "customer");

define("WOOFIXOPT_QTY_DESC", "woofix_qty_desc");
define("WOOFIXOPT_SHOW_DISC", "woofix_show_disc");
define("WOOFIXOPT_SHOW_STOCK", "woofix_show_stock");
define("WOOFIXOPT_CHECK_STOCK", "woofix_check_stock");
define("WOOFIXOPT_DEFAULT_ROLE", "woofix_default_role");
define("WOOFIXOPT_AVAILABLE_ROLES", "woofix_available_roles");

class WooFixedQuantity
{

So i thought it was good to change this line of code
define("WOOFIXCONF_QTY_DESC", "{qty} items @{price} {total}");

but nothing happen, what am i doing wrong?


text:
Q: Linux kernel utility function that takes symbol string as input and return its address Is there an API in linux that can give me the address of the symbol passed in as string input?
For example, in the below function, I need the same output as shown in the print of &begin1.
the reason that I need this programatically is that I have labels like begin1, begin2, begin3 etc...in my program and I have to run a loop to get their addresses.
extern void *begin1;
int main(int argc, char **argv)
{
    char buf1[30], buf2[30];
int i= 1;
asm volatile ("nop;\n"
       "nop;\n"
       "begin1:\n"
       "nop;\n"
       "nop;\n"
       "nop;\n"
       "nop;\n"
       "nop;\n"
       "nop;\n"
       "lbl1:\n"
       "nop;\n"
       "nop;\n"
       );

printf("&begin1 = %p\n", &begin1); //NEED THIS OUTPUT

sprintf(buf1, "begin%d",i);
sprintf(buf2,"lbl%d",i);

//Q: Can we pass buf1 as input to a kernel function that can give me the same output as above?

return 0;

}

A: A program with a main function cannot be kernel code. It is application code started by execve(2) -e.g. by your shell-
(and applications interact with the kernel thru syscalls listed in syscalls(2)...)
On Linux, your kernel code is often a kernel module for some custom driver.
You could use dlopen(3) and dlsym (and you need the symbols to be global, so use .global directive in assembler). You then want to link your program with -rdynamic flag (and the -ldl library), call dlopen with a NULL path, and use dlsym on that program handle.
Notice that dlopen is not a syscall (it uses open and mmap ...)
BTW, you might be interested by GCC label as values extension.


text:
Q: How do I convert a 24-bit/96 kHz FLAC to anything else? I have some FLAC files I want to convert to AAC, but I can't because my go-to program, Max, throws an exception (The call to ExtAudioFileSetProperty failed.) when it tries to convert 24-bit/96 kHz FLAC (16-bit is no problem) to any other format.
So is there another good program for converting from FLAC?

A: Personally I use a tool called X Lossless Decoder, or XLD for short. I use it for converting FLAC to Apple Lossless regularly, and it's never hiccupped.
From the project's page:

XLD can decode following formats:

*

*(Ogg) FLAC (.flac/.oga)

*[…]

and:

XLD supports various output formats. It can convert audio files into […] MPEG-4 AAC (QuickTime/CoreAudio), MP3 (LAME), Apple Lossless, FLAC […].

XLD is free, and is still being actively maintained. Highly recommended.


text:
Q: php5-fpm: server reached pm.max_children I have Nginx + php5-fpm. Several times per hour my website stucks and in logfile I see the following:

WARNING: [pool www] server reached pm.max_children setting (5),
  consider raising it.

/etc/php5/fpm/pool.d/www.conf file contains the following configuration:
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

Server:
AMD Opteron™ 3280, Octo-Core, 8x 2.4 GHz, 16 GB DIMM (DDR3).
I have no idea what numbers should I put in www.conf file for this server. Can me help somebody? Thanks

A: There are many possible reasons why your PHP-FPM would reach the max_children. Most common ones are:

*

*A lot of parallel requests from your clients

*Slow execution of the PHP scripts

*Very low setting of the max_children
Looking at the specs of your machine, assuming there is nothing else than PHP+Nginx running, I think you could set it much higher than 5. You say you have 8 Cores, usually Nginx needs much less CPU than PHP, so with 5 children you will probably never be able to use all of them. I'm usually setting it to something like the number of cores x 2 or number of cores x 4, depending on the memory consumption of your PHP scripts.

A: I found that by setting the pm.max_requests value (which is commented out by default) helped in fixing these errors. This setting forces child requests to respawn after executing a certain number of requests and can be helpful if there are memory leaks somewhere in your code or 3rd party libs.
In /etc/php-fpm.d/www.conf:
pm.max_requests = 500

A: I had the same problem whith my docker php-fpm and I fixed it by modifing parameters in these files:
/usr/local/etc/php-fpm.d/www.conf
/usr/local/etc/php-fpm.d/www.conf.default
The new parameters are :
pm = dynamic
pm.max_children = 25
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 500


text:
Q: How to set up git branch flow when having a shared code on feature branches I have a project, current set Main branch as the production branch and another develop branch for features branch intergration.
I create a few big feature branches, for example, feature/page-A and feature/page-B. So all small features inside page A will create a new small feature branch from feature/page-A, like feature/page-A/heading, and same action on feature/page-B. I use pull requests when merge small features into the big feature branch.
When I finish the big feature branch, like feature/page-A, I will create a release branch for this feature, release/page-A_1.0 and this release branch is like a cut and won't receive any new features. If I have more features on page A, then I'll create another release version branch, like release/page-A_1.1. When I create each release branch, I will merge the big feature branch to develop branch so develop branch also has the pull request requirement.
Is this git flow set up corret?
I also have a problem with this git flow. If I have few util functions created in feature/page-A, then I realize I need these functions on feature/page-B too. Because the individual feature branch is not finished yet, I don't merge it into develop, should I duplicate these functions on both feature branch individually then leave the merge conflict when feature branch is merging into develop? Or there is a better solution.
I may only need the same functions, which could be part of one commit or across multiple commits, so git cherry-pick may not a good solution for my case.


text:
Q: Is $ \frac{x^2}{x^2-1}$ a polynomial? Is $ \frac{x^2}{x^2-1}$  a polynomial?
I reviewed conjugates and exponents this afternoon when trying to rationalize the denominator.  I was wondering if this is equivalent? $$ \frac{x^2}{x^2-1} = x^2 + x^{-2} -1^{-1} $$
General polynomial equation is $$P(x) =a_n x^n + a_{n-1}x^{n-1}+a_{n-2} x^{n-2} + \cdots$$
$N$ has to be a positive integer for an equation to be a polynomial.  By this definition then $\frac{x^2}{x^2-1}$ is not a polynomial.
Conjugates up to this point have only been used for fractions with radicals or imaginary numbers in the denominator. However I was struggling with how to rationalize the denominator when I was studying this problem.

A: No. A polynomial is a function of the form $a_n x^n + a_{n - 1} x^{n - 1} + \dotsb + a_0$. No algebraic coaxing will put $x^2 / (x^2 - 1)$ into that form.
Another way to see this is that a polynomial function is everywhere finite (continuous), while your function fails that, it isn't defined at $x = \pm 1$ (there it tends to $\infty$)


text:
Q: py-datatable Replace empty string in column with NaN In a python data table, I wanted to replace empty strings with NaN. When I tried, I get the below error. It works with pandas. Thanks in advance for the help.
Datatable Syntax I tried:
dt[:,"column_name"].replace('',np.nan)

Error Received:

Cannot replace string value '' with a value of type <class 'float'>

pandas syntax that worked:
pd["column_name"]=pd["column_name"].replace('',np.nan)

A: Py datatable syntax to update (replace) one of the columns based on its value:
import datatable as dt
mydt = dt.Frame(a=['a','b','c','','d','e'])
mydt[dt.f.a == '', dt.update(a = None)]

Datatable before update:
mydt
   | a
-- + --
 0 | a
 1 | b
 2 | c
 3 |
 4 | d
 5 | e

Datatable after update:
mydt
   | a
-- + --
 0 | a
 1 | b
 2 | c
 3 | NA
 4 | d
 5 | e

works with version 0.10.0 or later
Bonus answer: to accomplish the opposite - replace missing values with some constant value use function isna():
mydt = dt.Frame(a=['a','b','c', None,'d','e'])
mydt[dt.isna(dt.f.a), dt.update(a = 'NULL')]


text:
Q: iPhone application Icon not registering I am at a complete loss because my application icon simply will not register. I've tried just about everything and the icon still just will not register. I think it may have to do with the fact that I was trying to re-name my project something else, and perhaps the targets now do not match. Can anybody provide advice on why my icon simply will not show up on the phone?
Thanks

A: PNG compression is a little algorithm that the compiler performs to cut down on the space images take up in your app.  Unfortunately, it has been the Bain of many a programmer's existence because it often doesn't de-compress the images once the binary is made and ran.  Just set it to NO.
PNG compression also optimizes the PNG's for an iOS device like so:

*

*Extra critical chunk (CgBI).

*Byteswapped (RGBA –> BGRA) pixel data, presumably for high-speed >direct blitting to the framebuffer.

*Zlib header, footer, and CRC removed from the IDAT chunk.

*Premultiplied alpha (color′ = color * alpha / 255).


text:
Q: Как заставить работать xDebug с Web Api? Добрый день.
Установлен и настроен xDebug на основном домене и поддоменах: site.ru, admin.site.ru, mobile.site.ru
При отладке страниц, он работает нормально. Использую phpstorm 8.02 + openserver 5.2.2
Есть еще домен третьего уровня api.site.ru
Через этот поддомен на сайте успешно работает Web Api. Когда ставлю точку останова и пытаюсь отладить кросс-доменный ajax запрос (с site.ru на api.site.ru), то xDebug его не видит и пропускает мимо.
Для запуска xDebug использую https://www.jetbrains.com/phpstorm/marklets/
Пробовал также https://chrome.google.com/webstore/detail/xdebug-helper/eadndfjplgieldjbigjakmdgkmoaaaoc
Он работает только при запуске в пределах одного домена.
Правильно ли я понимаю, что проблема из за того, что ajax запрос идёт с другого домена, поэтому не срабатывает xDebug? Как это решить?
Спасибо.

A: Вообщем проблема решена.
Как оказалось js почему-то не отправлял куки со значением XDEBUG_SESSION, который необходим для работы с xDebug. В моём случае, на стороне js отрабатывал angular, который должен был посылать эти самые куки. А так как ide у меня была phpstorm и значение xDebug прямо установлено как PHPSTORM, то моя кука выглядела так: XDEBUG_SESSION=PHPSTORM
Первый результат в поиске сразу выдал ответ-решение на SO, почему браузер не отправляет куки вместе с запросом:
https://stackoverflow.com/questions/17064791/http-doesnt-send-cookie-in-requests


text:
Q: Easy way to translate attributes of models in a web application? I have a web appplication where I sort photographies into categories. These categories are currently in Swedish but i want to add the option to add an english translation of the category names.
If the categories had been static I could've just added translations to the locale files, but now that a user should be able to add categories (and translations), I'm not sure how to go about it.
How would I go about doing this? The obvious first thought is to add columns for each language into the database table like title_en, title_sv etc but I guess that'll quickly become impractical as later on in the project, the customer will probably like to add more languages.
Anyone done something similar before? Thanks a lot!

A: The Rails i18n system allows different backends. If you Google "rails i18n backend," you'll find several implementations and examples.
You could use a database for this. Here's a RailsCast demonstrating managing the translations through a web interface.

A: There are some possible solutions. My first choice whould be to add a a lang:string field and parent_id:integer to the categories table. Then you add a self referential association to the Category (I assume its called Categrory,...) model.
belongs_to :translated, :class_name => 'Category', :foreign_key => 'parent_id'
has_many :translations, :class_name => 'Category', :foreign_key => 'parent_id'

Then add a scope to your model that filters by the lang field.
scope :language, lambda{|lang| where("lang = ?", lang)}

And a translate method.
def translate(lang)
  self.translations.language(lang).first if self.translations.language(lang).any?
end

So you can have one main language and add any amount of other languages.
Another possibilty whould be to add a translations:text field to your model and serialize it. So you can store the translations in a hash that is serializes. The downside of that solution whould be that serialized fields cant be searched that easy.


text:
Q: How can I retrieve SMS messages from a telephone operator? I can get the user's telephone operator using TelephonyManager, and I need to use this name to retrieve texts received from the operator. How can I use something like an SQL where clause with Android's ContextResolver.query() method? Here's my code to retrieve ALL the text messages received by the user. I need to tweak it to retrieve the messages from the user's telephone operator.
public void fetchSMS() {

    TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String operator=tMgr.getNetworkOperatorName();
    Uri mSmsinboxQueryUri = Uri.parse("content://sms/inbox");
    String[] cols = new String[]{"_id", "thread_id", "address", "person", "date", "body", "type"};
    Cursor cursor1 = getContentResolver().query(
            mSmsinboxQueryUri,
            cols, null, null, null);
    if (cursor1!=null && cursor1.moveToFirst()) {
        do {
            String address = cursor1.getString(cursor1
                    .getColumnIndex(cols[2]));
            //String address2=(address.split("-"))[1];

                String date = cursor1.getString(cursor1
                        .getColumnIndex(cols[4]));
                String msg = cursor1.getString(cursor1
                        .getColumnIndex(cols[5]));
                String type = cursor1.getString(cursor1
                        .getColumnIndex(cols[6]));

                smsLog.append("\n" + "Address:").append(address).append("\n" + "Date:").append(date).append("\n" + "Message:").append(msg).append("\n" + "Type:").append(type).append("\n\n");
            cursor1.moveToNext();
        }
        while (!cursor1.isAfterLast());
        cursor1.close();
    }
}

A: May be its useful for you.
More Information refer this page.
SmsBroadcastReceiver.java
This is a BroadcastReceiver which receives the intent-filtered SMS messages. onReceive, we extract the SMS message bundle and show a toast message and also update the UI by adding the SMS message to the SMS inbox list. When a SMS message arrives, the inbox is automatically refreshed.
public class SmsBroadcastReceiver extends BroadcastReceiver {

    public static final String SMS_BUNDLE = "pdus";

    public void onReceive(Context context, Intent intent) {
        Bundle intentExtras = intent.getExtras();
        if (intentExtras != null) {
            Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
            String smsMessageStr = "";
            for (int i = 0; i < sms.length; ++i) {
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

                String smsBody = smsMessage.getMessageBody().toString();
                String address = smsMessage.getOriginatingAddress();

                smsMessageStr += "SMS From: " + address + "\n";
                smsMessageStr += smsBody + "\n";
            }
            Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();

            //this will update the UI with message
            SmsActivity inst = SmsActivity.instance();
            inst.updateList(smsMessageStr);
        }
    }
}

SmsActivity.java
This is the main Android activity of the SMS application. It acts as the SMS inbox. It has a ListView to show the SMS messages. onCreate we read all the messages present in the internal SMS inbox from its Uri and show them using the ListView.
public class SmsActivity extends Activity implements OnItemClickListener {

    private static SmsActivity inst;
    ArrayList<String> smsMessagesList = new ArrayList<String>();
    ListView smsListView;
    ArrayAdapter arrayAdapter;

    public static SmsActivity instance() {
        return inst;
    }

    @Override
    public void onStart() {
        super.onStart();
        inst = this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);
        smsListView = (ListView) findViewById(R.id.SMSList);
        arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, smsMessagesList);
        smsListView.setAdapter(arrayAdapter);
        smsListView.setOnItemClickListener(this);

        refreshSmsInbox();
    }

    public void refreshSmsInbox() {
        ContentResolver contentResolver = getContentResolver();
        Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
        int indexBody = smsInboxCursor.getColumnIndex("body");
        int indexAddress = smsInboxCursor.getColumnIndex("address");
        if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
        arrayAdapter.clear();
        do {
            String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
                    "\n" + smsInboxCursor.getString(indexBody) + "\n";
            arrayAdapter.add(str);
        } while (smsInboxCursor.moveToNext());
    }

    public void updateList(final String smsMessage) {
        arrayAdapter.insert(smsMessage, 0);
        arrayAdapter.notifyDataSetChanged();
    }

    public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
        try {
            String[] smsMessages = smsMessagesList.get(pos).split("\n");
            String address = smsMessages[0];
            String smsMessage = "";
            for (int i = 1; i < smsMessages.length; ++i) {
                smsMessage += smsMessages[i];
            }

            String smsMessageStr = address + "\n";
            smsMessageStr += smsMessage;
            Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
Q: Example of a rational function such that : $(f(x))^{3} + (g(x))^{3} + (h(x))^{3}=x$ Can any one give me example of: rational functions $f, g$ and $h$ with rational coefficients such that
$$(f(x))^{3} + (g(x))^{3} + (h(x))^{3}=x$$
Also, if anyone knows a procedure for constructing such examples, I would be happy to learn them as well.

Added: Can we find rational functions $f$ and $g$ such that $(f(x))^3+(g(x))^3=x$

A: $(a^4-2a)^3+(a^3+1)^3+(2a^3-1)^3=(a^4+a)^3$
There are more at http://sites.google.com/site/tpiezas/010 Section 2.
This is Number Theory, not real analysis.

A: You may be interested to know identities are known that can bring this higher:
$a_1(x)^3+a_2(x)^3+a_3(x)^3 = x$
$a_1(x)^5+a_2(x)^5+a_3(x)^5+...+a_6(x)^5 = x$
$a_1(x)^7+a_2(x)^7+a_3(x)^7+a_4(x)^7+...+a_8(x)^7 = x$
where the given number of addends $a_i$ are rational functions in terms of x, hence can be treated as "Waring-like problems". The case k = 3 mentioned by Esteban is cited in Yuri Manin's book Cubic Forms (but has been solved earlier by Ryley), while k = 5 and 7 have been solved by Choudhry. Interestingly, k = 7 involves polynomials where the coefficients have 33 digits! One has to solve the simultaneous equations,
$a^2+m^5b^2 = c^2+m^5d^2$
$a^4+m^3b^4 = c^4+m^3d^4$
which, for m = 2, can be reduced to an elliptic curve and has an infinite number of integer solutions (after multiplying out the denominators), though the "smallest" one has 33 digits.
P.S. If anybody can solve k = 9, I'll be interested to know.
See, "Waring-Like Problems" at http://sites.google.com/site/tpiezas/001b.

A: Here is a start:
As ihf observed, you need
$f(x)^3+g(x)^3+h(x)^3=x q(x)^3$
On the left side you have three polinomials of degrees multiple of 3, on the right the degree is M3+1, thus something must cancel on the left side.
Without loss of generality, you can consider 2 cases:
Case 1: $deg(f)=deg(g) = deg(h)$. In this case, let $ax^k, bx^k$ and $cx^k$ be the dominant monomials in $f,g,h$. Then
$$a^n+b^n+c^n=0 \,.$$
which is not possible by Fermat last Theorem. So this is not possible.
Case 2: $deg(f)=deg(g) \geq deg(h)+1$.
Then $f=ax^k+bx^{k-1}+...$.  In order for the first two terms to cancel you need
$g=-ax^k-bx^{k-1}+..$.  And I am stucked here.
This suggest that the simplest potential example would be something like:
$$f=x^2+ax+b \,;\, g=-x^2-ax+c \,;\, h(x)=dx+e \,.$$
The computations seem too long :)

A: To the question added later:
$f(x)^3 + g(x)^3 = x$
It is not possible.
Setting $x$ to be $1^3, 2^3, \dots $ gives us a non-trivial solution to the diophantine equation $x^3 + y^3 = z^3$, since $f$ and $g$ can only have finitely many roots.


text:
Q: In RUBY CSV - how do I sum 1 column of sorted csv data and make sureto keep the constraints or limit on the data I am working on a csv reader, and looking to do manipulations on the data, I would like to sum one column - years, but make sure to not go past a certain number of points - say 1 million. I am not able to sum the columns, it is incrementing it. My constraint is 10 + years only
The csv looks like this
id, numbers, years,
1, 50000, 10
2, 40000, 12
3, 50000, 9

My ruby file looks like this
#!/usr/bin/env ruby

require 'pry'
require 'rubygems'
require 'fastercsv'

mycsv = CSV.read('input.csv', headers:true, col_sep: ', ', header_converters: :symbol, converters: :integer) # read the entire file into a 'loans' variable

new_mycsv = mycsv.find_all do |p|
 p[:years].between?(10, 12)
end

puts new_mycsv.inspect

#Sum csv data on first row
new_mycsv.first << "SUM"

new_mycsv[1..-1].each{|row| row << row.inject(:+)}

CSV.open("output.csv","w") do |out|
    new_mycsv.sort_by { |row| each do |row| }
   p out << row
 end
end

A: Running you code as posted :
$ ruby -w t_op.rb
t_op.rb:23: warning: shadowing outer local variable - row
t_op.rb:23: syntax error, unexpected '}'
    new_mycsv.sort_by { |row| each do |row| }
                                             ^
t_op.rb:26: syntax error, unexpected keyword_end, expecting '}'

Some comments to your code :

*

*post error-free code, so that we can copy-paste and work on it

*post only the code necessary to answer your question. For example
require 'pry'

is unused and not necessary to solve the posted problem

*run ruby with the -w option and correct all warnings

*this statement :
new_mycsv.first << "SUM"

concatenates "SUM" to the first element of new_mycsv, resulting in changing the array to :
1,50000,10,SUM
2,40000,12

*this statement :
new_mycsv[1..-1].each{|row| row << row.inject(:+)}

ignores the first row and concatenates something to other rows, resulting in changing the array to :
1,50000,10
2,40000,12,"[:id, 2, :numbers, 40000, :years, 12]"

Here is one solution (I'm not sure if I have well understood what not go past a certain number of points means) :
require 'csv'

mycsv = CSV.read('input.csv', headers:true, col_sep: ', ', header_converters: :symbol, converters: :integer) # read the entire file into a 'loans' variable

new_mycsv = mycsv.find_all { | row | row[:years].between?(10, 12) }

puts '---- new_mycsv'
puts new_mycsv

puts '---- selecting rows until the limit of numbers is reached'
numbers_limit  = 100_000
sum_of_numbers = 0
mycsv_limited  = []

new_mycsv.each do | row |
    number = row[:numbers]
    puts "row[:numbers]=#{number}  sum_of_numbers=#{sum_of_numbers}"
    break if sum_of_numbers + number >= numbers_limit
    sum_of_numbers += number
    puts "sum_of_numbers=#{sum_of_numbers}"
    mycsv_limited << row
end

CSV.open("output.csv","w") do |out|
    mycsv_limited.sort_by{ | row | row[:numbers] }.each { | row | out.puts row }
end

File input.csv :
id, numbers, years,
1, 50000, 10
2, 40000, 12
3, 50000, 9
4, 50000, 11
5, 40000, 11

Execution :
$ ruby -w t.rb
---- new_mycsv
1,50000,10
2,40000,12
4,50000,11
5,40000,11
---- selecting rows until the limit of numbers is reached
row[:numbers]=50000  sum_of_numbers=0
sum_of_numbers=50000
row[:numbers]=40000  sum_of_numbers=50000
sum_of_numbers=90000
row[:numbers]=50000  sum_of_numbers=90000

File output.csv :
2,40000,12
1,50000,10


text:
Q: Solving x'=Ax for 4x4 matrix with repeated eigenvalues $$\begin{bmatrix}
2 & 1 & 4 & 0 \\
0 & 2 & 1 & -1 \\
0 & 0 & 2 & 1 \\
0 & 0 & 0 & 2 \\
\end{bmatrix}$$
I have the following matrix, with eigenvalue 2 (multiplicity 4). I am trying to solve x' = Ax, where A is the matrix shown above.
I know that the equation can be solved as follows:
$x(t) = e^{At}x_0 = Pe^{Jt}P^{-1}x_0 $
J is the Jordan canonical form of the matrix A:
$$\begin{bmatrix}
2 & 1 & 0 & 0 \\
0 & 2 & 1 & 0 \\
0 & 0 & 2 & 1 \\
0 & 0 & 0 & 2 \\
\end{bmatrix}$$
How do I go about finding the eigenvectors in order to construct P and $P^{-1}$ in order to solve for x(t)? In addition, what is $e^{Jt}$ and how do I find it?

A: Eigenvectors are not going to cut it, your matrix is not diagonalizable. You'll need generalized eigenvectors.
Find an eigenvector by solving $(A-2I)x=0$ (or by observing your matrix). Then look for generalized eigenvectors which satisfy
$$(A-2I)^2x=0, (A-2I)^3x=0, (A-2I)^4x=0$$
You want them to be linearly independent. They form the matrix $P$.
$e^{Jt}$ is the exponential of $Jt$ that is
$$e^{Jt}=\sum_{n=0}^{\infty}\dfrac{t^nJ^n}{n!}$$
Since $J$ is not diagonal, $J^n$ is not so easily computed. You may write $J=2I+N$ where $N$ is nilpotent to help with practical calculations.

A: you do not need Jordan form  this time. Your matrix is of the form $A = 2I + N,$   where $N$ is the strict upper diagonal part as a square matrix, otherwise put $0.$ The two parts also commute, so
$$ e^A = e^{2I} e^N  $$  and
$$  e^{At}  = e^{2tI} e^{tN} $$
As $N$ is nilpotent, one can find the exponential from its (finite) Taylor series. Find $N, N^2, N^3.$ By my count $N^4 = 0.$
Note that the process with Jordan form is the same, you have a matrix $J = D + N$ with $N$ nilpotent, $D$ diagonal, and $DN=ND.$ The additional work is that it really is necessary to find a matrix $P$ such that $PJP^{-1} = A$ is the original matrix. Then $e^{At} = P e^{Dt} e^{Nt} P^{-1}.$ You need to find the actual matrix $P$ and its inverse.


text:
Q: ¿que se pone en el link en la funcion cell de fpdf?
Quiero saber lo que se pone en la variable $link para poder agregar datos desde un BD un reporte en php

A: Este tipo de problemas, por lo general, se solucionan leyendo el manual.
Según el manual:
Cell()

link:
URL o identificador retornado por AddLink().

Es decir, acepta:

*

*Una cadena, por ejemplo:
$link = 'http://www.fpdf.org/';
$fpdf->Cell(20, 10, 'Titulo', 1, 1,'C', false, $link);

*O una referencia interna retornada por AddLink, por ejemplo:
//...
$ref = $fpdf->AddLink();
$fpdf->Write(5, 'clic aca', $ref);

//... segunda página
$fpdf->AddPage();
$fpdf->Cell(20, 10, 'Titulo', 1, 1,'C', false, $ref);

A: Si el elemento a agregar es un enlace, ahi debes insertar la url del mismo.
Si solo es un texto plano, puedes no enviar ese parámetro o bien enviar una cadena vacía.


text:
Q: Is exponential CDF solvable for $\lambda$? I am trying to solve $F(x,\lambda)=1-e^{-\lambda x}$ for $\lambda$. $F$ and $x$ are known since they come from a risk management exercise of specifying extreme scenarios' impact as a percentile (90%) of the exponential distribution. I arrive at $\lambda =\frac{\ln(1-F)}{x}$ which obviously leads to negative λ.

A: No. You get $\lambda = -\ln(1-F)/x$ and since $0 \le F < 1$ and $ x > 0$ your $\lambda$ is positive.


text:
Q: "Pro-attitude" Definition What does the word pro-attitude mean in the following sentence:

Intentions are pro-attitudes, directed towards some future state of
affairs.
reference

I couldn't find this word  in the dictionaries.
Could you suggest a synonym for this word or explain it in some other words?

A: "A pro-attitude is an agent 's mental attitude directed toward an action under a certain description. Such attitudes include wants, desires , urges, moral views, aesthetic principles, and economic prejudices. Such a set of mental attitudes, together with the agent's belief that acting in a certain way promotes what the agent wants or values, form the primary reason for an agent to act in that way."
In simple terms, a pro-attitude is an urge or desire that drives an action.
Read a discussion of it here.


text:
Q: Disable image compression in Chrome mobile browser When using Chrome mobile on iOS and Android, we noticed that when "Reduce Data Usage" is turned on, the images on our modelling agency website get compressed by a significant amount. We would like to somehow disable this, since our portfolio has to consist of high quality photos.
Is there any HTML meta tag, CSS rule or any JS hack to force disable this function?

A: try <img src="example.png" pagespeed_no_transform> where
The 'Optimize Images' filter won't optimize an image (though it might still cache extend it) if it has the pagespeed_no_transform attribute.

A: Use some jquery
For example
$(document).ready(function(){
$("img").attr (" pagespeed_no_transform",true );
});


text:
Q: add div in fixed position with 100% height I need to add two div in top and bottom of fixed div,so I create fixed position panel in left, then add first div with h-100 class(height 100%). But Now, when I add second div in panel, I cant see this div in result.

.vertical-side {
  width: 250px;
  z-index: 1001;
  background: #fbfaff;
  bottom: 0;
  margin-top: 0;
  position: fixed;
  top: 0;
  border-right: 1px solid #e9e9ef;
}

.second {
  width: 250px;
  height: 100px;
  border-top: 1px solid #e9e9ef;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>

    First div

    second div

Demo HERE
I nee to this:

A: I think this is what your expecting, as per your description, you can adjust the height & width as per your need

.vertical-side {
  width: 250px;
  z-index: 1001;
  background: #fbfaff;
  bottom: 0;
  margin-top: 0;
  position: fixed;
  top: 0;
  border-right: 1px solid #e9e9ef;
}
.first {
  width: 250px;
  height: 100px;
  background:blue;
  border-top: 1px solid #e9e9ef;
}
.second {
  width: 250px;
  height: 100px;
  background:Red;
  border-top: 1px solid #e9e9ef;
}

      First Div

      Second Div

A: You can do this with flex utilities. Demo: here

.vertical-side {
  width: 250px;
  z-index: 1001;
  background: #fbfaff;
  bottom: 0;
  margin-top: 0;
  position: fixed;
  top: 0;
  border-right: 1px solid #e9e9ef;
}

.second {
  width: 250px;
  height: 100px;
  border-top: 1px solid #e9e9ef;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>

  First Div

  Second Div

A: you have in class .vertical-side : bottom: 0; and top: 0;
remove  bottom: 0; perhaps this helps
alternatively you can use grid and change the height here: grid-template-rows: 1fr 60px;
or grid-template-rows: 1fr 1fr for automatic height.

.vertical-side {
  display: grid;
  grid-template-rows: 1fr 60px;
  width: 250px;
  height: 100vh;
}

.first {
  display: grid;
  align-items: center;
  justify-content: center;
  background: grey;
}

.second {
   display: grid;
   margin-top: 2px;
   align-items: center;
   justify-content: center;
   background: green;
}

      first

      second

A: Your 2nd div is under your first div, which is 100% of its parent height. that means the 2nd div is out of the viewport. use flex/grid for your parent div (vertical-side). you'll find the 2nd div. use a height for your first div. that will also solve the issue.

A: In HTML, You are basically building in layers - So your second div was butted up against your first div, whereas you wanted it at the bottom. By putting in a third one in between the two as you can see with my spacer div it essentially provides you with margin between your top and bottom divs that you can still use and work with later on.
CSS
.vertical-side {
width: 250px;
z-index: 1001;
background: #fbfaff;
bottom: 0;
margin-top: 0;
position: fixed;
top: 0;
border-right: 1px solid #e9e9ef;
}

.top {
width: 250px;
height: 100px;
border-bottom: 1px solid #e9e9ef;
}

.spacer {
height: 45%;
}

.bottom {
margin-top: 100%;
width: 250px;
height: 100px;
border-top: 1px solid #e9e9ef;
}

HTML

First div

Spacer

second div

Image of how it looks

Edit any specifics you need/want


text:
Q: making a function to calculate average How I can make to create a \newcommand to calculate an average between three numbers (can be numbers or numeric variables)?
Usage would be
\numberavg{<A>}{<B>}{<C>}

Should be expandable to more than three arguments, as in
\numberavg{<A>}{<B>}{<C>}...{<n>}

A: Another xparse / expl3 solution with the same interface as the answer from Christian Hupfer. It works similar but avoids using temporary variables to stay expandable. This makes it easier to use the result in further calculations. It also returns a well-defined result (0) if the list is empty.
\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\cs_new:Nn\__avercalc_plus:n{
  + ( #1 )
}
\NewExpandableDocumentCommand{\avercalc}{O{1}+m}{%
  \fp_eval:n {
    round(
      ( 0 \clist_map_function:nN { #2 } \__avercalc_plus:n ) / max(1, \clist_count:n { #2 })
      , #1
    )
  }
}
\ExplSyntaxOff

\begin{document}
How I can make to create a newcommand to calculate an average between three numbers (can be numbers or numeric variables)
\def\foo{4.75}
\def\foobar{3.80}
\def\foobarfoo{10.3}

\avercalc{1.5, 3.5, 4}

\avercalc{}

\avercalc[4]{\foobar,\foo,\foobarfoo}
\end{document}

A: I suggest to use xparse and expl3 features, that applies a comma separated list in order to calculate the sum and then divide by the number of the elements. (It is not failsafe yet, since it does not check empty lists so far.)
The optional argument is meant for rounding numbers.
Please note that my \avercalc macro isn't expandable.
\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\avercalc}{O{1}+m}{%
  \clist_set:Nn \l_tmpa_clist {#2}%
  \fp_zero:N \l_tmpa_fp
  \clist_map_inline:Nn  \l_tmpa_clist {
    \fp_add:Nn \l_tmpa_fp {##1}
  }
  \fp_eval:n { round(\l_tmpa_fp/\clist_count:N \l_tmpa_clist, #1)}
}
\ExplSyntaxOff

\begin{document}
How I can make to create a newcommand to calculate an average between three numbers (can be numbers or nume

ric variables)
    \def\foo{4.75}
\def\foobar{3.80}
\def\foobarfoo{10.3}

\avercalc{1.5, 3.5, 4}

\avercalc[2]{\foobar,\foo,\foobarfoo}

\avercalc[3]{\foobar,\foo,\foobarfoo}

\avercalc[4]{\foobar,\foo,\foobarfoo}
\end{document}


text:
Q: Prove that $|f(x)|\leq (Mx^2)/2$ It is given that $|f''(x)|<=M$ for all $x$, and $f(0)=f'(0)=0$. Then prove that $|f(x)|\leq\frac{Mx^2}{2}$ for all $x$.
What I think about was by using the Mean Value Theorem twice, and then I will get $|f(x)|\leq Mx^2$ with no $\frac{1}{2}$. And I do not know if I use the MVT twice whethere there would be any mistake.
Is there any way other than the MVT to solve this problem? What I also considered were the Fundamental Theorem of Calculus and the Taylor's Theorem. But still, feel not too good about them.
Anyone offers a hint?

A: It is an immediate consequence of Taylor's theorem.
You have $f(x) = f(0) + f'(0)x + \int_0^x f''(t) (x-t)dt$. Using the facts that $f(0) = f'(0) = 0$ and $|f''(t)| \leq M$, you have $|f(x)| \leq M \int_0^x (x-t) dt = \frac{1}{2} M x^2$, as required.

A: Here's the hint that I can think of :
$$\left|f(x)\right|=\left|\int_0^x\int_0^y f'(t)\; dt\,dy\right|\leqslant \int_0^x\int_0^y|f''(t)|dt\,dy\leqslant\int_0^x\int_0^yM\;dt\;dy$$


text:
Q: Connect Application Gateway with App Service Azure My idea is to connect a Application Gateway with a App Service in a single VNET, but I'm getting a 502 if I try to access my public IP.
I've been reading already this question but I cannot find how to solve my issue.
Right now I have this setup:
Main VNET
Subnet 1 -> Application gateway
Subnet 2 -> App Service
What I tried until now was this configuration using access restrictions on the app service using the public IP of the gateway and also the IP for the private VNET:
Access restrictions
Backend Pool
Http Settings
Even with this I'm having this 404 on the health probe.
Health probe
Should I add in another way the APP Service to the VNET? Is this the good one? What am I doing wrong here?

A: I tried to replicate  the same issue in my workaround and got the below results
I am able to access the app service using application gateway while restricting the IP address in the App service
I have followed the below steps to access the app service through application gateway using private endpoint
I have created the application gateway and configured the

Backend pool

Access restrictions

Http settings

Health probe

I have created the private endpoint with same V-net

Created the virtual machine to access the app service

Connected the bastion service to check weather I am able to access the app service
nslookup url

For related information please refer this document

A: Luckily because you are receiving a 404 that rules out several other potential causes related to reachability.  In the image you provided for your Backend Settings, the "Override with New Hostname" switch is set to No, which means that whatever hostname you reach your App Gateway with will be passed as the hostname to your App Service.  Typically, App Service uses a subdomain of *.azurewebsites.net and if you send either the wrong hostname or no hostname it will respond with a 404.  You can test this by hitting your App Service by the IP address in the browser; you will receive a 404.
If you switch this to Yes, you have two options: You can opt to override the hostname with the FQDN from your Backend Pool, which in your case is an azurewebsites.net subdomain, or you can set this manually.  Either should work in your case.
On top of this, you can configure a custom probe.  If you do not see a probe listed, it's because you are using the default, which sends a hostname of "127.0.0.1" to the backend pool member.  This is the hostname being used to reach your App Service's IP address which is likely why probes are failing with a 404.
By creating a custom probe you can opt to pick the hostname from the Backend Settings or use a custom one.  You'll also see you can adjust the range of acceptable status codes from the default 200-399.  This can be useful in the future if you have a backend that requires authentication and returns a 401 Unauthorized as App Gateway probes are not capable of performing authentication.
Source Documentation on App Gateway probes: https://learn.microsoft.com/en-us/azure/application-gateway/application-gateway-probe-overview


text:
Q: How to get to HTML element of component from another component Vue here is the situation.
Have a component(cmp1) that inside of it uses search bar component (cmp2). My goal is to dig into cmp2 and grab input element to set focus on it when cmp1 renders. How do I achieve it with Vue? What have I tried so far that worked was to set ref on cmp2, than through this.$refs.search.$el.firstChild[0].focus() but I realize that this is not an option. So, perhaps you'd help me out with this one. some screenshots attached. Many thanks!

A: You don't need to manually set these by accessing the child html elements.
If I understand correctly, you want to execute a function of the child triggered by the parent.

*

*One way to do that is to have the parent have a loaded state default to false. Pass the state as a prop to the child, and then you can add a watch for this state to the child. When the loaded changes to true, your watch should trigger the desired action.

*You can complicate things a bit by having an emit in the child pass a function or the input to the parent that you can manage from there.
But as mentioned in the comment, this doesn't need to be a complicated rective situation. I think  what may suffice is having a isFocused prop available to the parent.

example for #1:
in parent:
<template>
  <my-component :isFocused="focusedElement === 'item-1'"/>
</template>

<script>
  data () {
    focusedElement: null
  },
  mounted() {
    this.focusedElement = 'item-1'
  }
</script>

in child/component:
<script>
  params: ['isFocused'],
  watch: {
    isFocused(val){
      if (val === true) {
        this.$refs.input.focus()
      }
    }
  }
</script>

example for #2:
to emit a function, you could do this in the child
  methods: {
    setFocus() { this.$refs.input.focus() }
  }
  mounted() {
    this.$emit('onMounted', this.setFocus);
  },

then, in the parent you would use the @onMounted listener to register the function. you would still need to store the function and manage when the function fires from the parent. I think option one is a better choice

A: *

*Create method in search-payment-component and ref input element:
methods: {
    ...
    focus() { this.$refs.input.focus() }
    ...
}

And call this method in parent component with this.$refs.searchComponent.focus() (yes, you should also ref child component to use it).

*Add prop focused to search-payment-component:
props: ['focused'],
...
watch: {
    focused(val) { val && this.$refs.input.focus() }
}

But you should also provide events when focus is lost as best practice.
[UPDATED]
OR
if you want just focus input on initial rendering:
    props: { focused: Boolean },
    ...
    mounted() {
        focused && this.$refs.input.focus();
    }

    // in parent template
    ...
    // if you just declared attribute(w/o value) it will be true
    <search-payment-component focused ><search-payment-component>
    ...

Also if you want to work with child component in mounted hook you should use it in this.$nextTick method to be sure that child component was rendered.


text:
Q: Textbox multiline imprimindo apenas ultimo item Eu estou usando TextBoxt Multiline para fazer a "emissão" do relatório no próprio sistema.
Ta imprimindo, porém, aparece a seguinte mensagem: "System.Windows.Forms.TextBox" e em seguida, o dado.
public Formulário()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    using (StreamReader ler = new StreamReader(@"escrevesaida.txt"))
    {
        string leitor;

        while ((leitor = ler.ReadLine()) != null)
        {
            textBox1.AppendText($"{leitor}{Environment.NewLine}");
        }
    }
}

A: O problema é que no Text do textBox, para cada linha que ele lê você está atribuindo o valor, substituindo o valor que tinha anteriormente.
textBox1.Text = leitor;

O correto seria concatenar, ou seja, juntar os resultados de cada linha. Da seguinte forma:
textBox1.Text += leitor;

A: Se o objetivo é separar linha a linha, a melhor forma será:
string leitor;

while ((leitor = ler.ReadLine()) != null)
{
    textBox1.AppendText($"{leitor}{Environment.NewLine}");
}

Colocando o seguinte código antes do while:
leitor = ler.ReadLine();
textBox1.Text = leitor;

Estava a "apanhar" a 1ª linha e só depois as restantes. Pode colocar tudo dentro do ciclo.

Em relação ao texto System.Windows.Forms.TextBox, Text: 123, realmente, como o @ThiagoMagalhães referiu, parece ter origem em textBox1.Text += textBox1; ou algo do género. A não ser que isso já venha do ficheiro...


text:
Q: Unable to convert date in valid format PHP I'm creating an application in which user enter a date and make a request. At server side I verify whether user has entered valid date or not . But what the problem comes is PHP isn't converting some of date user enters. For e.g
if user selects 13/10/15 with jquery datetimpicker and I print it,
print_r(date('Y-m-d',strtotime($this->request->post['delivery_date'])));

And its showing
1970-01-01

So I tried to check if any error is there or not. To do so I tried
$date = date_parse($this->request->post['delivery_date']);
print_r($date);

And it's showing an error
[error_count] => 1
[errors] => Array
        (
            [0] => Unexpected character
        )

It works fine for other dates but not with some dates. What should I do? Any help will be appreciated.

A: Forward slash (/) signifies American M/D/Y formatting, and there isn't a thirteenth month in our calendar.
print_r(date('Y-m-d',strtotime("10/13/15")));

Should be good. Or use DateTime::createFromFormat like
$date = DateTime::createFromFormat('d/m/y', '13/10/15');
echo $date->format('Y-m-d'); // 2015-10-13

A:    $str = '24/12/2013';
   $date = DateTime::createFromFormat('d/m/Y', $str);
   echo $date->format('Y-m-d');


text:
Q: https in myapp.appspot.com throws me an error in Firefox when not logged in I want to access myapp.appspot.com through https.
In app.yaml I have done this configuration:
- url: /.*
  script: main.app
  login: optional
  secure: always

When accessing it with Firefox, it throws me this error without being able to access the page.
Your connection is not secure

The owner of www.myapp.appspot.com has configured their website improperly.
To protect your information from being stolen, Firefox has not connected to this website.

This site uses HTTP Strict Transport Security (HSTS) to specify that Firefox may only connect to it securely.
As a result, it is not possible to add an exception for this certificate.

*

*I have tested my web using Chrome, and it works.

I found this in App Engine docs:
It is possible to use to use Strict-Transport-Security in your App engine.
In order to add HTTP Strict-Transport-Security headers (HTST)
to your app, you must be implement the headers within your app's code,
not within your app's config file (app.yaml or appengine-web.xml).

https://cloud.google.com/appengine/kb/#hsts
But I don't know what it means.
What Am I missing?
Thanks.

A: Instead of
https://www.myapp.appspot.com

try
https://myapp.appspot.com

i.e. without the www. I believe GAE doesn't support sub-sub domains except for the case of version numbers.


text:
Q: QLabel with image in round shape I want to display image with round shape in PyQt5/PySide2 application.
Below is the code i tried.
self.statusWidget = QLabel()
img = QImage(":/image.jpg").scaled(49, 49, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
self.statusWidget.setPixmap(QPixmap.fromImage(img))
self.statusWidget.setStyleSheet("border-radius:20px")

I got below output.

And I want Qlabel like below.

A: User avatar QLabel
The best way to make a circular avatar
This method uses the setClipPath QPainter method in conjunction with QPainterPath
to crop the image.
import sys
from PyQt5.QtCore    import Qt
from PyQt5.QtGui     import QPixmap, QPainter, QPainterPath
from PyQt5.QtWidgets import QLabel, QWidget, QHBoxLayout, QApplication

class Label(QLabel):
    def __init__(self, *args, antialiasing=True, **kwargs):
        super(Label, self).__init__(*args, **kwargs)
        self.Antialiasing = antialiasing
        self.setMaximumSize(50, 50)
        self.setMinimumSize(50, 50)
        self.radius = 25

        self.target = QPixmap(self.size())
        self.target.fill(Qt.transparent)

        p = QPixmap("E:/_Qt/img/qt-logo.png").scaled(
            50, 50, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)

        painter = QPainter(self.target)
        if self.Antialiasing:
            painter.setRenderHint(QPainter.Antialiasing, True)
            painter.setRenderHint(QPainter.HighQualityAntialiasing, True)
            painter.setRenderHint(QPainter.SmoothPixmapTransform, True)

        path = QPainterPath()
        path.addRoundedRect(
            0, 0, self.width(), self.height(), self.radius, self.radius)

        painter.setClipPath(path)
        painter.drawPixmap(0, 0, p)
        self.setPixmap(self.target)

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)
        layout = QHBoxLayout(self)
        layout.addWidget(Label(self))
        layout.addWidget(Label(self, antialiasing=False))
        self.setStyleSheet("background: blue;")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())


text:
Q: pros and cons of saving XSL to file vs. db If I had a dynamically generated XSL document and needed to persist it, would there be any pros or cons to writing it to a file or saving it in a DB? Feels like a coin toss at the moment (although db persistence would be easier of the two ), but I wonder if I'm ignoring security implications (performance?)?

A: Write it to a file.  XSL files can have things like
<xsl:include href="../some_other_file.xsl" />

which won't work if it's in a database.  You can get around this with XML catalogs, but really, XSL was designed for file systems.
Edit: I was wrong.  XSL was designed for URIs and you can get this to work in a database.  See the comments.


text:
Q: Calculate Geometric Progression with logarithm I'm trying to find the following summation but cant seem to find the answer. Would really appreciate any help from here!
$$\sum_{i=0}^{k}(4/3)^{i}\log(n/3^i)$$

A: $$(4/3)^i\log(n/3^i)=(4/3)^i(\log n-\log(3^i))=(4/3)^i(\log n-i\log 3)$$
So, your sum is,
$$\log n\left[\sum_{i=0}^k (4/3)^i\right]-\log 3\left[\sum_{i=0}^k i(4/3)^i\right]$$
The first summand has a finite geometric series and the second summand has a finite arithmetico-geometric series. Do you know how to compute them?


text:
Q: Windows10 no longer stays asleep after configuring sshd I've had Windows 10 Home Edition running for a year and half without problems. I set up my PC's power button to put the OS into sleep mode. The other day I was trying to set up sshd. I used Windows PoweShell to run some commands like in this tutorial.
Ever since then, Windows no longer stays asleep. I press the power button and Windows goes through the motions of going into sleep mode. It hums for a bit then the screen goes blank. But then after a few minutes, the screen turns back on and the log in screen is shown.
Similar behavior happens when I enable Wi-Fi Mobile Hotspot, allowing me to tether my cell phone to my PC's internet connection. When I have Mobile Hotspot enabled, the computer refuses to enter sleep mode.
I tried undo my sshd installation, but these commands didn't resolve the issue:
# Uninstall the OpenSSH Client
Remove-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

# Uninstall the OpenSSH Server
Remove-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

So I'm at a loss of what to try next.


text:
Q: What does rspec's eq method actually test for? I'm a bit confused:
class SessionsController < ApplicationController
    def new
        @user = User.new
    end
end

I would have thought that all three of the following expectations would pass:
require 'spec_helper'

describe SessionsController do
    describe '#new' do
        let(:user) { FactoryGirl.build(:user, name: nil, email: nil, password: nil, password_confirmation: nil)}
        before { get :new }

        it { expect(assigns(:user)).to eq user }

        it { expect(assigns(:user)).to eq User.new }

        it "should assign stubbed user" do
            assigns(:user).should eq user
        end
    end
end

And yet I get this:
FFF
Failures:
  1) SessionsController#new should eq #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
     Failure/Error: it { expect(assigns(:user)).to eq user }

       expected: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
            got: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>

       (compared using ==)

       Diff:
     # ./spec/controllers/sessions_controller_spec.rb:8:in `block (3 levels) in <top (required)>'

  2) SessionsController#new should eq #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
     Failure/Error: it { expect(assigns(:user)).to eq User.new }

       expected: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
            got: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>

       (compared using ==)

       Diff:
     # ./spec/controllers/sessions_controller_spec.rb:10:in `block (3 levels) in <top (required)>'

  3) SessionsController#new should assign stubbed user
     Failure/Error: assigns(:user).should eq user

       expected: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
            got: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>

       (compared using ==)

       Diff:
     # ./spec/controllers/sessions_controller_spec.rb:13:in `block (3 levels) in <top (required)>'

I mean what? The Diff section is even empty. If I was using the be matcher I'd understand, but I'm using eq, so what's going on?

A: In ActiveRecord two model objects are considered equal if they have the same class and the same non-nil primary key values.
So if two identical objects have nil id values they are not equal.
See https://github.com/rails/rails/blob/master/activerecord/lib/active_record/core.rb#L290
That may seem odd but it makes sense if you consider that those two objects if they were ever saved would be allocated two different id values by the database. So until their id of an ActiveRecord model object is allocated it cannot be compared meaningfully with another.

A: Try comparing user.attributes using the eq method instead and it should pass.


text:
Q: Elvis Operator vs Non-Null Assertion: Diff Between These Statements? Trying to understand null safety in Kotlin: both of these following statements seem to work fine and be interchangeable in my program:
var y1: Double = 0.0
    get() = when(hasParent) {
        true -> parent!!.y1
        else -> field
    }

and
var y1: Double = 0.0
    get() = parent?.y1!!

(hasParent is simply a getter to see if parent is null or not)
Are these two semantically the same or are they actually different expressions that mean different things? And if they mean the same thing semantically, is the first ever preferred over the second for any reason?

A: In this case you don't need hasParent. The form which is applicable is this:\
var y1: Double = 0.0
    get() = parent?.y1 ?: field

The problem with your second getter is that it will try to return the parent.y1 no matter what and it will throw a NullPointerException if it is not there.
If you use IDEA you'll get warnings for these kinds of problems so they are an easy fix, but you need to be aware of the so called platform types which come from Java code:
val queue: Queue<String> = LinkedList()
queue.peek().toInt()

Here the compiler won't complain for .toInt() although it is possible to get a null from the Queue. I've written about this here.

A: Note that jingx's and Adam Arold's answer is good for the current situation, but it wouldn't be equivalent to your first snippet if the type of y1 was nullable: if parent is not null, but parent.y1 is, then your code gives null and parent?.y1 ?: field gives field.
I'd say the actual preferred form if you need the first behavior is
if (parent != null) parent.y1 else field // if parent is val without a custom getter
parent.let { if (it != null) it.y1 else field } // otherwise

Using hasParent hides from the compiler that you actually checked for null and don't need !!.


text:
Q: Replacing [InnerHTML] code with another How to replace [innerhtml] line of code with other to allow all user-defined properties in angular 4 ?
[ng...]="..." ? [innerHTML]="..." ?
When I wanted to insert any user-defined files it did not allow me to do it.

A: Solution 1:

{{htmlContent}}

Solution 2:

Solution 3:


text:
Q: Redisson + redis sentinel. how to handle failover and write into redis? I have just edited my previous question, and I am providing more details, (hopefully someone would be able to help).
I have a Redis cluster with 1 master and 2 slaves. All 3 nodes are managed by Sentinel. The failover works fine and when the new master is elected, I can write on the new master (from the command line).
Now, I am trying to write a small Java program using Redisson, which ideally should write records into redis, and be able to handle the failover (which it should do as far as I have understood). This is my code until now.
import org.redisson.Redisson;
import org.redisson.RedissonNode;
import org.redisson.api.*;
import org.redisson.api.annotation.RInject;
import org.redisson.config.Config;
import org.redisson.config.RedissonNodeConfig;
import org.redisson.config.SubscriptionMode;
import java.util.Collections;
import java.util.UUID;

public class RedissonTest {

    public static class RunnableTask implements Runnable {
        @RInject
        RedissonClient client;

        @Override
        public void run(){
            System.out.println("I am in ..");
            RMap<String, String> map = client.getMap("completeNewMap");
            System.out.println("is thread interrupted?? " + Thread.currentThread().isInterrupted());

            NodesGroup ngroup = client.getNodesGroup();
            Collection<Node> nodes = ngroup.getNodes();
            for(Node node : nodes){
                System.out.println("Node ip "+ node.getAddr().toString()+" type: "+node.getType().toString());
            }

            for(int i=0; i < 10000; i++) {
                String key = "bg_key_"+String.valueOf(i);
                String value = String.valueOf(UUID.randomUUID());
                String oldVal = map.get(key);
                map.put(key, value);

                RBucket<String> bck = client.getBucket(key);

                bck.set(value);

                System.out.println("I am going to replace the old value " + oldVal + " with new value " + value + " at key "+key);

            }
            System.out.println("I am outta here!!");
        }
    }

    public static void main(String[] args) {
        Config config = new Config();
        config.useSentinelServers()
                .setMasterName("redis-cluster")
                .addSentinelAddress("192.168.56.101:26379")
                .addSentinelAddress("192.168.56.102:26379")
                .addSentinelAddress("192.168.56.103:26379")
                .setPingTimeout(100)
                .setTimeout(60000)
                .setRetryAttempts(25)
                .setReconnectionTimeout(45000)
                .setRetryInterval(1500)
                .setReadMode(ReadMode.SLAVE)
                .setConnectTimeout(20000)
                .setSubscriptionMode(SubscriptionMode.MASTER);

        RedissonClient client = Redisson.create(config);

        RedissonNodeConfig nodeConfig = new RedissonNodeConfig(config);
        nodeConfig.setExecutorServiceWorkers(Collections.singletonMap("myExecutor6", 1));
        RedissonNode node = RedissonNode.create(nodeConfig);
        node.start();

        System.out.println("Node address "+node.getRemoteAddress().toString());
        RExecutorService e = client.getExecutorService("myExecutor6");
        e.execute(new RunnableTask());
        e.shutdown();
        if(e.isShutdown()) {
            e.delete();
        }
        client.shutdown();
        node.shutdown();
        System.out.println("Hello World!" );
    }

}

Running the code, a couple of things that I don't understand happen.
The first one is:

*

*why redisson recognise my 3 hosts as redis slaves??

*why the key value pairs I created are not stored into redis??

The idea is that after I have been able to write into redis, I would start to test the failover killing the master and expecting that the program will manage it and continues to write to the new master, without losing a message(it would be nice to be able to cache the messages while the failover occurs).
What happen with this simple program is that I can write into redis, but when I kill the master, the execution just hangs for a time that seems to be close to the setTimeout and exits without completing the task.
Any suggestion?

A: You should set retryAttempts parameter big enough to make Redisson survive failover period.


text:
Q: Automatically use the directory as the project name in CMake I'm fairly new at using CMake to manage my build system, so if I'm being stupid and this is a bad idea, please let me know.
I'd like to be able to set up my cmakelists.txt file so that when I do
project( ... )

the name of the directory becomes the project name automatically.  I want to do this because I find it convenient to be able to copy the entire directory of one project as the starting point of another.  However, though I always rename the directory to something meaningful, I often forget to change the project(name) line of the cmakelists.txt file, and then I end up with multiple projects open in my build environment with the same name, which gets confusing.
Ideally, if there are spaces in the directory name they'd be replaced by underscores.
Can CMake do this? And is it a bad idea for some reason I'm not seeing?

A: I think CMAKE_CURRENT_LIST_DIR more suitable for this case
get_filename_component(ProjectId ${CMAKE_CURRENT_LIST_DIR} NAME)
string(REPLACE " " "_" ProjectId ${ProjectId})
project(${ProjectId} C CXX)

A: You can achieve this by adding the following to the start of your CMakeLists.txt:
get_filename_component(ProjectId ${CMAKE_CURRENT_SOURCE_DIR} NAME)
string(REPLACE " " "_" ProjectId ${ProjectId})
project(${ProjectId})

I don't see a problem with doing this for throwaway projects, although I guess production projects would normally have a predefined name which would be set explicitly in the project command.
When you mention that you "copy the entire directory of one project as the starting point of another", I assume you don't include the build tree when you copy?  CMake isn't really able to handle the build tree being moved.

A: Newer CMake (3.20+) supersedes get_filename_component with cmake_path:
cmake_path(GET CMAKE_CURRENT_SOURCE_DIR FILENAME ProjectName)
string(REPLACE " " "_" ProjectId ${ProjectName})
project(${ProjectName})


text:
Q: How do I approach this combinatorics problem involving labeled and unlabelled configurations Here is the question:

If we allow  f(n) and g(n) to represent the number of labeled and
  unlabelled configurations, respectively, of n objects, then why is
  the following reasonable?  You  should include your assumptions
  (e.g., how you understand the  terms "labeled" and "unlabelled").
f(n)/n! ≤ g(n) ≤ f(n)

I appreciate any tips or advice.

A: If you take an unlabeled configuration, in how many ways can you apply labels to the objects? What happens if these are all identical? What happens if they're all distinct?


text:
Q: Unable to access NuGet sources I am trying to add a NuGet package from a private source; https://[provider].pkgs.visualstudio.com/[package]/nuget/v3/index.json (provider and package is left out intentionally).
I have added the sources to a local Nuget.Config file in my project
<configuration>
    <packageSources>
        <add key="[name]" value="https://[provider].pkgs.visualstudio.com/_packaging/[package]/nuget/v3/index.json" />
    </packageSources>
    <packageSourceCredentials>
        <[name]>
            <add key="Username" value="[username]" />
            <add key="Password" value="[password]" />
        </[name]>
    </packageSourceCredentials>
</configuration>

and when i request a list of sources through CLI I get the following
Registered Sources:

  1.  [name] [Enabled]
   https://[provider].pkgs.visualstudio.com/_packaging/[package]/nuget/v3/index.json
  2.  nuget.org [Enabled]
      https://api.nuget.org/v3/index.json

However when I try to add the specific package to my project I get the following error
error: Unable to load the service index for source https://[provider].pkgs.visualstudio.com/_packaging/[package]/nuget/v3/index.json.
error: Response status code does not indicate success: 401 (Unauthorized).

The natural explanation would of course be that I entered invalid credentials. However, when I access the source in a browser I am able to login with the same credentials and inspect the index.json file.
I am wondering if I could be missing something in the process of adding a private NuGet source?
(NuGet Version: 4.9.3.5777)

A: I just found out what I was missing. I needed to install Azure Artifacts Credential Provider and follow the instructions on the GitHub page.