text:
Q: Java mouse operations I am writing a game in Java, and need to have mouse interaction. I was going to use MouseAdapter, but I've looked into it some, and it does not seem to have any means of determining the location of the mouse pointer without a click or action being done... What would be the recommended way of doing this?
A couple questions:

*

*Would the mouse "location" refer to the location of the mouse in relation to the bounds of the monitor, the bounds of the game, or would it be represented as movements relative to a previous location?

*How would one disable the mouse pointer in a windowed application? (ie. A first person shooter where the mouse movements rotates the players view rather than move a pointer) Is this possible?

A: Look at the MouseMotionListener.  This will allow you to track mouse movements.  It will give you the location of the mouse within the component that it is attached to.  But if you look at SwingUtilities class there are some convenience methods to convert points to the screen or other components or the monitor.
For the cursor, you have the option to set your own bitmap for the cursor, you can look here.  Or for a more recent SO answer, you can look here. So you could hide the cursor, or set it to an empty bitmap, and then intercept the mouse movements and events to control your view.

A: A tutorial on mouse events is at:
http://java.sun.com/docs/books/tutorial/uiswing/events/mouselistener.html
If you look here:
http://java.sun.com/javase/7/docs/api/java/awt/event/MouseEvent.html
you can get the absolute location, on the screen, or coordinates relative to the component.
If there is a movement to change direction then you will need to remove the mouse listener, or you can just have some logic where the event handler will just exit, doing nothing.  I think this would be better, otherwise you have to keep track of when you add and remove the listeners.


text:
Q: При запросе SQL через тело функции PHP получаю ошибку Мучаюсь с такой проблемой:
Мне нужно чтобы при клике по radio получить значение этого radio и передать его в SQL запрос. В JS я получаю значение.
$("input[name='select_account']").on('click', function () {
    var x = $("input[name='select_account']:checked").val();
})

Потом как я понимаю его надо передать в PHP и сделать запрос через SQL. Соответственно я делаю функцию, которая передают это значение, однако при получении запроса я получаю ошибку (Query failed). Однако если я запущу код запроса вне тела функции, то никакой ошибки не возникает.
function sql_query($user_id) {
    $query = 'select * from users WHERE id='.$user_id.';';
    $query_result = mysqli_query($connection, $query);
        if(!$query_result) {
            die('Query failed'.mysqli_error());
        } else {
            echo ('Complete');
        }
        return $query_result;
}

$connection я получаю ранее в коде без ошибок.
И вообще может я зря мучаюсь с этой функцией, может есть более простое решение?
Проблема решилась добавлением в функцию строки:
global $connection;

Спасибо всем за подсказки!

redpajama_set_name: RedPajamaStackExchange


text:
Q: best way to parallelize calculations on time series data in matlab I have a linux cluster with Matlab & PCT installed (128 workers with Torque Manager), and I am looking for a good way to parallelize my calculations.
I have a time-series Trajectory data (100k x 2) matrix. I perform maximum likelihood (ML) calculations that involve  matrix diagonalization, exponentiation & multiplications, which is running fast for smaller matrices. I divide the Trajectory data into small chunks and perform the calculations on many workers (coarse parallelization) and don't have any problems here as it works fine (gets done in ~30s)
But the calculations also depend on a number of parameters that I need to vary & test the effect on ML. (something akin to parameter sweep).
When I try to do this using a loop, the calculations becomes progressively very slow, for some reason I am unable to figure out.
%%%%%%% Pseudo- Code Example:

% a [100000x2], timeseries data
load trajectoryData

% p1,p2,p3,p4 are parameters
% but i want to do this over a multiple values fp3 & fp4 ;
paramsMat = [p1Vect; p2Vect;p3Vect ;p4Vect];
matlabpool start 128

[ML] = objfun([p1 p2 p3 p4],trajectoryData) % runs fast ~ <30s

%% NOTE: this runs progressively slow
for i = 1:length(paramsMat)

     currentparams = paramsMat(i,:);
     [ML] = objfun(currentparams,trajectoryData)
end
matlabpool close

The objFunc function is as follows:
% objFunc.m
[ML] = objFunc(Params, trajectoryData)

% b = 2 always
[a b] = size(trajectoryData) ;

% split into fragments of 1000 points  (or any other way)
fragsMat = reshape(trajectoryData,1000, a*2/1000) ;

% simple parallelization. do the calculation on small chunks
parfor ix = 1: numFragments
   % do heavy calculations
   costVal(ix) = costValFrag;
end

% just an example;
ML = sum(costVal) ;

%%%%%%

Just a single calculation oddly takes ~30s (using the full cluster) but within the for loop, for some weird reason there is damping of speed & even within the 100th calculation, it becomes very slow. The workers are using only 10-20% of CPU.
If you have any suggestions including alternative parallelization suggestions it would be of immense help.

A: If I read this correctly, each parameter set is completely independent of all the others, and you have more parameter sets than you do workers.
The simple solution is to use a batch job instead of parfor.
job_manager = findresource( ... look up the args that fit your cluster ... )
job = createJob(job_manager);
for i = 1:num_param_sets
    t = createTask(job, @your_function, 0, {your params});
end
submit(job);

This way you avoid any communications overhead you have from the parfor of the inner function, and you keep your matlabs separate. You can even tell it to automatically restart the workers between tasks (I think), as one of the job parameters.

A: What is the value of numFragments? If this is not always larger than your number of workers, then you will see things slowing down.
I would suggest trying to make your outer for loop be the parfor. It's generally better to apply the parallelism at the outermost level.


text:
Q: Radio Input onChange only fires once? I have a simple task I'm trying to accomplish: Fire a function whenever a radio button is toggled between its group.
class App extends Component {
    onButtonClick() {
        console.log('something was clicked!')
    }

    return (

        <button onClick={this.onButtonClick.bind(this)}>
            Click me
        </button>
        <input
            type="checkbox"
            onChange={this.onButtonClick.bind(this)}
        />
        <input
            type="radio"
            value="yes"
            name="answer"
            onChange={this.onButtonClick.bind(this)}
        />
        <input
            type="radio"
            value="no"
            name="answer"
            onChange={this.onButtonClick.bind(this)}
        />

    )
}

The button and checkbox work just fine. If you click on it, it fires the function multiple times. The radio buttons fire once and then stop.
It's almost as if ReactJS stops watching for the onChange for radio buttons for some reason. Any help would be greatly appreciated. Thank you!
UPDATE
It seems like it works properly in https://codesandbox.io/s/rGMGzJNL, but is not working properly in my local environment which is utterly perplexing. Will update if I figure out what is going on, but would appreciate any guidance if anyone has run into this before!

A: You need to set checked property on each radio and  save radio status in state.
class App extends Component {
  state = {
    radio: 'yes',
  }

  onButtonClick() {
    console.log("something was clicked!");
  }

  onRadioChange(value) {
    console.log("radio change");
    this.setState({
      radio: value,
    })
  }

  render() {
    return (

        <button onClick={() => this.onButtonClick()}>
          Click me
        </button>
        <input type="checkbox" onClick={() => this.onButtonClick()} />
        <input
          type="radio"
          value="yes"
          name="answer"
          checked={this.state.radio === 'yes'}
          onChange={(e) => this.onRadioChange('yes')}
        />
        <input
          type="radio"
          value="no"
          name="answer"
          checked={this.state.radio === 'no'}
          onChange={(e) => this.onRadioChange('no')}
        />

    );
  }
}


text:
Q: Creating minimal release-ready header file for C++ class I made a C++ class that I've put in its own static library.
I also decided to create a minimal header file that would allow other people to see the public: part of the class. So I basically took the original header file (which is rather long, contains the private: and public: parts of the class, etc.), and stripped out everything but the public: part (which is short, only the constructor/destructor and one public function).
To test things out I've created a dummy project that would use the library. The thing is, whenever I use the minimal header file in that project, it crashes with messages like:
test(44349) malloc: *** error for object 0x7fdab2c242e8: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug

But whenever I include the original header file, it works fine.
What could be the problem? It compiles fine (no warnings even with -Wall) using both the minimal and the original header files.

A: That doesn't work and violates the one-definition rule: Every class must have precisely one definition, and each translation unit must see the exact same definition, or otherwise your program is ill-formed, and worse, no diagnostic is required.
You might be better served with the PIMPL idiom, by which you split your class into two parts, and you do not need to expose the implementation component:
// Ship this:

class FooImpl;

class Foo
{
    std::unique_ptr<FooImpl> impl;
public:
    Foo();
    void do_magic();
};

// Don't ship this:

class FooImpl { void magic(); };
void FooImpl::magic() { /* secret code */ }

Foo::Foo() : impl(new FooImpl) { }
void Foo::do_magic() { impl->magic(); }

See Herb Sutter's GotW #101 for a nice general-purpose framework for PIMPL classes.

A: You cannot remove the private/protected part of a class from the interface: the compiler using the interface must know of the (private/protected) member variables and virtual functions, otherwise it would have a wrong idea of the class instances and the virtual table.


text:
Q: Tomcat HTTPS only except 1 endpoint I already configured my Connector in the server.xml with the redirection from 8080 to 8443, and set the security-constraint in web.xml with the appropriate sub-tags. It redirects properly, but I would like to ignore the HTTP access and use only HTTPS. So I do not need redirection or smthing like that. An external service requires HTTP access for an endpoint, I would like to enable only that endpoint over HTTP.
I tried to remove the Connector with 8080 port, but with this approach there is no chance to get the request over http.

A: If you disable http conection you will not have an access to your application over http.
So you can implement a filter that checks if the protocol of current request is HTTP and endpoint URL is allowed otherwise block the request.
In your web.xml you can declare following filter:
<filter>
    <filter-name>blockHttpFilter</filter-name>
    <filter-class>com.example.BlockHttpFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>urlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Implementation may be following:
public class BlockHttpFilter implements Filter {

    private ServletContext context;

    public void init(FilterConfig fConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if(req.isSecure() && checkHttpEnpointPath(req)){
            chain.doFilter(request, response);
        } else {
            HttpServletResponse res = (HttpServletResponse)response;
            res.sendError(403);
         }
    }

    public void destroy() {
        //we can close resources here
    }

}


text:
Q: Can't increment integer in Cocos2d-x V 3.0 I need to increment an integer.I have this code here :
Utils.h :
class Utils{
static HUD* hudLayer();
static Layer* layerWithTag(int tag);
};

Utils.cpp :
HUD* Utils::hudLayer(){
    return (HUD*)Utils::layerWithTag(TAG_HUD);
}
Layer* Utils::layerWithTag(int tag)
{
    Scene *sc = Director::getInstance()->getRunningScene();
    if (sc->getTag() == TAG_GAME_SCENE) {
        Layer *layer = (Layer *)sc->getChildByTag(tag);
        return layer;
    }
    return NULL;
}

HUD.h
class HUD : public Layer{

public:
    int score1;
    Label* scoreLabel1;
    virtual bool init();
    void didScore();
    CREATE_FUNC(HUD);
};

HUD.cpp :
bool HUD::init(){
    if(!Layer::init()){return false;}
    score1 = 0;

    scoreLabel1 = Label::createWithSystemFont(CCString::createWithFormat("Score : %d",score1)->getCString(), "Arial", 64);
    scoreLabel1->setAnchorPoint(Point(0.0f, 1.0f));
    scoreLabel1->setPosition(Point(20, Utils::s().height-10));
    this->addChild(scoreLabel1);
    return true;
}
void HUD::didScore(){
    score1+=10; // Error HERE after coming from onTouchBegan (says parentis null)
    scoreLabel1->setString(CCString::createWithFormat("Score : %d",score1)->getCString());
}

In GameScene.h now i have this in onTouchBegan method :
bool GameScene::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
    Point location = touch->getLocationInView();
    location = Director::getInstance()->convertToGL(location);

    if(location.x < 300.0f){
        Utils::hudLayer()->didScore();
    }
    return true;
}

What am i doing wrong here ?
I can increment an integer in V 2.x the same way but not in V 3.0 . WHY ?

A: In cocos2d-x v3 is a new listener system for events (touches, accelerometr etc.), you need to create listener for getting touches. In GameScene::init you should put something like that
auto listener1 = EventListenerTouchOneByOne::create();
listener1->setSwallowTouches(true);
listener1->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchBegan, this);

this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener1, this);

Look at:
http://www.cocos2d-x.org/wiki/EventDispatcher_Mechanism


text:
Q: Web Application under Tomcat with SSL I wanted to secure an application I developed recently, and I following mkyong's tutorial.
It worked only for tomcat manager's pages.
Indeed, I use the  <transport-guarantee>CONFIDENTIAL</transport-guarantee> with <auth-method>CLIENT-CERT</auth-method>.
At the beginning, I wasn't sure about mkyong's certificate, so I followed instructions in maximporges.
I keep getting error code 401.
When I change auth-method from CLIENT-CERT to BASIC, I am prompted to enter login and password, I enter a user's credentials that exists in tomcat-users.xml, and it works.
I tried to add a user in tomcat-users.xml like <user username="CN=xxxx xxx xxx, O=knmi, O=users, O=dutchgrid" password="null" roles="abc" /> I duplicate the exact same information entered previously for the certificate, but doesn't work.
I think the server can't find the client's certificate
Note: I had to change protocol="HTTP/1.1" to protocol="org.apache.coyote.http11.Http11AprProtocol" in server.xml to avoid getting ERR_BAD_SSL_CLIENT_AUTH_CERT.

A: [Response from comments]
To stablish a secure connection you do not need a client certificate. Here you are a simple tutorial http://www.mkyong.com/tomcat/how-to-configure-tomcat-to-support-ssl-or-https/
If you want a 'green bar' I suggest buy an SSL certificate instead of generating one
Tomcat tag in web.xml is not needed. See Is security-constraint configuration for Tomcat mandatory?
<transport-guarantee>CONFIDENTIAL</transport-guarantee>

To force HTTPS disable the http connector, usually on port 8080. Then, only the https connector will be reachable


text:
Q: How to get URL preview of link shared in tweet using Twitter API? I'm using the Tweet Lookup API (part of V2). When a user shares a link in a tweet, a preview of that URL is generated in that tweet. I want to recreate this using API. So how can I get the preview image of the URL and also other details like the domain, etc?
For example, if you look at this tweet: https://twitter.com/elonmusk/status/1429907171639103489

If you see the above tweet, there's a URL preview card, with image of starlink and a brief description of the link. How to get these details through the Twitter API?

A: I suppose I am a little late, but..!
Unfortunately, to my knowledge there is no way to get the preview image from the twitter API.
You have to find the link from the tweet, get that site and scrape the image from there. Websites can tell twitter what image they want to use by making a  tag that has the property "twitter:image"!
--
What you can do, for example, is get the original URL for the post from entities!
E.g. making the tweet look-up like this:
https://api.twitter.com/2/tweets/1532014165686206466?tweet.fields=entities
From there, get the original url, for example from the "unwound_url" in the JSON response of that look-up example.
You need to make a request to that site and from the html response, look for a  tag that has the property set to "twitter:image"
In that tags content you have your image link!
See:
https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets-id
https://developer.twitter.com/en/docs/twitter-api/data-dictionary/object-model/tweet
I hope my rambling made sense and good luck!

A: Unfortunately, this is impossible because Twitter requires URLs with Twitter meta tags in order to show these Links as cards with images. So the only way to do that is to add these meta Tags in the head of your website :

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="LINK TITLE HERE">
<meta name="twitter:description" content="LINK DESCRIPTION HERE">
<meta name="twitter:image" content="PREVIEW IMAGE HERE">

This is how I made it on my own website. I hope that will help you.


text:
Q: Rails ActiveAdmin create resource for PublicActitivity gem I am a Fan of Rails Active Admin plugin, it is quite Easy and good administration tasks.
gem 'activeadmin'
gem 'public_activity'

For news feed, I am using another gem public activity gem. I trying to create an active admin page for Activity feeds.

A: I found solutions for this and it was very very easy,
  rails generate active_admin:resource MyModel

Replacing MyModel with PublicActivity::Activity worked for me.
  rails generate active_admin:resource PublicActivity::Activity


text:
Q: How to give a Fargate Task the right permissions to upload to S3 I want to upload to S3 from a Fargate task. Can this be achieved by only specifying a ExecutionRoleArn as opposed to specifying a both a ExecutionRoleArn and a TaskRoleArn?
If I specify a ExecutionRoleArn that has the following Permission Policies attached:
Custom policy:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::example_bucket/*"
        }
    ]
}

AmazonECSTaskExecutionRolePolicy:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecr:GetAuthorizationToken",
                "ecr:BatchCheckLayerAvailability",
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

With the following trust relationship:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "events.amazonaws.com",
          "lambda.amazonaws.com",
          "ecs-tasks.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

Would this be sufficient to allow the task to upload to S3? Or do I need to define a TaskRoleArn?

A: The ExecutionRoleArn is used by the service to setup the task correctly, this includes pulling any images down from ECR.
The TaskRoleArn is used by the task to give it the permissions it needs to interact with other AWS Services (such as S3).
Technically both Arns could be the same, however I would suggest separating them to be different roles to avoid confusion over the permissions required for both of the scenarios the role is used for.
Additionally you should have the endpoint for ecs.amazonaws.com. In fact the full list of services depending on how you're using ECS are below (although most could be removed such as spot if you're not using spot, or autoscaling if you're not using autoscaling).
"ecs.amazonaws.com",
"ecs-tasks.amazonaws.com",
"spot.amazonaws.com",
"spotfleet.amazonaws.com",
"ecs.application-autoscaling.amazonaws.com",
"autoscaling.amazonaws.com"

A: In the case of Fargate, both IAM role pay different role

*

*Execution Role
This is role is mandatory and you can not run the task without this role even if you add ExecuationRole policy  in Task Role
To produce this error just set Execution role =None, you will not able to launch the task.

AWS Forums (Unable to create a new revision of Task Definition)

*

*Task Role
This role is optional and you can add s3 related permission in this role,

Optional IAM role that tasks can use to make API requests to authorized AWS services.

Your police seems okay,

*

*Create ecs_s3_upload_role

*Add below policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::example_bucket/*"
        }
    ]
}

Now Fargate Task will able to upload to S3 bucket.

A: Your policies don't include any s3 related permissions. Thus you  should define your s3 permissions in a task role:

With IAM roles for Amazon ECS tasks, you can specify an IAM role that can be used by the containers in a task.


text:
Q: How to Write a Custom Snitch for Apache Cassandra? I'm currently attempting to write a new snitch that makes minor tweaks and improvements to SimpleSnitch that comes with the "out of the box" Apache Cassandra.
My current objective is, instead of the pre-made Dynamic Snitch that comes as a wrapper of subsnitches provided by Cassandra, to create my own snitch that is able to inform Cassandra about which nodes to send requests to. Whereas most snitches simply inform Cassandra about the topology of the network, I want to inform Cassandra about which node to send to, and where that node resides.
My main trouble is finding how to get my snitch to interact with Cassandra in a way that exceeds the scope of requesting for topological data. For example, my public String getDatacenter(InetAddress endpoint) function is actively being called, however this is the only function in my program that is called by Cassandra. I would love to be able to write some function, public String getBestNode(), that returns the IP of the node to Cassandra when it requests for it. However, I can't seem to find any information online that provides me with functions to override/write myself that Cassandra calls for.
If anyone has a good Snitch writing resource they could link me, that would be greatly appreciated. Otherwise, I would be thankful for any advice anyone has for me.


text:
Q: SQL query with two self-joins - is there a better way could you help with this query please.
Table structure is as folllows:
PropertyOwner

*

*Number (primary key)

*PropertyId (primary key)

*OwnerId

Property

*

*PropertyId (primary key)

*LoanId (primary key)

Now, if I have a LoanId, how can I find all properties of property ownerId's who have taken the given LoanId?
I am having the below now but it looks awkward:
Select po.OwnerId, po.PropertyId
from Property
join PropertyOwner po on po.PropertyId= Property.PropertyId
join PropertyOwner po2 on po2.OwnerId = po.OwnerId
join Property pp on po2.PropertyId= pp.PropertyId and pp.LoanId = @_givenLoanId

Is there a better way?

A: Exists comes to mind as being a more direct interpretation of what you are doing:
Select po.OwnerId, po.PropertyId
from PropertyOwner po
where exists (select 1
              from Property p2 join
                   PropertyOwner po2
                   on p2.PropertyId = po2.PropertyId
              where po2.OwnerId = po.OwnerId and
                    p2.LoanId = @_givenLoanId
             );

A: This is what you're looking for:
SELECT OwnerId, PropertyId
FROM PropertyOwner
WHERE OwnerId IN
(
    SELECT DISTINCT o.OwnerId
    FROM Property p
    JOIN PropertyOwner o
        ON o.PropertyId = p.PropertyId
    WHERE LoanId = @_givenLoanId
);


text:
Q: Python - Extract data from csvfile1 and write to csvfile2 based on values in columns I have data stored in a csv file :
ID;Event;Date
ABC;In;05/01/2015
XYZ;In;05/01/2016
ERT;In;05/01/2014
...     ...       ...
ABC;Out;05/01/2017

First, I am trying to extract all rows where Event is "In" and saves thoses rows in a new csv file. Here is the code i've tried so far:
[UPDATED : 05/18/2017]
with open('csv_in', 'r') as f, open('csv_out','w') as f2:
    fieldnames=['ID','Event','Date']
    reader = csv.DictReader(f, delimiter=';', lineterminator='\n',
    fieldnames=fieldnames)
    wr = csv.DictWriter(f2,dialect='excel',delimiter=';',
    lineterminator='\n',fieldnames=fieldnames)
    rows = [row for row in reader if row['Event'] == 'In']
    for row in rows:
        wr.writerows(row)

I am getting the following error : " ValueError: dict contains fields not in fieldnames: 'I', 'D'
[/UPDATED]
1/ Any thoughts on how to fix this ?
2/ Next step, how would you proceed to do a "lookup" on the ID (if exists several times as per ID "ABC") and extract the given "Date" value where Event is "Out"
output desired :
ID        Date         Exit date
ABC     05/01/2015     05/01/2017
XYZ     05/01/2016
ERT     05/01/2014

Thanks in advance for your input.
PS : can't use panda .. only standard lib.

A: you can interpret the raw csv with the standard library like so:
oldcsv=open('csv_in.csv','r').read().split('\n')

newcsv=[]

#this next part checks for events that are in

for line in oldcsv:
    if 'In' in line.split(';'):
       newcsv.append(line)

new_csv_file=open('new_csv.csv','w')
[new_csv_file.write(line+'\n') for line in newcsv]
new_csv_file.close()

you would use the same method to do your look-up, it's just that you'd change the keyword in that for loop, and if there's more than one item in the newly generated list you have more than one occurance of your ID, then just modify the condition to include two keywords

A: The error here is because you have not added a delimiter.
Syntax-
csv.DictReader(f, delimiter=';')
For Part 2.
import csv
import datetime

with open('csv_in', 'r') as f, open('csv_out','w') as f2:
    reader = csv.DictReader(f, delimiter=';')
    wr = csv.writer(f2,dialect='excel',lineterminator='\n')
    result = {}
    for row in reader:
      if row['ID'] not in result:
        # Assign Values if not in dictionary
        if row['Event'] == 'In':
          result[row['ID']] = {'IN' : datetime.datetime.strptime(row['Date'], '%d/%m/%Y') }
        else:
          result[row['ID']] = {'OUT' : datetime.datetime.strptime(row['Date'], '%d/%m/%Y') }
      else:
          # Compare dates with those present in csv.
          if row['Event'] == 'In':
            # if 'IN' is not present, use the max value of Datetime to compare
            result[row['ID']]['IN'] = min(result[row['ID']].get('IN', datetime.datetime.max), datetime.datetime.strptime(row['Date'], '%d/%m/%Y'))
          else:
            # Similarly if 'OUT' is not present, use the min value of datetime to compare
            result[row['ID']]['OUT'] = max(result[row['ID']].get('OUT', datetime.datetime.min), datetime.datetime.strptime(row['Date'], '%d/%m/%Y'))
    # format the results back to desired representation
    for v1 in result.values():
      for k2,v2 in v1.items():
        v1[k2] = datetime.datetime.strftime(v2, '%d/%m/%Y')
    wr.writerow(['ID', 'Entry', 'Exit'])
    for row in result:
      wr.writerow([row, result[row].get('IN'), result[row].get('OUT')])

This code should work just fine. I have tested it on a small input


text:
Q: Is there an implementation somewhere of the yellow screen of death? In ASP.NET when you are in DEBUG mode and something fails you get a the famous yellow screen of death.
It shows that there was a Server Error in <Location> Application, provides a description, exception details, source file and stack trace.
I would like to extend this error page to include some extra information.

*

*Is there an "open source" implementation of the yellow screen of death?

*Is there a way to extend the built-in yellow screen of death?

A: This page seems to have the info you're looking for.
http://www.asp.net/hosting/tutorials/processing-unhandled-exceptions-cs
Essentially, when an exception bubbles up to to the runtime it gets wrapped in an System.Web.HttpException (This was wrong.  At least I didn't see this behavior in MVC 3).
I'd think you can extend that class and override GetHtmlErrorMessage to return whatever extra data you want.
Update:  Well, with a little experimentation it appears I'd be wrong. BUT there is a workaround...
You can write the info from the exception in any manner you choose then clear the error and you'll have what you want returned.
Something like this...
protected void Application_Error(object sender, EventArgs e)
{
    var context = HttpContext.Current;
    var error = context.Server.GetLastError();
    context.Response.Write(error.Message);
    context.Response.Write("

");
    context.Response.Write(error.StackTrace);
    context.Response.Write("

");
    context.Response.Write("Hello World");
    context.Server.ClearError();
}

A: The error page formatting is done by System.Web.ErrorFormatter and its subclasses, which unfortunately are internal. You can grab the HTML and modify it if you like using HttpException.GetHtmlErrorMessage(). But I'd be inclined to do as other commenters have suggested and use Server.GetLastError and format it myself.
If so - please ensure you HtmlEncode the error message output to mitigate XSS and ensure your production sites don't display any information about the error (as this was the attack vector for the ASP.NET padding oracle decryption attack in 2010).

A: If you are using custom error pages, I believe you can get the last error with HttpContext.Current.Server.GetLastError(); I'm not sure if there are any custom pages out there. But the content of the YSOD should be available from the context of the request.

A: Yes there is.
See here:
http://www.oschina.net/code/explore/mono-2.8.1/mcs/class/System.Web/System.Web/HttpException.cs
It's from the source code of mono (.NET for Linux), in versions < 2.10 (that is to say 2.8).
In version 2.10+, they started using templates, which makes it far more difficult to find and understand it.


text:
Q: Proof that in a cyclic group an element of order d is a product of $\frac{n}{d}$d-cycles I have to Proof that in a cyclic group of order n an element of order d is a product of $\frac{n}{d}$d-cycles. I know that the order of an element is d = $\frac{n}{gcd(n,m)}$. How can I conclude my thereom? Is there any proof for that?

A: If you mean that in the Cayley representation of $G$, an element $g$ of order $d$ is a product of $\frac{n}{d}$ $d$-cycles, then this is clear, because the cycles are orbits of $x \mapsto gx$ and these are the cosets of the $\langle g \rangle$. The number of cosets is the index of $\langle g \rangle$, which is $\frac{n}{d}$.


text:
Q: Get the index of a pattern in a string using regex I want to search a string for a specific pattern.
Do the regular expression classes provide the positions (indexes within the string) of the pattern within the string?
There can be more that 1 occurences of the pattern.
Any practical example?

A: special edition answer from Jean Logeart
public static int[] regExIndex(String pattern, String text, Integer fromIndex){
    Matcher matcher = Pattern.compile(pattern).matcher(text);
    if ( ( fromIndex != null && matcher.find(fromIndex) ) || matcher.find()) {
        return new int[]{matcher.start(), matcher.end()};
    }
    return new int[]{-1, -1};
}

A: Use Matcher:
public static void printMatches(String text, String regex) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(text);
    // Check all occurrences
    while (matcher.find()) {
        System.out.print("Start index: " + matcher.start());
        System.out.print(" End index: " + matcher.end());
        System.out.println(" Found: " + matcher.group());
    }
}

A: import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
    public static void main( String args[] ){

      // String to be scanned to find the pattern.
      String line = "This order was places for QT3000! OK?";
      String pattern = "(.*)(\\d+)(.*)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
   }
}

Result
Found value: This order was places for QT3000! OK?
Found value: This order was places for QT300
Found value: 0


text:
Q: How many possible ways to pick n different coloured shirts from the given set? So I have this question, I have
$8$ red shirts
$4$ blue shirts ... and so on.
The generalized question would be: Suppose I have $k$ shirts, and they are of $m$ different colours and it's given that $a_i$ denotes the number of shirts of $i$th colour. $1 \leq i \leq m$ and $\sum a_i = k$ .
So in how many ways can I pick $n$ different coloured shirts where $n < m$?
I can solve this by picking any $n$ colours, like suppose $n = 3$
and I have red, blue, green, and yellow shirts,
my answer would $(a_{red} * a_{green} * a_{blue}) + (a_{red} * a_{green} *a_{yellow}) + (a_{green} * a_{blue} * a_{yellow} )$
but is there any general method for a random $n$, where I have don't have to calculate individual combinations?

A: suppose you need the first n colors . then u can choose it in $a_1.a_2....a_n$ ways. but then you have to choose any n colors. so the no. of ways will be
$\sum a_{i_1}a_{i_2}...a_{i_n}$ where $i_k \neq i_l$ whenever $k \neq l$ and sum over possible choices

A: This answer is in essence the same as the answer of Saikat, and also matches with your own effort. Unfortunately it is not much more than a notation.
Let $B_{n,m}$ denote the collection of functions $f:\{1,\dots,n\}\rightarrow\{1,\cdots,m\}$ that are orderpreserving. This in the sense that $i_1<i_2\implies f(i_1)<f(i_2)$.
The number of possibilities equals the following expression:$$\sum_{f\in B_{n,m}}\prod_{i=1}^{n}a_{f\left(i\right)}$$
Special case: if $a_1=\cdots=a_m=r$ then the expression equals $r^n\binom{m}{n}$


text:
Q: Why is the p-value for Cohen's $d$ not equal to the p-value of a t-test? I am using the package compute.es in R to calculate effect size from a $t$-test. The $t$-test is marginally significant with $p=0.05657$.
When I run tes(t=2.3563, n.1=4, n.2=4) I get the following output (trimmed):
Mean Differences ES:
d [ 95 %CI] = 1.67 [ -0.34 , 3.67 ]
var(d) = 0.67
p-value(d) = 0.09
U3(d) = 95.22 %
CLES(d) = 88.06 %
Cliff's Delta = 0.76

My question is what is the meaning of p-value(d) = 0.09 in this case? That is, what is the null hypothesis of the Cohen's $d$? And if it is the same as in the $t$-test, then why are the $p$-values different?

A: Cohen's d is a measure of the standardized difference in means.
(mean($X_1$)-mean ($X_2$))/sigma
So the null hypothesis tests whether this standardized difference is equal to zero. This is different from the original null hypothesis which tests whether the non-standardized difference in means is equal to zero.
It might help to see how Cohen's d can be calculated using t. You can find the details in the compute.es package documentation (http://cran.r-project.org/web/packages/compute.es/compute.es.pdf):
t = d$*$sqrt($n_1$*$n_2$/($n_1$ + $n_2$))
rearranging will give you d.
[Addition to the above:]
The d = 1.67 tells you that the difference between the two groups is about one and two-thirds of a standard deviation. The original p=0.05657 was calculated for the non-standardized difference in means. The t-statistics for this difference follows a 'central t-distribution' - that is, it is symmetric around 0. 'Central t-distributions' have one parameter: the degrees of freedom.
The difference with the effect size is that the t-statistic for it is non-centrally distributed (it is not symmetric around 0). 'Non-central t-distributions' have two parameters: the degrees of freedom and a 'non-centrality' parameter. Rather than getting into further details, you can find a straightforward introduction here:
Cumming, G. & Finch, S. (2001) A primer on the understanding, use, and calculation of confidence intervals that are based on central and noncentral distributions. Educational and Psychological Measurement, 61, 633-649.
They give a readable account of why the effect size has a non-central t-distribution on pages 549-551.
Also: you asked for an explanation of the p-value. P-values depend on the distribution of the test statistic which I've addressed in the above (the details of which are in the reference). Hopefully that helps! If you want an explanation of what a p-value is generally, then likely that would require a different post and has probably been asked elsewhere.


text:
Q: How to bind code behind variable value to javascript? I have a javascript header <script type="text/javascript" src="http://example.com?Key=">
This Key is in aspx.cs like string Key="123456"; How can I bind this Key value to the javascript header?

A: You can access code behind variables in aspx files:
<script type="text/javascript" src="http://example.com?Key=<%= Key %>">

A: Try this way:
1-make your script referrable by code-behind by adding an id and runat="server" attributes:
<script id="myScript" runat="server" type="text/javascript">

2-in code-behind, on page_load, add the src attribute dynamically:
this.myScript.Attributes.Add("src","http://example.com?Key=" + Key);

You're done!

A: Code behind:
public Key { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Key = "123456";
    }
}

Markup:
 <script type="text/javascript" src="http://example.com?Key=<%= Key %>">
 </script>


text:
Q: Can We raise Two Merge Request from one local branch when 1 MR is cancelled in GitLab Suppose I have one local branch Named as Palak_branch1

*

*Added some code , commit it and push will generate 1 http link with the help of it will raise Merge Request.

*Closed the Raised Merge Request

*Again Added Some code , commit it and push will it generate again Http link to create new Merge Request ??


text:
Q: xml format elements ending with differents tags In the xml file below, the element "book" and its child "bookid" are different from the elements "toc-entry": "book" and "bookid" begin with <book> and <bookid> respectively, and terminates with </book> and </bookid> respectively, while "toc-entry" elements begin with <toc-entry and end with either /> or > depending if they have a child or not.
My question is: why is there such difference ?
<?xml version="1.0" encoding="UTF-8"?>
<bs-submission participant-id="0"
  run-id="GROUNDTRUTH"
  task="book-toc"
  toc-creation="semi-automatic"
  toc-source="full-content">
<source-files xml="no" pdf="no" />
<description>
This file contains the annotated groundtruth file (ideal ToCs) for the 2013 ICDAR Book Structure Extraction competition.
</description>
<book>
<bookid>6AD91AD5A04A7129</bookid>
<toc-entry title="DEDICATION." page="7"/>
<toc-entry title="HISTORICAL CATECHISM. CHIEFLY RELATING TO THE ENGLISH PROVINCE OF THE SOCIETY." page="9"/>
<toc-entry title="Collections, Illustrating the Biography, &c." page="19">
<toc-entry title="SCOTCH MEMBERS, S. J." page="19"/>
</toc-entry>
<toc-entry title="Collections, Illustrating the Biography, &c." page="44">
<toc-entry title="ENGLISH MEMBERS, S. J." page="44"/>
</toc-entry>
<toc-entry title="Collections, Illustrating the Biography, &c." page="231">
<toc-entry title="IRISH MEMBERS, S. J." page="231"/>
</toc-entry>
<toc-entry title="REMARKS ON THE CASE OF THE JESUITS. 1829." page="271"/>
</book>

A: In XML, it is mandatory that each element is opened and later closed. An element contains everything that's between its opening tag and its closing tag.
To achieve that there are three kinds of element markup tags:

*

*Opening tags don't have a / at all, like <book>

*Closing tags start with </, such as </book>

*Self closing tags start with < and end with />, such as <entry name="stuff"/>
Opening tags and closing tags, as their names indicate, open and close elements.
Self closing tags are a shorthand that do both at once. In XML syntax they are 100% equivalent to opening the tag and closing it immediately after, so writing <entry name="stuff"/> is exactly the same as <entry name="stuff"></entry>

A: Like you hinted towards in your question, the difference is that some elements  have children and some do not (they're empty).
Empty elements can either end with /> or an end tag ('</' Name S? '>').
Empty elements that end with /> are sometimes referred to as self-closing.
<toc-entry title="some title" page="1"/>

is the same thing as:
<toc-entry title="some title" page="1"></toc-entry>

From the spec:

Empty-element tags may be used for any element which has no content, whether or not it is declared using the keyword EMPTY. For interoperability, the empty-element tag should be used, and should only be used, for elements which are declared EMPTY.


text:
Q: appending the dialog box form data as a new column in a table #dialog-form contains two radio buttons. On selecting "Audi" value from drop down dialog a form appears. On selecting "yes" and clicking on save I want to append the yes value as a new td to only the row where we selected value but this script is appending to all the rows.
I also tried using $.closest tr and it didn't worked for me.

$(document).ready(function() {
    $("#dialog-form").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
            "Save": addUser,
            Cancel: function() {
                $("#dialog-form").dialog( "close" );
            }
        }
    });
    $(".d1").on('change', function() {
        if ($(this).val() == 'audi') {
            $("#dialog-form").dialog("open");
        }
    });

    function addUser(){
        var selected = $("#dialog-form input[type='radio']:checked");

        if(selected.length > 0 && selected.val() == "Yes") {
            $('.mainTable tr').append("" + selected.val() + "	");
            $("#dialog-form").dialog("close");
        }
    }
});

        Online Password (Repeated)
        <select name="D1" class="d1">
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="mercedes">Mercedes</option>
                <option value="audi">Audi</option>
            </select>

        <input type="text" value="" class="d2">

        Online Password (Repeated)
        <select name="D1" class="d1">
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="mercedes">Mercedes</option>
                <option value="audi">Audi</option>
            </select>
        <input type="text" value="" class="d2">

        Online Password (Repeated)
        <select name="D1" class="d1">
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="mercedes">Mercedes</option>
                <option value="audi">Audi</option>
            </select>
         <input type="text" value="" class="d2">

     <form>
         Select smart safe Yes or No

         <input type="radio" name="smart" value="Yes" checked> YES

         <input type="radio" name="smart" value="No"> NO

     </form>

A: Here is solution for you from my comment
 $(document).ready(function() {
   var whichSelect = null;
  $("#dialog-form").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
           "Save": addUser,
        Cancel: function() {
          $("#dialog-form").dialog( "close" );
        }
      }
            });
   $(".d1").on('change', function() {
   if ($(this).val() == 'audi') {
            whichSelect = this;
             $("#dialog-form").dialog("open");

                    }
                      });

    function addUser(){
    var selected = $("#dialog-form input[type='radio']:checked");

    if(selected.length > 0 && selected.val()=="Yes"){

        $(whichSelect).parent().parent().append("" + selected.val() + "	");
        $("#dialog-form").dialog("close");
    }
    }
  });

jsfiddle

A: You can assign selected option to a variable and then take closest "tr" and append new "td" into it.
**var that = '';**
  $("#dialog-form").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
           "Save": addUser,
        Cancel: function() {
          $("#dialog-form").dialog( "close" );
        }
      }
            });
   $(".d1").on('change', function() {
   if ($(this).val() == 'audi') {
            **that = $(this);**
             $("#dialog-form").dialog("open");

                    }
                      });

    function addUser(){
    var selected = $("#dialog-form input[type='radio']:checked");

    if(selected.length > 0 && selected.val()=="Yes"){

        **that.closest("tr").append("" + selected.val() + "	");**
        $("#dialog-form").dialog("close");
    }
    }

I have also added jsfiddle at https://jsfiddle.net/vkm193/uzrfy6q7/1/

A: Have a look at this:

  $(document).ready(function() {
  var selectElement;
  $("#dialog-form").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
        Save: function() {
          var selected = $("#dialog-form input[type='radio']:checked");
          if(selected.length > 0 && selected.val()=="Yes"){
              selectElement.closest("tr").append("" + selected.val() + "	");
          }
          $("#dialog-form").dialog( "close" );
        },
        Cancel: function() {
          $("#dialog-form").dialog( "close" );
        }
      }
            });
   $(".d1").on('change', function() {
      selectElement = $(this);
     if ($(this).val() == 'audi') {
        $("#dialog-form").dialog("open");
      }
   });

    function addUser(){

    }
  });

<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

      Online Password (Repeated)

        <select name="D1" class="d1">
          <option value="volvo">Volvo</option>
          <option value="saab">Saab</option>
          <option value="mercedes">Mercedes</option>
          <option value="audi">Audi</option>
        </select>

        <input type="text" value="" class="d2">

      Online Password (Repeated)

        <select name="D1" class="d1">
          <option value="volvo">Volvo</option>
          <option value="saab">Saab</option>
          <option value="mercedes">Mercedes</option>
          <option value="audi">Audi</option>
        </select>

        <input type="text" value="" class="d2">

      Online Password (Repeated)

        <select name="D1" class="d1">
          <option value="volvo">Volvo</option>
          <option value="saab">Saab</option>
          <option value="mercedes">Mercedes</option>
          <option value="audi">Audi</option>
        </select>

        <input type="text" value="" class="d2">

    <form>
    Select smart safe Yes or No

      <input type="radio" name="smart" value="Yes" checked> YES

  <input type="radio" name="smart" value="No"> NO

    </form>


text:
Q: Magento 1 How to redirect on current page I want to redirect to the current page and display a success message but it's redirecting to the home page.
Any solution is available?
Thank you

A: paste this code at the end of your controller
 return $this->resultRedirectFactory->create()->setPath('*/*/controller');

if You are on edit page
return $this->resultRedirectFactory->create()->setPath('*/*/controller', ['id' => "your_id"]);


text:
Q: Preciso de ajuda para entender este codigo Estou iniciando em python assistindo video aulas no youtube,o seguinte exercicio foi passado:
if 10 <= saque <= 600:
    notas_cem = saque // 100
    saque = saque % 100

NÃO ENTENDI ESTAS PARTES,porque a variavel "notas_cem"é atribuida ao saque dividido por 100?e porque o saque é igual ao resto dessa divisão?
O programa não deve se preocupar com a quantidade de notas existentes na
máquina.

Exemplo 1: Para sacar a quantia de 256 reais, o programa fornece duas
notas de 100, uma nota de 50, uma nota de 5 e uma nota de 1;
Exemplo 2: Para sacar a quantia de 399 reais, o programa fornece três
notas de 100, uma nota de 50, quatro notas de 10, uma nota de 5 e
quatro notas de 1.

saque = int(input("Digite o valor do saque: "))

if 10 <= saque <= 600:
    notas_cem = saque // 100
    saque = saque % 100

    notas_cinquenta = saque // 50
    saque = saque % 50

    notas_dez = saque // 10
    saque = saque % 10

    notas_cinco = saque // 5
    saque = saque % 5

    notas_um = saque // 1

    if notas_cem > 0:
        print(notas_cem, "notas de R$ 100")
    if notas_cinquenta > 0:
        print(notas_cinquenta, "notas de R$ 50")
    if notas_dez > 0:
        print(notas_dez, "notas de R$ 10")
    if notas_cinco > 0:
        print(notas_cinco, "notas de R$ 5")
    if notas_um > 0:
        print(notas_um, "notas de R$ 1")

else:
    print("Nao é possivel fazer o saque")

A:
porque a variavel "notas_cem"é atribuida ao saque dividido por 100?e porque o saque é igual ao resto dessa divisão?

Bom, vamos supor que o valor do saque seja 256 reais. Como você faz para saber quantas notas de 100 serão necessárias? Dividindo por 100.
E no caso foi usado o operador de divisão inteira (//), assim o resultado já é arredondado. No caso, 256 dividido por 100 dá 2 (portanto, preciso de 2 notas de 100).
Mas 2 notas de 100 dá um total de 200, só que o valor do saque é 256. Ou seja, ainda preciso saber a quantidade das outras notas. Então pego o valor do saque (no nosso exemplo, 256) e calculo o resto da divisão por 100. Isso resulta em 56, que é o valor que falta se descontarmos as notas de 100.
Depois o algoritmo continua, usando o mesmo raciocínio com as demais notas: repare que ele faz o mesmo com 50, 10, 5 e 1 - se bem que com notas de 1 é desnecessário, pois dividir por 1 não muda nada (a não ser que o valor tivesse também os centavos, mas não parece ser o caso).
No final temos a quantidade de cada uma das notas.
E o algoritmo também funciona se o valor for menor que 100. Por exemplo, se for um saque de 90, a divisão por 100 dá zero (pois não precisa de nenhuma nota de 100), e o resto da divisão por 100 dá 90 (e aí prossegue com as notas de 50, etc).
Aproveitando, aqui tem outras opções diferentes para este mesmo algoritmo.


text:
Q: PATCH not updating application/json (Python) I am trying to update home and away score on League Lobster using their API.  When I send the request, I only get the current data back and nothing is updated.
I have searched through all the similar questions with no resolution. The API I am using has this method in its documentation, so I know it supports PATCH. https://scheduler.leaguelobster.com/api/docs/#match-partial_update
image of API doc showing PATCH
My Code (just want to update home and away score)
import requests

url = "https://scheduler.leaguelobster.com/api/match/113796918"

payload='home_score=1&away_score=3'
headers = {
  'Authorization': 'JWT my_token',
  'Content-Type': 'application/x-www-form-urlencoded', #Also tried /json
  'Cookie': 'django_language=en'
}

response = requests.request("PATCH", url, headers=headers, data=payload)

print(response.text)

Response (200 Code)
{
    "id": 113796918,
    "venue_name": "Dads Small Apartment",
    "home_team_name": "Crayon Eaters",
    "away_team_name": "Bad the Sequel",
    "week": 1,
    "start": "2022-06-20T19:00:00",
    "home_score": null,
    "home_points": 0,
    "away_score": null,
    "away_points": 0,
    "friendly": false,
    "comment": null,
    "locked": null,
    "season": 1110234,
    "playoff_fixture": null,
    "home_team": 11547686,
    "away_team": 11547689,
    "venue": 939776,
    "referee": null,
    "assistant_referees": []
}

From the Docs
HTTP/1.1 200
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Encoding: gzip
Content-Language: en
Content-Type: application/json
Date: Sun, 24 Jul 2022 19:36:17 GMT
Server: openresty/1.15.8.3
Vary: Accept-Encoding, Accept, Accept-Language, Cookie
X-Frame-Options: ALLOW

{"id":113796918,"venue_name":"Dads Small Apartment","home_team_name":"Crayon Eaters","away_team_name":"Bad the Sequel","week":1,"start":"2022-06-20T19:00:00","home_score":0,"home_points":1,"away_score":0,"away_points":1,"friendly":false,"comment":null,"locked":null,"season":1110234,"playoff_fixture":null,"home_team":11547686,"away_team":11547689,"venue":939776,"referee":null,"assistant_referees":[]}

it works with their interaction page but not through Postman or Python

A: I think the problem is that you are sending the data as form data, but it's expecting a json body. To fix it, its very simple.
Try:
payload={ "home_score":1, "away_score": 3 }

headers = {
  'Authorization': 'JWT my_token',
  'Content-Type': 'application/json',
  'Cookie': 'django_language=en'
}

and then
response = requests.request("PATCH", url, headers=headers, json=payload)


text:
Q: Error when trying to run nvidia-settings and nvidia-prime I've installed nvidia-prime and nvidia-346 drivers on my Asus K550J with intel integrated card and nvidia geforce gtx850m..
When I try to use nvidia-settings on the terminal it says:
cirelli@cirelli-pc:~$ sudo nvidia-settings
** Message: PRIME: Requires offloading
** Message: PRIME: is it supported? yes

ERROR: nvidia-settings could not find the registry key file. This file should
       have been installed along with this driver at
       /usr/share/nvidia/nvidia-application-profiles-key-documentation. The
       application profiles will continue to work, but values cannot be
       preopulated or validated, and will not be listed in the help text.
       Please see the README for possible values and descriptions.

How to fix this?


text:
Q: Why isn't Deja Dup making room for more backups? I've got Deja Dup (14.2) backing up to an external USB drive on Lucid.
Up until now, I've had "Keep Backups for" set to "Forever". However, after a couple of months of usage, the drive is now full.
I've tried setting the "Keep Backups for" setting to a shorter time period, even as low as one week, my assumption being that older backups would be cleared when the next backup runs.  However this doesn't seem to happen and I get an error message along the lines of "cannot copy temp file x to backup location y" and the backup stops.
How come space isn't being made for the new backup?

A: It looks like Déjà Dup keeps at least two full backups before it will free up space by overwriting old ones. You mention you have been using it for a 'couple months'. I bet that means you are up against this limitation. Full backups can't be scheduled exactly, but it is going to be about once a month with scheduled backups happening weekly.
You can manually delete old full backups, they are all those 'duplicity-full*' files on the backup drive. Make sure you have at least one full backup to recover from, obviously. You are taking a risk here that your remaining full backups are not corrupted, too.
Best practice before deleting anything is to use another drive to make a tested, known good backup to, then try deleting and/or resizing the backup partition on the destination drive.
Since you know you normally need 2 backups before Déjà Dup will make the third (and overwrite older ones), you need a destination of roughly 3x your current quantity of data being backed up.
If you are seeing different behavior or any bugs, you can ask a question or report a bug on the project's Launchpad page (requires a Launchpad account)

A: I would assume that only backups made after the setting was changed would be affected. At least, I wouldn't want it to automatically delete existing backups. It would probably be nice to have a dialog asking you what to do. You should file a bug, I think. Do so on Launchpad.net.


text:
Q: Issue with RestApi with Basic Authentication I am trying to call a RestApi call with basic authentication. I am able to make the call succesfully, but the issue that i am facing is that if i give wrong username & password in the call, then also I am getting sucess response. I tried by making the login & pasword field as blank also, still positive response is received. I believe its a caching issue. The code that i am trying is as follows
let headers = [
            "cache-control": "no-cache"
        ]
        let login = ""
        let password = ""
        let request = NSMutableURLRequest(url: NSURL(string: urlString)! as URL,
                                          cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
                                          timeoutInterval: 10.0)
        request.httpMethod = "GET"
        request.allHTTPHeaderFields = headers

        let config = URLSessionConfiguration.default
        let loginData = String(format: "%@:%@", login, password).data(using: String.Encoding.utf8)!
        let base64EncodedCredential = loginData.base64EncodedString()
        let authString = "Basic \(base64EncodedCredential)"
        config.httpAdditionalHeaders = ["Authorization" : authString]

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if (error != nil) {
                print(error!)
            } else {
                let httpResponse = response as? HTTPURLResponse
                print(httpResponse!)
                let responseData = String(data: data!, encoding: String.Encoding.utf8)
                print(responseData!)
            }
        })
        dataTask.resume()

The call is going to an IIS server. Can someone help me to solve the issue. Thanks in advance.


text:
Q: Changing CPU indicator from Powersave to Performance did not improve ping results I am trying to ping between two PCs running Ubuntu 20.04 connected via a Layer-2 switch.
My goal is to get "nearly" stable ping latency.
Similar to other people, I figured out that ping latency (round-trip-time) under a low CPU load gets worse than under a higher CPU load.
https://superuser.com/questions/543503/ping-vs-cpu-usage
https://superuser.com/questions/1189531/kvm-how-is-cpu-usage-related-to-ping
For instance, let say I am pinging from PC-A to PC-B. When PC-B did not run any program other than default programs in the operating system, the ping latency received on PC-A was around 0.5 - 0.6 ms. However, when I used the stress tool to increase CPU load (e.g., stress one core to 80% load), I saw that the ping latency received on PC-A was just around 0.2 - 0.3 ms.
I am sure the problem is not caused by the switch because I also tried the direct cable between PC-A and PC-B and still got the same behavior.
I am pretty sure that this behavior is caused by powersave mode, which is the default CPU indicator. But what surprises me is that when I changed CPU indicator from powersave mode to performance mode using cpufrequtils, the ping latency received on PC-A was still around 0.5 - 0.6 ms (no load on PC-B). The same behavior (the ping latency around 0.2 - 0.3 ms) happened when I increased CPU load. In addition to changing the CPU indicator, I guess I still need to do something else.


text:
Q: custom templatefield using ASP.NET Gridview I can figure out a couple of hack ways of doing this,...but no really neat ".NET" way.
I am displaying a table of data using Gridview...one of the columns is dedicated to displaying the status of a boolean variable. The spec I am trying to meet is to have a "On" and "Off" button in the column representing this variable....and clicking ON would change the variable to 1 in my database,...and clicking OFF would change it to 0 etc.
I usually deal with php but I'm guessing this can somehow be done in a clean fashion using the templatefield...but,..i don't know how, which is why i'm asking :)
any tips would be appreciated.
Andrew

A: Something like this should get what you're after.
ASPX Side:
<templateField>
  <itemtemplate>
    <asp:button runat="server" id="myButton" Text='<%# Response.Write(IIF(Eval("MyBool"),"Off", "On")) %>' CommandName='<%# Response.Write(IIF(Eval("MyBool"),"TurnOff", "TurnOn")) %>' CommandArgument='<%# Eval("MyRowIdentifier") %>' />
  </itemTemplate>
</templateField>

code behind:
protected sub Row_itemCommand (ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles MyGrid.RowCommand
   Dim btn As Button =e.Item.FindControl("myButton")
   Select case e.CommandName
      case "TurnOff"
        MyTurnOffFunction(e.CommandArgument)
        btn.Text = "Off"
        btn.CommandName="TurnOn"
      Case "TurnOn"
        MyTurnOnFunction(e.CommandArgument)
        btn.Text = "On"
        btn.CommandName="TurnOff"
    End Select

End Sub

A: You are right about the template field:
  <asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Image ID="img_on" Visible='<%# (bool) Eval("FieldBoolean") %>' runat="server" ImageUrl="GreenLight.jpg" />
                <asp:Image ID="img_off" Visible='<%# !(bool) Eval("FieldBoolean") %>' runat="server" ImageUrl="RedLight.jpg" />
            </ItemTemplate>
            <EditItemTemplate>
             <asp:button ID="btn_switch" runat="server" Text='<%# Response.Write( (bool) Eval("FieldBoolean") ?  "Off" : "On")) %>' CommandName="switch"
              CommandArgument='<%# Eval("FieldBoolean") %>' />

            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandArgument == "switch")
            {
                UpdateValue(!bool.Parse((string) e.CommandArgument));
            }
        }

A: I think you can do something like this:
<Columns>
  <asp:TemplateField>
    <ItemTemplate>
      <asp:ImageButton ID="btnEliminar" runat="server"
         ImageUrl=<%# ((bool) Eval("condition"))? "yes.png":"no.png" %>
         OnClick="btnEliminar_Click"
      />
    </ItemTemplate>
  </asp:TemplateField>
</columns>

On the image OnClick event you should update your database, according some logic you must evaluate.

A: Page
<ItemTemplate>
    <asp:ImageButton id="OnButton" runat="server" OnClick="ToggleButtons" visible="True"/>
    <asp:ImageButton id="OffButton" runat="server"OnClick="ToggleButtons" visible="False" />
</ItemTemplate>

Code Behind
protected void ToggleButtons(object sender, EventArgs e)
{
    if (OnButton.visible)
    {
        OnButton.visible = false;
        OnButton.visible = true;
    } else {
        OnButton.visible = true;
        OnButton.visible = false;
    }
    DoWork(OnButton.visible);
}


text:
Q: Issue with JSON serialization in specific configuration in angular application some time ago I was using Angular 9 in my application and I decided to update it to version 12. After this I couldn't debug my application using Chrome debugger. It turned out that command "ng serve" was using "development" configuration before and now uses "production" configuration by default.
To enable debugging through chrome debugger over my application I added a specific configuration named "development" and I run application now with configuration written explicitly: ng run --configuration="development".
These settings looks like here:

and everything was going okay until now when I noticed that both options: "buildOptimizer" and "optimization" are set on true in "production" configuration and after deploy they cause various (invalid) results during JSON serialization in my custom Serializer (I had to create custom Serializer due to not-flatten data). If I turn these options off, serialization works fine.
Do you have any ideas why these options may affect serialization?

A: I found a root cause of this issue.
It is fault of array.map() and it looks like setup: optimization + buildOptimizer in pair cause improper behavior of map() method (maybe on account of parallelism). I replaced it with brute-force foreach approach:
export class A
{
  children: A[] = [];
  param: string = '';
}

Approach with map (unexpected result after prod-build optimization):
toJson(input: A): string {
  let children =
    '"children": ['
    + input.children.map((child) => `{ ${this.toJson(child)} }` );
    + '],'

  let param = `"param": ${input.param}`;
  return '{' + children + param + '}';
}

Approach with foreach:
toJson(input: A): string {
  let children = '"children": [';
  let childrenArray: string[] = [];
  input.children.forEach((child) => {
    childrenArray.push(`${this.toJson(child)}`);
  });
  children += childrenArray.join(',');
  children += '],';

  let param = `"param": ${input.param}`;
  return '{' + children + param + '}';
}


text:
Q: get request from Openweathermap returns (404) not found I'm trying to get weather info with following code, but every time (except first, but I'm not sure) I getting 404 responce. What I'm doing wrong?
CityName = "Omsk";
            API_KEY = "368e827be4b38db51ff960ca88b5c396";
        weburl = "http://api.openweathermap.org/data/2.5/weather?q=" + CityName + "&mode=xml&APPID=" + API_KEY;
        //weburl = "http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=368e827be4b38db51ff960ca88b5c396";

        doc = new XmlDocument ();

        var xml = new WebClient().DownloadString(new Uri (weburl));
        doc.LoadXml (xml);
        foreach(XmlNode node in doc.GetElementsByTagName("*"))
        {
             Console.Out.WriteLine(node.Name);
        }


text:
Q: python 3 int' object has no attribute 'isdecimal' Very new to python and trying to create a program which takes an inputed number and tells the user if the number is odd or even. I have part of it working, it takes an number and gives the correct output depending on weather its odd or even, but the problem is, if you enter anything but a number, the program dosn't recongise it and crashes the program.
My solution dosn't work and I don't understand the error message.
Enter any number above 0   45
Traceback (most recent call last):
line 5, in <module>
    if not number.isdecimal():
AttributeError: 'int' object has no attribute 'isdecimal'

My implementation:

while True:
    print()
    number = int(input("Enter any number above 0   ")) # Ask user to input a number

    if not number.isdecimal(): # Trying to get code to reject a input that is not a number instead of crashing the program
        print()
        print("Incorrect format, please enter numbers")
        print()
    else:
        if number % 2 == 0: # Tell user inputed number is even if number is even
            print()
            print("That number is even!")
        else:
            print()
            print("That number is odd!")  # Tell user inputed number is odd if number is odd

A: if not number.isdecimal():
    print("incorrect")
else:
    number = int(number)
    if number % 2 == 0: # Tell user inputed number is even if number is even
        print()
        print("That number is even!")
    else:
        print()
        print("That number is odd!")

A: The solution yo thos problem would require the use of the type method. So the solution would be as follows.
 If type(number) != int:

 Do something.

Hope this works.

A: The reason for this is .isdecimal() is a string function and you cannot apply it for an integer.
while True:
    print()
    number = (input("Enter any number above 0   ")) # Ask user to input a number

    if not number.isdecimal(): # Trying to get code to reject a input that is not a number instead of crashing the program
        print()
        print("Incorrect format, please enter numbers")
        print()
    else:
        if int(number) % 2 == 0: # Tell user input number is even if number is even
            print()
            print("That number is even!")
        else:
            print()
            print("That number is odd!")  # Tell user input number is odd if number is odd

This should solve the problem.
I have not type cast the user input to int right away, instead it is now being done while checking if num%2==0.

A: The method isdecimal is a string method, seeing that is just verify if the string is a decimal and after that convert to a int.

string_input = input()

if not string_input.isdecimal():
    raise Exception("That is not a number!!!")
else:

    number = int(string_input)

    if number % 2 == 0: # Tell user inputed number is even if number is even
        print()
        print("That number is even!")
    else:
        print()
        print("That number is odd!")  # Tell user inputed number is odd if number is odd


text:
Q: Numerical error caused math domain error when using Python math.acos() I use math.acos() to calculate the angle between two vectors. The idea is to calculate the dot product of the two normalized vectors, and use arccos of the dot product to return the angle of the two vectors (in the range of 0 to pi).
Occasionally the two vectors, when normalized, have a same direction and their dot product should be 1. However, because of the numerical errors, it is actually 0.999999999998, ... or sometimes 1.0000000000002. The latter kills the math.acos() with an error ValueError: math domain error
I accidentally found this question asking about a similar problem, but was closed. Here I am re-asking, hope to get a better idea on how to avoid such errors.
In my case, I have to check if the two vectors have the same direction before doing dot production and arccos. This helps, but I am still wondering if there are better ways to do this.

A: This is an old numerical problem encountered by all who worked with vectors and floating point arithmetic. A simple fix is to wrap the code that computes the angle in a function with some clamping logic:
import numpy as np
import math

def angle_between(vhat1, vhat2, tol = 5e-6):
    cosang = np.dot(vhat1, vhat2)
    if math.fabs(cosang) > 1.0:
        if math.fabs(cosang) - 1.0 < tol:
            cosang = math.modf(cosang)[1]
        else:
            raise ValueError('Invalid arguments (vectors not normalized?)')
    return math.acos(cosang)

w = np.array([ 1., 0., 0.])
z = np.array([-1., 0., 0.])
v = np.array([ math.sqrt(2.)/2., math.sqrt(2.)/2., 0.])
z1 = np.array([-1.0000001, 0., 0.])
w1 = np.array([9., 3., -5.])

print "{0:>5} deg".format(angle_between(v, w) * 180.0 / math.pi)
print "{0:>5} deg".format(angle_between(w, z) * 180.0 / math.pi)
print "{0:>5} deg".format(angle_between(w, z1) * 180.0 / math.pi)
# this last one will raise ValueError
print "{0:>5} deg".format(angle_between(w1, z1) * 180.0 / math.pi)

Output:
 45.0 deg
180.0 deg
180.0 deg

...
ValueError: Invalid arguments (vectors not normalized?)


text:
Q: Lookahead (?=pattern) without preceding pattern I learned that the lookahead regex is like this x(?=y) and means

Matches x only if x is followed by y.

according to the MDN. However I find this code on w3school:

A form with a password field that must contain 8 or more characters that are of at least one number, and one uppercase and lowercase letter:

<form action="demo_form.asp">
Password: <input type="password" name="pw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters">
<input type="submit">
</form>

Why does (?=.*\d) indicate "at least one number appears in the string"? And the three pair of parentheses don't matter where the match is, because as I look at this, it should be first one or more digit followed by one or more lowercase letters and then one or more uppercase letters and then 8 or more characters, what is wrong?
After a little search, it seems regex is different in various languages, is that what this is about?
edit:
I don't think you guys got my question. I meant the lookahead is like x(?=y), but the (?=.*\d) doesn't precede with anything, so what to match? And the second question, the three parentheses comes with specific order, but the match doesn't have to be same order, since /abc/ matches "abcdd" not "cbdda" ---- why doesn't the order matter?
update:
OK, probably I have a misunderstanding of lookahead, and thanks to whoever changed my title for this problem. So here's my final update if there's no more need after:
My problem is like the title says, a lookahead (?=pattern) can omit the preceding pattern, so what does it mean when nothing before the parentheses? I searched for 'lookahead', almost all explanation comes with a preceding pattern.
And I tried something on regex tester:
/(?=\d)/ will create an infinite match if the string contains a digit, like "a2", but it will show "no match" if the string has no digit, like "a"
Interestingly /(?=\d)./ will match for any digit, now it seems equals to \d
I have no idea what's going on right now, I'll go and learn the lookahead again but any further answers are welcomed, thanks

A: The (?=pattern) is a regex lookahead. It's a zero-width, "true or false" part of the pattern that doesn't actually "eat" any characters, but must match (be true) for the expression to succeed. So,
(?=.*\d)

means "lookahead to see .*\d, which is 'anything' (any number of times, greedy), followed by a number". Since the .* will by default eat up all characters until the end of the string, obviously the \d wouldn't have anything left to eat for itself. The .* backtracks, or gives up, a character at a time until the \d can match. Since * means 'zero or more', .* will give up everything it has matched, if necessary, to let the \d match. Thus, at least one digit somewhere in the string is enough to let the pattern match.


text: Q: Bootstrap stretching images with a fixed width I am using bootstrap with woocommerce (using the JBST theme) and it's stretching images to 100% which is what I would want but unfortunately, it's making those images blurry, especially the thumbnails for woocommerce. The thumbnails have a fixed witdh and I want to keep them at their intended size. I went through the css and removed any reference to width:100% for images yet the thumbnails are still being stretched. Any ideas?


text:
Q: F2PY cannot compile Fortran with print or write I'm having problems compiling Fortran into a Python extension module when the Fortran code includes print or write function calls.
I am on Windows 8.1 with gfortran (through mingw-w64) and the MSVC Compiler for Python 2.7 installed. The Python distribution in use is Anaconda.
test.f
subroutine test (a)

    integer, intent(out) :: a

    print *,"Output from test"

    a = 10

end subroutine test

Running f2py -c -m --fcompiler=gnu95 test test.f90 I see these errors:
test.o : error LNK2019: unresolved external symbol _gfortran_st_write referenced in function test_
test.o : error LNK2019: unresolved external symbol _gfortran_transfer_character_write referenced in function test_
test.o : error LNK2019: unresolved external symbol _gfortran_st_write_done referenced in function test_
.\test.pyd : fatal error LNK1120: 3 unresolved externals

But it works fine when I comment out the print (or write) statement.
A weird thing I've noticed is that it seems to be using Python for ArcGIS.
compile options: '-Ic:\users\[username]\appdata\local\temp\tmpqiq6ay\src.win-amd64-
2.7 -IC:\Python27\ArcGISx6410.3\lib\site-packages\numpy\core\include -IC:\Python
27\ArcGISx6410.3\include -IC:\Python27\ArcGISx6410.3\PC -c'
gfortran.exe:f90: test.f90

Any help would be greatly appreciated.

A: Answering my own question.
Steps to fix:

*

*Ignore or scrub the mingw-w64 install. It wasn't needed as Anaconda
comes with mingw

*Add C_INCLUDE_PATH to the Windows system environment variables and point that to the include folder located within the anaconda path (e.g. C:\userdata\[user]\Miniconda\include)

*Change --compiler=msvc to --compiler=mingw32

*In my case, it was attempting to use numpy from the ArcGIS install. To fix, I had to conda uninstall numpy, take note of all the packages it removed, and then conda install [list of packages that were previously removed]
The Fortran code now compiles perfectly and can be called from Python.


text:
Q: How to find this line length and targeted point coordinates based on other points? First of all I'm beginner in "advanced" math. For this reason I don't know how to compute this problem.
Consider we have a generic rectangle with width W and height H. Also, consider that inside the bounds of that rectangle exists a point B and a point M, in any coordinates inside the rectangle. Knowing this, how can we find the coordinates of a point T which lies in a line MBT and that also stays on the edge of that rectangle? The reason to find the coordinates of T is that I will can draw a line between B and T.
To help understand the problem, see this figure:
example
To try to solve this, I attempted some stuff:

*

*I imagined that the rectangle is living inside a circle;

*the center of the circle coincides with the center of the rectangle, then we have the radius of the circle dividing the diagonal of the rectangle by 2;

*Using the center point C, we can create a triangle MCB, which also have all it's sides known from distance of points formula;

*By using it's sides is possible to find the angle at the vertice B using the cosine's law;

*From the angle X above, we can get it's adjacent X' by subtracting it from 180 degree;

*With the angle X', then, is possible to find the length of the line from B to a point T2 formed by the triangle CBT2 (as illustrated below), again using cosine's law;

*After getting the length of the line BT2 called L, is possible to find the coordinates of the point  T2 using the way described here: Finding a point along a line a certain distance away from another point! (being L, the related distance).

illustration
Those steps are really messy and I was only about to get the coordinate of T2 instead of T. I could go further to find T taking the fact that T is between B and T2 or even creating more triangles and so on.
Then, as I have to use those calculations in programming, are those worth it? If not (and probably not) what a fine way to find the coordinates of the point T in this scenario?

A: First assume that the vertices of the rectangle are $(0,0)$, $(W,0)$, $(W,H)$ and $(0,H)$. If $B=(b_1,b_2)$ and $M=(m_1,m_2)$, then the ray $MB$ (you need the ray in order to ensure that the points are in the order $M,B,T$ and not $T,M,B$) has parametric equation $M+\lambda (B-M)$, where $\lambda \in \mathbb{R}^+$, that is, the points of the ray are the ones of the form $(m_1+\lambda (b_1-m_1),m_2+\lambda (b_2-m_1))$.
Now you can find the intersection of the ray with each of the lines that contain the sides of the rectangle, if the point of intersection $S=(s_1,s_2)$ verifies $0\leq s_1\leq W$ and $0\leq s_2\leq H$, then you can take $T=S$, else, you just compute the other intersections (one of them will give you the point). For example, the point of intersection of the ray $MB$ with the line $y=0$ (if it exists) has $m_2+\lambda (b_2-m_2)=0$, so $\lambda =\frac{m_2}{m_2-b_2}$, it doesn't exists if $m_2=b_2$ (in that case the line $BM$ is parallel to the $x$-axis) or $m_2<b_2$ (in that case the ray "goes upwards").
If the vertices of the rectangle have given coordinates (the sides are not necessarily parallel to the coordinate axes), you can use the same idea intersecting ray $MB$ with each of the lines containing the sides (the equations won't be that nice, but it still works).


text:
Q: Can you help me with a short code that can print itself? #define q(k)main(){return!puts(#k"\nq("#k")");}
q(#define q(k)main(){return!puts(#k"\nq("#k")");})

This code can print itself on the screen,however,I have a difficulty in reading it,especially that two #K,how does it work?I know how #define q(k)  2*k works,but I really have no idea about this code.Please help me to analyse it!thank you!

A: Simplify the call and use your compiler's preprocessor to see what is going on:
#define q(k)main(){puts(#k"hello("#k")");}
q(argument)

Running gcc -E on that gives you:
main(){puts("argument""hello(""argument"")");}

As you can see, what happens is that the argument to the q macro gets transformed into a string (because is is used as #k - this is sometimes called "stringification"). There is no other magic going on here.


text:
Q: Old SQL function using @@ROWCOUNT causing issues We have a SQL function which was written years ago that has been causing sporadic issues (for years I think).
I was finally able to get my hands on a backup of a customers DB so that I could figure out what is going on.
The function in question pulls the latest "session" ID from the DB and returns it unless @@ROWCOUNT is equal to 0, in which case it returns an empty string.
ALTER FUNCTION [dbo].[GetCurrentSessionId]()
RETURNS nvarchar(255)
AS
BEGIN
    declare @v nvarchar(255)

    select top 1 @v = SessionId
    from RestoreSession
    where
        SessionState <> 3 and -- Complete
        SessionState <> 7 -- CompletedWithWarnings
    order by SessionId desc

    if @@ROWCOUNT = 0
        set @v = ''

    return @v
END

Every once in a blue moon this function suddenly will start always returning an empty string even when there is a session in the DB.
When I looked at the above function for the first time while debugging the issue I noticed the @@ROWCOUNT and thought that it was odd.
I removed the @@ROWCOUNT condition and retested, this time the session ID was correctly returned. I then re-added the @@ROWCOUNT condition and retested and it once again returns an empty string.
Further details which may or may not matter. This function is being called from a C# application using the utilities in the System.Data.SqlClient namespace.
The method which calls the above SQL function looks like the following.
public string GetCurrentSessionID()
{
    string res = string.Empty;
    using (var connection = _persistence.CreateSqlConnection())
    {
        var sessionsQuery = "select [dbo].GetCurrentSessionId() as SID";
        using (var sqlCommand = connection.CreateCommand(sessionsQuery))
        {
            using (var sessionReader = sqlCommand.ExecuteReader())
            {
                if (sessionReader.Read())
                {
                    if (!sessionReader.IsDBNull("SID"))
                    {
                        res = sessionReader.GetString("SID");
                    }
                }
            }
        }
    }
    return res;
}

In the above C# method both IsDBNull and GetString are custom extension methods that look like the following:
public static bool IsDBNull(this IDataRecord reader, string name)
{
    return reader.IsDBNull(reader.GetOrdinal(name));
}

public static string GetString(this IDataRecord reader, string name)
{
    return reader.GetString(reader.GetOrdinal(name));
}

I also want to mention that when I execute the SQL function from within SSMS without the removal of the @@ROWCOUNT conditional statement the session ID is correctly returned.
This only seems to occur when calling the function from the C# application.
I believe the fix is removing the @@ROWCOUNT conditional statement as when I did that the C# application was able to correctly pull the session ID.
I'm curious what the issue could be in this case? Why does the @@ROWCOUNT seem to "not work" sporadically when the function is called from the C# application.

A: The problem here is that you are using completely unpatched version of SQL Server 2019 and inlining of user scalar functions, and also expecting the same behaviour from other versions of SQL Server (such as those prior to 2019, where scalar inlining didn't exist) or newer versions of 2019, where the problem you are experiencing has been addressed.
Firstly, the problem. If we look at Inlineable scalar UDF requirements you'll note that it states:

Inlineable scalar UDF requirements
A scalar T-SQL UDF can be inlined if all of the following conditions are true:

*

*...

*The UDF doesn't contain references to intrinsic functions that may alter the > results when inlined (such as @@ROWCOUNT) 4.

*...

...
4 Restriction added in SQL Server 2019 (15.x) CU2

Notice that this restriction was added in CU2; this is because it was noticed early on that inlining functions, such as @@ROWVERSION was causing unexpected/undesired results, and so Microsoft addressed this by making it so that functions using said functions don't inline. As such the function returns back to being a multi-line scalar function.
As you are using 2019 RTM, you don't have this update, and so the function is being inlined and resulting in known undesired behaviour; just one reason of many as to why you should be keeping your SQL Server up to date.
As, however, you are using a range of versions for your deployments, I honestly would suggest that you steer clear of user defined scalar functions for a couple of reasons (unless they are very simple, and even then...). Multi-line scalar function can perform poorly, and inline table value functions (iTVF) are often far more performant. Also, their behaviour doesn't change from version to version (or more specifically from an unpatched to patched version of 2019), so you know that things won't change in a multi client environment, who are using different versions (and some clients are truly useless at updating their servers).
The above query can actually easily be rewritten as a iTVF as the following:
CREATE FUNCTION dbo.GetCurrentSessionID()
RETURNS table
AS RETURN
    SELECT ISNULL((SELECT TOP (1) SessionId
                   FROM dbo.RestoreSession
                   WHERE SessionState <> 3 -- Complete
                     AND SessionState <> 7 -- CompletedWithWarnings
                   ORDER BY SessionID DESC),'') AS SessionID;

If you must use an inline scalar function, then I would suggest that due to having a multi-client environment, with different versions, you ensure that scalar inlining is turned off. This would probably be best at the database level, and thus you should ensure that on creation, for instances on 2019+, you have the following configuration set, by running it on the specific database:
ALTER DATABASE SCOPED CONFIGURATION SET TSQL_SCALAR_UDF_INLINING = OFF;

Though you could do this at the instance level, your clients may not thank you if they are using inlining else where on their instance.
Alternatively, you can set it at the function's level, using WITH INLINE = OFF, on instances running 2019+:
ALTER FUNCTION [dbo].[GetCurrentSessionId]()
RETURNS nvarchar(255)
WITH INLINE = OFF
AS
BEGIN
    declare @v nvarchar(255);

    select top 1 @v = SessionId
    from RestoreSession
    where
        SessionState <> 3 and -- Complete
        SessionState <> 7 -- CompletedWithWarnings
    order by SessionId desc;

    if @@ROWCOUNT = 0
        set @v = '';

    return @v;
END;

Though, if I am honest, you could also just make it so that the query doesn't use @@ROWCOUNT and has a single RETURN value:
CREATE FUNCTION [dbo].[GetCurrentSessionId]()
RETURNS nvarchar(255)
AS
BEGIN
    RETURN (SELECT ISNULL((SELECT TOP (1) SessionId
                   FROM dbo.RestoreSession
                   WHERE SessionState <> 3 -- Complete
                     AND SessionState <> 7 -- CompletedWithWarnings
                   ORDER BY SessionID DESC),''));
END;

But, again, I personally suggest switching to an iTVF for better performance across all environments (not just environments using SQL Server 2019+).


text:
Q: Why doesn't the java.net.URI constructor throw a URISyntaxException for alphabetic strings? Why doesn't the java.net.URI constructor throw an exception when I pass in a string like "abc"? I've isolated it to the test case below.
import static org.junit.Assert.assertEquals;

import java.net.URI;
import java.net.URISyntaxException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class HelloWorldTest {
    @Test(expected=URISyntaxException.class)
    public void testAlphabeticStringWithUriConstructor()
        throws URISyntaxException {
        URI uri = new URI("abc");
    }
}

Which, when compiled and run, produces the following:
$ java -cp .:lib/junit-4.12.jar:lib/hamcrest-core-1.3.jar org.junit.runner.JUnitCore HelloWorldTest
JUnit version 4.12
.E
Time: 0.005
There was 1 failure:
1) testAlphabeticStringWithUriConstructor(HelloWorldTest)
java.lang.AssertionError: Expected exception: java.net.URISyntaxException
    at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.runner.JUnitCore.runMain(JUnitCore.java:77)
    at org.junit.runner.JUnitCore.main(JUnitCore.java:36)

FAILURES!!!
Tests run: 1,  Failures: 1

According to the javadocs for URI, the constructor java.net.URI should throw a URISyntaxException "if the given string violates RFC 2396, as augmented by the above deviations" with some minor deviations included. And the URI constructor does catch other malformed URIs. But for some reason it seems to be okay with this one. Is it possible that "abc" is a valid URI? RFC 2396 - Uniform Resource Identifier (URI): Generic Syntax does not clearly indicate it if so.
Ultimately, this is a problem because I would like to validate that a user-supplied string is a URI before attempting to make an HTTP request.

A: Well, "abc" is a perfectly valid URI string. Let's say I want to refer to a file called abc in the current directory. This is the way to do it !
I guess you really wanted to use URL, which will in this case throw the following exception :
Exception in thread "main" java.net.MalformedURLException: no protocol: abc
    at java.net.URL.<init>(URL.java:586)
    at java.net.URL.<init>(URL.java:483)
    at java.net.URL.<init>(URL.java:432)
    at offlineAnalysis.Main.main(Main.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

URI is different from URL, but I'm not going to explain it there are answers for this already : What is the difference between a URI, a URL and a URN?


text:
Q: Java regular expression for decimal ranges separated by a delimiter I have a input field that I want to validate.This input is used to describe a range. The input can take values of the form x-y or x,y . x and y can be decimal numbers like 101.22-135.33 or 101.22,135.33. I am planning to use regular expression to check for the validity of this range field. Can someone provide with the appropriate regular expression?

A: I'm not sure if you want this:
(\d+\.\d+)[-,](\d+\.\d+)

The code:
String n1 = "125.6,11.2".replaceAll("(\\d+\\.\\d+)[-,](\\d+\\.\\d+)","$1");
String n2 = "125.6,11.2".replaceAll("(\\d+\\.\\d+)[-,](\\d+\\.\\d+)","$2");
System.out.println(n1);
System.out.println(n2);

prints:
125.6
11.2

A: You can try this regex:
^\\s*[=-]?\\d+(\\.\\d+)?\\s*(?:[,-]|and)\\s*[=-]?\\d+(\\.\\d+)?$

PS It won't accept .50-.75 but will accept: 0.50-0.75


text:
Q: How is browser UI painting interleaved with servicing the JavaScript job queue? JavaScript maintains an internal Job Queue of procedures to run with a run-to-completion semantic.
How is UI painting interleaved with servicing this queue? Clearly UI painting is blocked by the running of said procedures.
Does the browser maintain a scheduler and pre-empt the emptying of the queue, or does it wait for a "breath", i.e. an empty queue before attempting a UI update?
Furthermore is the Job Queue typically a straightforward queue or is there a concept of priority (e.g. can browser jobs queue-jump)?


text:
Q: JQuery , syncronized selection option I have to tag in my jsp with two identical select option.
I want that anytime I am chaining one , the second (that is in the bottom ) will change too.
<select class="groups">
    <option class='America' value='America'>America</option>
    <option class='Europe' value='Europe'>Europe</option>
    <option class='Asia' value='Asia'>Asia</option>
<select>

<select class="groups">
    <option class='America' value='America'>America</option>
    <option class='Europe' value='Europe'>Europe</option>
    <option class='Asia' value='Asia'>Asia</option>
<select>

So for instance anytime I am choosing Europe ( or any other ) I want all of my select get updated with the same value.

A: without jquery:
document.getElementsByClassName("groups").forEach(function(element){
  element.onchange = function(event) {
    document.getElementsByClassName("groups").forEach(function(x){
    x.value = event.target.value;
    });
  }
});

with jquery:
$('.groups').onchange = function(e){
  $('.groups').forEach(function(x){
  x.val(e.currentTarget().val)
  });
}


text:
Q: How can I print one layer of a Minecraft schematic on paper? I have exported some of my world into a schematic by MCEdit.
And now I want to print the first layer of my schematic onto paper (since I don't have a 3D printer, I should print it layer by layer)
What should I do?

A: Based on the screenshots, I'd say Schematic2Blueprint may be able to do it depending on the blocks involved. Someone aside from the original creator updated it with a lot of newer blocks, too.
Original: http://klaue.net16.net/programme/ownprogs/java/schematic2blueprint.en.php
Updated: https://www.dropbox.com/s/6cpgmka6mmqgjan/Schematic2Blueprint.jar?dl=0

A: Update the schematic2blueprint project seems to have been taken over by Inostupid Streams...
http://double-helix.industries/applications/schematic2blueprint/#download
It seems to understand purpur blocks and end bricks, but not end rods, or dragon heads.
You can see me preparing and building a statue using it in my video
Ant 024 Survival Statue


text:
Q: How i can get all my objects on my array with $elemMatch? I'm trying to just catch the teams with ligue:"UEFA EURO" , so i used elemMatch to catch it but the query get me only the first object with "UEFA EURO" of my array.
my function :
getRanking: (req, res) => {
    Sport.find(
      {},
      {clubs: { $elemMatch: { ligue: "UEFA EURO" } } },

      (err, data) => {
        if (err) {
          console.log(err);
        } else {
          res.json(data);
          console.log(data)
        }
      }

    );

  },

I'm supposed to have around 20 teams on my new array but my console.log data get just the first one !
also my bdd on mongodb :
clubs: [
    {
      generalMeanWeekly: [],
      tabDB: [],
      _id: 60b64520f0f7f662624ed539,
      nomClub: 'Italie',
      classement: 20,
      dateMatch: 2018-09-21T22:00:00.000Z,
      dateMatchStop: 2018-09-24T22:00:00.000Z,
      classementDB: 20,
      logo: '/images/Italie.png',
      adversaire: '',
      sommeDB: 0,
      pays: 'UEFA EURO',
      ligue: 'UEFA EURO',
      moyenneRank: 100
    }
 {
      generalMeanWeekly: [],
      tabDB: [],
      _id: 60b64520f0f7f662624ed539,
      nomClub: 'France',
      classement: 20,
      dateMatch: 2018-09-21T22:00:00.000Z,
      dateMatchStop: 2018-09-24T22:00:00.000Z,
      classementDB: 20,
      logo: '/images/Italie.png',
      adversaire: '',
      sommeDB: 0,
      pays: 'UEFA EURO',
      ligue: 'UEFA EURO',
      moyenneRank: 100
    }
{
      generalMeanWeekly: [],
      tabDB: [],
      _id: 60b64520f0f7f662624ed539,
      nomClub: 'PSG',
      classement: 20,
      dateMatch: 2018-09-21T22:00:00.000Z,
      dateMatchStop: 2018-09-24T22:00:00.000Z,
      classementDB: 20,
      logo: '/images/Italie.png',
      adversaire: '',
      sommeDB: 0,
      pays: 'FRANCE',
      ligue: 'ligue 1',
      moyenneRank: 100
    }
  ]
}