text:
Q: ssh possible dns spoofing when logging into multiple machines via single host I log in to the rhel5 machines at my school from home via ssh and it automatically sends me to the computer with the least load. So ssh -Y itsme@myShcool.edu will send me to either mySchoolA.edu mySchoolB.edu, or mySchoolC.edu. I can log into the individual computers with no issue but when, but when I use itsme@myShcool.edu , sometimes I get a message about a man-in-the-middle attack and possible DNS spoofing, and I'm directed to ~/.ssh/known_hosts to remove the offending key. Removing the offending key works the first time I log in (I'm prompted to add the host to known_hosts, which I confirm).
Is it possible to log in using itsme@myShcool.edu and not get this message nor have to manually remove the offending keys each time?
One thing I tried that doesn't seem to work is adding the following to ~/.ssh/config
Host hostIPaddress
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null

Any help would be much appreciated.

A: No.  That is a security feature of SSH to know you've connected to the right machine and your connection is not being intercepted.  You certainly don't want to short-circuit that, it would allow a real man-in-the-middle attack and you'd never know it.
If this is how your school's IT administrator meant for this to work -- round-robin a cluster of machines with the same DNS name -- he/she would have copied the SSH private identity key to all the machines in the cluster so this authentication problem doesn't occur.


text:
Q: Why is axios not returning correctly I am trying to replace a fetch with axios. I keep getting undefined in my console log.
async componentDidMount() {
    console.log('app mounted');

    const tokenString = sessionStorage.getItem("token");
    const token = JSON.parse(tokenString);

    let headers = new Headers({
        "Accept": "application/json",
        "Content-Type": "application/json",
        'Authorization': 'Bearer ' + token.token
    });

    const response = await axios({
        method: 'get',
        url: Config.apiUrl + `/api/Orders/GetAllInvoices`,
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
            'Authorization': 'Bearer ' + token.token }
    });
    console.log(`axios: ${response.json}`)
    this.setState({ invoiceList: response.json });

    //const response = await fetch(Config.apiUrl + `/api/Orders/GetAllInvoices`, {
    //    method: "GET",
    //    headers: headers
    //});
    //const json = await response.json();
    //console.log(json);
    //this.setState({ invoiceList: json });
    ...

... the commented out fetch is working. I just now added the .json even though axios should not need it. Neither way works. What am I doing wrong?

A: Did you even console.log(response) just to see whats inside of it?
I guess you dont, because response is an object witch has no json key in it. You should use response.data

redpajama_set_name: RedPajamaStackExchange


text:
Q: CORBA::ORB_init leaking memory I have a project that uses TAO(CORBA)'s Naming Service for information exchange between different modules. However, I found that my implementation of the Naming Service caused memorys leak as detected by my memory leak detection software(Parasoft).
For testing purposes, I have created a small sample project.
int main (int argc, ACE_TCHAR ** const argv)
{
    std::cout << "start of main" << std::endl;

    CORBA::ORB_ptr myOrb = CORBA::ORB_init(argc, argv);
    CORBA::release(myOrb);
    myORB->destroy();

    std::cout << "end of main" << std::endl;
}

When I ran my memory leak detection software, it was discovered that the ORB_init is leaking memory. However, as can be seen form the sample code, all I did was to init an ORB, and release and destroy it immediately after. Are there any other steps to release the ORB allocated resources from within?
One of the leaks:

12 bytes 1 chunk allocated
malloc () (interface)
operator new()
CORBA::string_alloc() String_Alloc.cpp, 53
CORBA::string_dup() String_Alloc.cpp, 38
TAO_Default_Resource_Factory::get parser_names() default_resources.cpp, 590
TAO_Parser_Registry::open() Parser_Registry.cpp, 40
TAO_ORB_Core::init() /home/user/ACE_Wrappers/ace/Arg_Shifter.cpp, 1291
CORBA::ORB_init() ORB.cpp 1359
main() ..src/AlphaTest.cpp, 34

I only have control over src/AlphaTest.cpp, the rest are TAO files.

A: The leak you show is from a global singleton, that is cleaned at process exit and doesn't increase memory during runtime. Very likely the issue is in your application code, you are very likely not using the CORBA IDL to C++ language mapping correctly. Your example code is not correct in that respect, it should be as following
int main (int argc, ACE_TCHAR * const argv[])
{
    std::cout << "start of main" << std::endl;

    CORBA::ORB_var myOrb = CORBA::ORB_init(argc, argv);
    myORB->destroy();

    std::cout << "end of main" << std::endl;
}


text:
Q: Access authorizer from an AWS lambda function with proxy integration - Python [Derived from AWS ApiGateway Lambda Proxy access Authorizer ]
I´m using an Lambda Proxy and a Cognito User Pool Authorizer in my ApiGateway. With node.js Lambda functions, it's possible access to have access to the authorizer (basically, get the user id, email and stuff) in event.requestContext.authorizer.claims.
But in Python, there's no such object. Exploring the event object and the context object shows there's nothing like requestContext or authorizer, just an identity object that contains Cognito Federated Identities information : for me, it's just null.
I haven't seen any mention of the event.requestContext.authorizr.claims in Python AWS-Lambda functions, and it would be a pain to

*

*use federated identities instead

*in API Gateway, set Authorization to AWS_IAM and turn on Invoke with caller credential

*drop the proxy integration for a custom integration or

*write the lambdas with node.js instead of python

Have you any idea if I'm missing something, if it's not implemented by AWS, if there's an easy workaround, or anything else ?
Thanks a lot for your help !
Here's the context object in python aws-lambda function, in a dictionary-like form :
"aws_request_id":"99XXXXf5-6XXe-1XX8-bXXf-5dXXXXXXXX50",
  "function_name":"test_DynamoDB",
  "function_version":"$LATEST",
  "invoked_function_arn":"arn:aws:lambda:eu-west-3:4XXXXXXXXXX0:function:test_DynamoDB",
  "log":"<bound method LambdaContext.log of <__main__.LambdaContext object at 0x7f07bcb21da0>>",
  "log_group_name":"/aws/lambda/test_DynamoDB",
  "log_stream_name":"2018/06/13/[$LATEST]76XXXXXXXXXXXXXXXXXXXXXXXXXXXXf0",
  "memory_limit_in_mb":"128",
  "identity":{
     "cognito_identity_id":null,
     "cognito_identity_pool_id":null
  },
  "client_context": None

Update
From https://stackoverflow.com/a/44039371/9936457 , it seems the same issue was in C# lambda functions and there's a workaround for it, using System.IO.Streams. Would this solution work in Python, with the right syntax ?


text:
Q: Using FastLink for Account Refresh and Edit We are trying to use Fastlink to provide instant refresh and account edit functions. This has not been successful as we keep getting "Problem updating account" FastLink UI.

We do not want to use the ProviderAccount PUT API to trigger refresh as we want to stay away from providing login/MFA UI. FastLink has been very helpful in providing the account add function and we really want to leverage it for all the account related functions.

A: Please use the following sample values in extraParams for refreshing or updating account.
Refresh Account:
String extraParams="flow=refresh&siteAccountId=10139794&callback=https://www.google.co.in";
Update Account:String extraParams = "flow=edit&siteAccountId=10139794&callback=https://www.google.co.in";
Please pass the value of providerAccountId for siteAccountId.


text:
Q: New deployment of Azure VMSS with system assigned Managed identity fails I'm encountering an issue wherein new deployment for azure vmss (which has managed identity enabled) fails for the first time due to the following error -
Code: ResourceNotFound.
Message: The Resource 'Microsoft.Compute/virtualMachineScaleSets/' under resource group '' was not found
Following are the relevant snippets of my arm template -
VMSS section-
{
  "type": "Microsoft.Compute/virtualMachineScaleSets",
  "sku": {
    "name": "[parameters('vmNodeType0Size')]",
    "capacity": "[parameters('defaultVMScaleSetSize')]",
    "tier": "Standard"
  },
  "name": "[variables('vmNodeType0Name')]",
  "apiVersion": "[variables('vmssApiVersion')]",
  "location": "[parameters('computeLocation')]",
  "tags": {
    "resourceType": "Service Fabric",
    "clusterName": "[variables('cloudClusterName')]"
  },
  "identity": {
    "type": "systemAssigned"
  },
  "properties": {
    ...
  }
}

Access policy section -
{
  "type": "Microsoft.KeyVault/vaults/accessPolicies",
  "name": "[concat(variables('KeyVaultName'), '/add')]",
  "apiVersion": "2018-02-14",
  "properties": {
    "accessPolicies": [
      {
        "tenantId": "[reference(concat('Microsoft.Compute/virtualMachineScaleSets/',  variables('vmNodeType0Name'), '/providers/Microsoft.ManagedIdentity/Identities/default'), '2015-08-31-PREVIEW').tenantId]",
        "objectId": "[reference(concat('Microsoft.Compute/virtualMachineScaleSets/',  variables('vmNodeType0Name'), '/providers/Microsoft.ManagedIdentity/Identities/default'), '2015-08-31-PREVIEW').principalId]",
        "permissions": {
          "keys": [
            "get"
          ],
          "secrets": [
            "get",
            "set"
          ],
          "certificates": [
            "get"
          ]
        }
      }
    ]
  },
  "dependsOn": [
    "[concat('Microsoft.KeyVault/vaults/',  variables('KeyVaultName'))]"
  ]
}

It seems that ARM tries to deploy managed identity for VMSS even before VMSS itself is created and hence it fails. I have found no way to add a dependency on VMSS creation for managed identity creation. Subsequent deployments succeed as VMSS is already created by that point.

A: try adding the following to the KV resource:
"dependsOn": [ "[variables('vmNodeType0Name')]" ]

if that doesnt work, wrap adding the access policies to the KV into a linked template deployment and make that deployment depend on the vmss provision. that would always work.


text:
Q: Is there any recovery software available for ext4? Well, I have accidentally deleted my Ubuntu drive. I just want to recover all the contents of /home.
Is there a way to do it? I referred to foremost, where I need to specify the extensions of files. And in my case, I don't know actual extensions. So, is there any utility which can let me recover my /home folder alone?
I have not even formatted that drive or touched it at all. So no write has been done on that drive.
If you have suggestions on how to recover, please tell me.

A: The first thing to do, is to STOP USING THE DISK! Everything that gets written to it runs the risk of overwriting your data.  Mount it read only and copy the things you find to a different device.
After that, the tools mentioned by the other contributors are good places to start.  Add Magic Rescue, and any raw sector editor to the mix.  Magic Rescue is good at finding pictures, videos, zip archives and MS Office files.  And the sector editor can be used to find most documents provided you remember some words out of them to use for searching.

A: Try TestDisk/PhotoRec:

*

*CTRL ALT t to open a terminal

*sudo apt-get install testdisk and type your normal user password

*sudo photorec
Good luck!
EDIT: take a look at https://help.ubuntu.com/community/DataRecovery too.

A: Take a look at this:
Best tool to recover removed files
Formatted and lost 6 years worth of photo memories.. any way to get this back?
How to recover Ubuntu partition after computer failure?
Where the answers of some other people under those questions may also be helpful for you.
Good luck!

A: I'd suggest computer forensics tools, like The Sleuth Kit and its Autopsy browser.

A: I suggest this lightweight tool:
http://extundelete.sourceforge.net


text:
Q: Options in command-promt This might be very basic, but I'm trying to use init, and should be able to choose one of the options bellow, but for some reason it seems like it goes back to the foot folder before I can answer. What can I do?
c:\wamp64\www\yii-application>init
Yii Application Initialization Tool v1.0

Which environment do you want the application to be initialized in?

  [0] Development
  [1] Production

  Your choice [0-1, or "q" to quit]
  Quit initialization.

c:\wamp64\www\yii-application>`

I have the same problem when I try to run migrate.


text:
Q: Filter viewController In my app I have a search bar where people can add free text and get the results the meet the criteria
func search(searchClinics: [Clinica], searchArr: [String]) -> [Clinica] {
    var searchArr = searchArr
    // base case - no more searches - return clinics found
    if searchArr.count == 0 {
        return searchClinics
    }
    // itterative case - search clinic with next search term and pass results to next search
    let foundClinics = searchClinics.filter { item in
        (item.name.lowercased() as AnyObject).contains(searchArr[0]) ||
        item.specialty1.lowercased().contains(searchArr[0]) ||
        item.specialty2.lowercased().contains(searchArr[0])
    }
    // remove completed search and call next search
    searchArr.remove(at: 0)
    return search(searchClinics: foundClinics, searchArr: searchArr)
}

I also have a flag to identify if the searchBar is being used
var searching = false // Checks if searchBar was used

In case searchBar was used, it returns the filtered array data otherwise returns the full list. For example
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if searching {
        let totalClinics = clinicsSearch.count
        if totalClinics == 0 {
            return 1
        } else {
            return totalClinics
        }
    } else {
        let totalClinics = clinics.count
        if totalClinics == 0 {
            return 1
        } else {
            return totalClinics
        }
    }
}

I'm now willing to add another viewController where the user would be able to define specific filters (like State, City, Specialty among others). Once the user clicks apply, it would go back to the previous viewController with filtering data.
I'm in doubt with the best approach to apply this filter. At first I though about doing something like:

*

*User clicks a button in the navigationBar and opens "Search" viewController;

*User inputs Data;

*User clicks "Apply";

*Call previous viewController;

*I would add another status flag with status "True" that will be used in my tableView ViewController. If true, considers the list of clinics with filters applied. If not, show the full list of clinics;

I've a lot of searching in stackoverflow but I found a lot of filtering/searchbar stuff but none related to a separate search/filter viewController.
Would you recommend this approach or is there a better way to do it?
One of my concerns here if with step 4... if I call a segue, wouldn't I be stacking views and consuming more memory?
Thanks

A: In my app user click filter button present Controller open
let vc = storyboard?.instantiateViewController(withIdentifier: "searchFilter") as! SearchFilter
vc.modalPresentationStyle = .overCurrentContext
vc.SearchCompletion = {(model,flag) in
    if(flag){
        self.serachArr.removeAllObjects()
        for i in 0..<model.count{
            self.serachArr.add(ListModel(data: model[i] as! NSDictionary))
        }
        self.ListTable.reloadData()

    }
}
self.present(vc, animated: true, completion: nil)

User click apply button and  pass data previous Viewcontroller
self.SearchCompletion(dataArr,true)


text:
Q: Why does my Android Tablet not Report Focal length or Sensor width? So this is something that's been blocking us for a while now.
For context, we're trying to use Google's MediaPipe library on an Android tablet.
However, it crashes complaining about a Null array
    Process: com.example.jarvis, PID: 9853
    java.lang.NullPointerException: Attempt to read from null array
        at com.google.mediapipe.components.CameraXPreviewHelper.calculateFocalLengthInPixels(CameraXPreviewHelper.java:485)
        at com.google.mediapipe.components.CameraXPreviewHelper.updateCameraCharacteristics(CameraXPreviewHelper.java:472)
        at

To investigate this further, we started looking into the Camera Characteristics returned, including making a separate APK just to see what's going on.  Relevant part is here https://github.com/onthecrow/know-your-camera/blob/main/app/src/main/java/com/onthecrow/knowyourcamera/MainActivity.kt#L86
                if (!characteristicsStateValue.characteristicsExists) {
                    Text(text = "Can't obtain the camera characteristics!")
                }
                if (!characteristicsStateValue.focalLengthCharacteristicsExists) {
                    Text(text = "Obtained characteristics doesn't contain the focal length")
                }
                if (!characteristicsStateValue.sensorWidthCharacteristicsExists) {
                    Text(text = "Obtained characteristics doesn't contain the sensor width")
                }

It seems like LENS_INFO_AVAILABLE_FOCAL_LENGTHS and SENSOR_INFO_PHYSICAL_SIZE are null when they shouldn't be.  We're running Android 11, and these seem like they're supposed to always be present https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics#LENS_INFO_AVAILABLE_FOCAL_LENGTHS
Any ideas what's going on?
We have also considered trying to find the right Camera Characteristics some other way and then hard coding them into the Dict before they're read - not ideal but possible if we could figure it out.


text:
Q: Permissions on .htaccess file I tried to edit .htaccess file via sftp on filezila (ppk file and etc) and it says i dont have permissions to edit\upload.
I have wordpress bitnami on aws ec2.
Can you help me please?
Thanks.

A: You have to make sure that the ftp user does have permissions to edit the files. If not then you have to change the ownership of the files/folders to the ftp user. You may also have to add your FTP user to the group of your web server user.


text:
Q: execute logic beforedelete event trigger Before deleting the record (Ex: Account obj record), I want to update the field on the account record and send it to content management, hold it for a few seconds, and then delete it.
For this scenario, I used beforedelete event and updated the fields in the record, and called the content management with updated record data. The record is updated with new values (i verified after restoring it from recycle bin), But it is not calling the content management before deleting the record. Is there any option that we can wait for a few seconds until the record is updated on content management and delete the record? Please share your suggestions. Thank you.

A: If you let beforeDelete pass through without throwing error, Salesforce will delete the record immediately and put into recycle bin.
Since triggers cannot make callouts, you will have to notify Content management via async process (Queueable or Future) and async process is not guaranteed to execute in certain time. If you have lots of async jobs scheduled, Salesforce may delay execution of this particular async request to later time.
Instead of trying to time it, reliable approach is to pass the record id to Content Management system and indicate that it is deleted. Content mgmt can query the record with /queryAll api which returns deleted record with full details and take care of its process.
If you don't have control over having Content system make queryAll, you will have to do your own delete mark (with custom field), make a call and after a while delete the record.


text:
Q: Add external url to WooCommerce My Account navigation I need to add custom item to WooCommerce My Account navigation. I can add the item with no problem. Since it is a link to user's profile I use the following code:
<?php
  global $switched;
  switch_to_blog(2);
?>
<a href="<?php echo bp_loggedin_user_domain(); ?>">Profile
<?php restore_current_blog(); //switched back to main site ?>

First I switch to BuddyPress which handles users (multisite newtork). Then I use bp_loggedin_user_domain to get user profile url.
But the actual output of the link is incorrect, I get: www.domain.com/my-account/"www.subdomain.domain.com/members/profile/"
I know that My Account page treats all links as child pages with WooCommerce endpoints, but is there a way to get the external url there? Without WooCommerce's default domain.com/my-account/ prefix

A: Making a small assumption here. It's more likely that the actual output looks something like this:

  Profile

rather than:

  Profile

And your browser is actually filling in for the missing scheme and path. Browsers will assume an href is relative if you don't use an absolute URI (go figure!) so if you're using external links you need to be sure there's a // at the start(or an https://, or http:// etc.). Else the browser will insert the appropriate relative path for you, in the case of a missing / it will insert the current full path for the link, effectively providing:

  Profile

Use view-source, not dev tools, in your browser to see the raw output, rather than the interpreted & formatted output to be sure though.

A: This is how I solved my problem:
I have a multisite network on domain.com, there is also BuddyPress which handles user profiles on buddypress.domain.com. When user registers it often happens on domain.com because we have a webshop there. So I wanted to add BuddyPress profile link to WooCommerce My Account navigation.
When I added it with:
<a href="<?php echo bp_loggedin_user_domain(); ?>">Profile

I would get the following link in frontned www.domain.com/"buddypress.domain.com/members/user" instead of buddypress.domain.com/members/user
I think this is because of the way WooCommerce handles My Account page. Basically it treats each link on that page as an endpoint and inserts the domain.com part. It treats every link on it as a child page.
Since I'm on a tight schedule with the project I used this instead:
<?php echo bp_core_get_userlink( bp_loggedin_user_id() ); ?>

which showed Username and profile link correctly. Since this is a multisite I used it with switch_to_blog();
So If anyone needs to play with WooCommerce and BuddyPress on multisite network, I hope this will help.


text:
Q: Program compiles but crashes when using floating point So I am working with this simple block of code:
#include <iostream>
#include <cmath>

using namespace std;

int sum_of_squares (double a, double b)
{
    double sum;
    double sum1;
    sum1 = pow(a,2)+pow(b,2);
    sum = sqrt(sum1);
    return sum;
}
int main ()
{
    //User Inputs
    double x1;
    double x2;
    double y1;
    double y2;
    double r1;
    double r2;
    double diffx;
    double diffy;
    cout << "Enter the information for the first circle";
    cout << "x-coordinate:";
    cin >> x1;
    cout << "y-coordinate:";
    cin >> y1;
    cout << "radius:";
    cin >> r1;
    cout << "Enter the information for the second circle";
    cout << "x-coordinate:";
    cin >> x2;
    cout << "y-coordinate:";
    cin >> y2;
    cout << "radius:";
    cin >> r2;

    //Math
    double total_radius;
    double circle_sep;
    double difference;
    diffx = abs(x1-x2);
    diffy = abs(y1-y2);
    total_radius = r1+r2;
    circle_sep = sum_of_squares(diffx,diffy);
    difference = circle_sep - total_radius;

    //Outputs
    int z;
    if(total_radius>circle_sep)
        cout<< "THE CIRCLES OVERLAP.";
    else
        cout << difference;
        cout << "THE MINIMUM DISTANCE BETWEEN THE CIRCLES IS " << difference << ".";
    cout << "Enter 0 to exit";
    cin>> z;
    return 0;
}

The first output if statement works perfectly, even when giving it coordinates that would require floating point math. The else statement after that is not working as well. I can get the program to compile and run when I remove the "cout << difference", but when I deliberately enter circles that are separated the program crashes. I can't get the program to compile if I leave that line of code in there. To me it seems like the computer should be able to do a simple line of subtraction, but it crashes. I have another program with a similar issue that I hope the solution to this will apply to.
Thanks!

A: The program compiles fine for me on g++ 4.6.3
However, if you only want to output the THE MINIMUM DISTANCE BETWEEN THE CIRCLES IS message when total_radius <= circle_sep, you should put curly braces around those indented lines.


text:
Q: Is my send()/recv() going out of order after first pass-Python Socket programming I'm getting started with Socket programming in Python.
As part of my requirement I want to send some requests (call send_post_requests) and then receive all of them.
Can anyone tell me what I'm doing wrong here.
Right now I'm able to receive only first response.
Here's my code snippet-
def send_post_request(s,i="1",question='{"a": {"b":"dummy}}'):

        s.send('POST /request HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: identity\r\nContent-Length: '+str(len(question))+'\r\nrequest-id: '+i+'\r\nConnection: Keep-Alive\r\nContent-Type: application/json\r\n\r\n')

        s.send(question)

def pipe(noOfSockets=1,noOfRequest = 5,question='{"a": {"b":"dummy}}',sizeFactor = 1):
        sockets =[]
        for i in range(0,noOfSockets ):
            sockets.append(socket( AF_INET, SOCK_STREAM))

        for s in sockets:
            try:
                s.connect( (<IP>, <port>))
                for i in range(0,noOfRequest):
                    send_post_request(s,str(i),question)

            except(error,timeout), e:
                print(e)
            except Exception, e:
                print("unknown except(%s) :(" % e)

        passes =0
        allResp =[]
        for s in sockets:
            sleep(2)
            size = noOfRequest * 1000 *sizeFactor
            responses = s.recv(size)

            allResp.append(responses)

        return allResp

A: Webservers normally close the connection after one request. Use a library for http-requests like urllib2 or requests.


text:
Q: TikZ: "Clipping problem" I have the following code
\documentclass{report}
\usepackage{tikz}
\usetikzlibrary{intersections}

\begin{document}
bla bla bla

\begin{tikzpicture}
\def\r{1}; % radius
\def\a{80}; % 1st angle
\def\b{170} % 2nd angle
\pgfmathsetmacro\px{\r/cos(\a)}
\pgfmathsetmacro\qy{\r/cos(\b-90)}

\coordinate (p) at (\px,0);
\coordinate (p1) at (2*\a:\px);
\coordinate (p2) at (-2*\a:\px);
\coordinate (q1) at (0,\qy);
\coordinate (q2) at (2*\b-90:\qy);
\path[name path=lineup] (p)-- (p1);
\path[name path=linedown] (p)-- (p2);
\path[name path=lineleft] (q1)-- (q2);

\draw[name intersections={of=lineup and lineleft,by={r1}}];
\draw[name intersections={of=linedown and lineleft,by={r2}}];

\draw (0,0) circle [radius=\r];
\draw (0,0) -- (\a:\r);
\draw (0,0) -- (-\a:\r);
\draw (0,0) -- (\b:\r);
\draw (p) -- (r1) -- (r2) -- cycle;
\end{tikzpicture}

bla bla bla
\end{document}

which gives me the following picture.
As you can see there is a lot of empty space above and below the triangle.
This comes from the fact that the left corners (r1 and r2 in the code) of the triangle are intersection of virtual line segments (lineup, linedown and lineleft in the code).
Question: How can I ask Tikz to ignore these virtual line segments when computing the size of the window?
I tried to do something with \clip, but I was not successful.
Note that my picture depends on three parameters \r, \a and \b, which I define at the beginning of the tikzpicture. I don't want to have a clip with some arbitrary value which would correspond only to a specific choice of parameters.

A: The coordinates p, p1, p2, q1 and q2 as well as the paths that use them are bigger than the stuff you actually draw.
They are still considered by PGF to be part of the picture and thus the bounding box of the picture gets enlarged accordingly.
In your case, the easiest solution would be to put the whole section including the name intersections-auxiliary paths in a scope with the options overlay.
This makes it so that the whole scope will not be considered to be part of the bounding box.
\begin{scope}[overlay]
  \coordinate (p) at (\px,0);
  \coordinate (p1) at (2*\a:\px);
  \coordinate (p2) at (-2*\a:\px);
  \coordinate (q1) at (0,\qy);
  \coordinate (q2) at (2*\b-90:\qy);
  \path[name path=lineup] (p)-- (p1);
  \path[name path=linedown] (p)-- (p2);
  \path[name path=lineleft] (q1)-- (q2);

  \path[name intersections={of=lineup and lineleft,by={r1}}];
  \path[name intersections={of=linedown and lineleft,by={r2}}];
\end{scope}

Even though the name intersections path do not declare coordinates outside of the desired bounding box and thus wouldn't need to be inside the scope, because the name path key works locally it is easier to include them. (There's also global name path.)

You could also use \pgfresetboundingbox (which does what is says) as you said but then you should make sure there's nothing before it that does protrude outside the final bounding box.


text:
Q: how to add login for different roles in rails I have three models A,B and C and their associations are A has_many B,C and B,C belong_to A. I created login and authentication for 'A' by referring Michael hartl book. when A logs in, he organises B and C (create,update and destroy B and C).
Now I want a login and authentication for B. when B logins he redirect to another page.
To achieve this I tried to add roles to A and B using cancan gem but I got stuck how to use login page of A for B to log in and redirect. How to achieve this?

A: If you are using Devise for authentication, you can use the after_sign_in_path_for hook, as described in the documentation. In this method you can define the logic the application should follow in order to redirect the logged-in user to one page or another one.
In addition, you should take into account that some users cannot access certain pages, and that is where CanCanCan gem makes sense. No matter the redirect configuration you set up, you should prevent unauthorized users from visiting certain pages.


text:
Q: How can I filter the custom ListView with edit Text? I have tried for hours looking through examples and other people's code but I still don't quite understand it.
I have my own method, which half works.
public class List_of_recipes extends ActionBarActivity {
    //original
    public List<List_view_class> list_view_class;
    ArrayAdapter<List_view_class> adapter;

    // not the original
    public List<List_view_class> another_list_class;
    public ListView list;
    public EditText edit_text;
    //ActionBar actionBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_of_recipes);

        //  actionBar = getActionBar();
        //actionBar.setDisplayHomeAsUpEnabled(true);
        //actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#A02727")));

        list = (ListView) findViewById(R.id.listView1);
        edit_text = (EditText) findViewById(R.id.editText1);
        list_view_class = new ArrayList<List_view_class>();
        another_list_class = new ArrayList<List_view_class>();
        adapter = new MyListAdapter(list_view_class);

        list_view_class.add(new List_view_class(R.drawable.chicken, "Chicken salad", "15 min", "Easy", "4 serves"));
        list_view_class.add(new List_view_class(R.drawable.mexican, "Mexican egg soup", "20 min", "Easy", "2 serves"));
        list_view_class.add(new List_view_class(R.drawable.oyster, "Oysters with pancetta", "10 min", "Super Easy", "2 serves"));
        //list_view_class.add(new List_view_class(R.drawable.wild_mushroom,"Wild mushroom crostini","5 min", "Easy","6 serves"));

        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View viewclicked, int position, long id) {
                // TODO Auto-generated method stub
                if (position == 0) {
                    Intent i = new Intent(List_of_recipes.this, Chicken_salad.class);
                    startActivity(i);
                    finish();
                }

                if (position == 1) {
                    Intent i = new Intent(List_of_recipes.this, Mexican_egg.class);
                    startActivity(i);
                    finish();
                }

                if (position == 2) {
                    Intent i = new Intent(List_of_recipes.this, Oyster.class);
                    startActivity(i);
                    finish();
                }
            }
        });

        edit_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub
                String searchString = edit_text.getText().toString();
                another_list_class.clear();
                int textLength = edit_text.length();

                for (int i = 0; i < list_view_class.size(); i++) {
                    String name = list_view_class.get(i).gettitle().toString();

                    if (textLength <= name.length()) {
                        if (searchString.equalsIgnoreCase(name.substring(0, textLength))) {
                            another_list_class.add(list_view_class.get(i));
                        }

                    }
                }

                adapter.notifyDataSetChanged();
                adapter = new MyListAdapter(another_list_class);
                list.setAdapter(adapter);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
            }
        });
    }

    public class MyListAdapter extends ArrayAdapter<List_view_class> {
        public MyListAdapter(List<List_view_class> object_class) {
            super(List_of_recipes.this, R.layout.activity_list_class_view, object_class);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View rowView = convertView;

            if (rowView == null) {
                LayoutInflater inflater = (LayoutInflater) List_of_recipes.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                rowView = inflater.inflate(R.layout.activity_list_class_view, null, true);
            }

            List_view_class listclass = list_view_class.get(position);
            ImageView image = (ImageView) rowView.findViewById(R.id.imageView1);
            image.setImageResource(listclass.getrecipe_icon());
            TextView date = (TextView) rowView.findViewById(R.id.textView1);
            date.setText(listclass.gettitle());
            TextView cook = (TextView) rowView.findViewById(R.id.cooktime);
            cook.setText(listclass.getcook_time());
            TextView diff = (TextView) rowView.findViewById(R.id.difficultylvl);
            diff.setText(listclass.getdifficulty());
            TextView serve = (TextView) rowView.findViewById(R.id.serving);
            serve.setText(listclass.getmakes());

            return rowView;
        }
    }
}

It gives no errors, but all I am getting is the first list view item no matter what I type.
I am not sure what else to add or what I am doing wrong here. Any help will be appreciated, thank you !

A: Try to move code to afterTextChanged
int textLength=edit_text.getText()!=null?edit_text.getText().toString().length():0;
     for(int i =0; i< list_view_class.size(); i++)
     {
         String name = list_view_class.get(i).gettitle().toString();

         if(textLength <= name.length()){

             if(searchString.equalsIgnoreCase(name.substring(0,textLength)))
             {
                 another_list_class.add(list_view_class.get(i));
             }

         }
     }

A: there is no need to create another adapter again and again on edit text change.you can refresh list view by just calling notifyDataSetChanged  on adapter.

String searchString = s.toString();
     another_list_class.clear();
     for(int i =0; i< list_view_class.size(); i++){
             String name = list_view_class.get(i).gettitle().toString();
             if(name.contains(searchString))
             {
                   another_list_class.add(list_view_class.get(i));
             }
     }
     adapter.notifyDataSetChanged();

    equalsIgnoreCase returns true if and only if two strings are exactly equal(Ignoring case sensitive);

You can also use startWith in place of contains
One more thing set your adpater with another_list_class arraylist initially.
because in this example we are changing search result in another_list_class .

It is better to put code in afterTextChanged.


text:
Q: How can I cast an object as another in java? "javafx.scene.Group cannot be cast to javafx.scene.shape.Rectangle" How can I change the attributes of objects that are stored in a grid? I tried this, but it gives me the above error:
    Group group = new Group();
    double dimension_x=100;
    double dimension_y=100;

    GridPane grid = new GridPane();
    grid.setHgap(1);
    grid.setVgap(1);
    grid.setPadding(new Insets(36));
    grid.setGridLinesVisible(true);

    Rectangle temp = new Rectangle(dimension_x,dimension_y);
    Rectangle temp2 = new Rectangle(dimension_x,dimension_y);
    Rectangle temp3 = new Rectangle(dimension_x,dimension_y);
    Rectangle temp4 = new Rectangle(dimension_x,dimension_y);

    grid.add(temp, 0,0);
    grid.add(temp2, 1,1);
    grid.add(temp3, 2,2);
    grid.add(temp4, 3,3);

    for (final Node node : grid.getChildren())
    {

        Rectangle tempvar = (Rectangle) node;  //Errors out at javafx.scene.Group cannot be cast to javafx.scene.shape.Rectangle
        node.getStyleClass().add("box");
        //tempvar.setFill(Color.TRANSPARENT);
        //tempvar.setStroke(Color.WHITE);

    }

is there any way to loop through my grid and change the objects?

A: Print the result of grid.getChildren().
I'm suspicious that grid contains other objects other those 4 Rectangle


text:
Q: NotImplementedError: must implement `get_logits` or must define a logits output in `fprop` WhenI try to run from github.com/behzadanksu/rl-attack
python train.py --env Breakout --noisy --save-dir ./data/Breakout/ --attack fgsm --num-steps 20 --attack-prob 1.0
from cleverhans library, I get the following error. How can I avoid it?

NotImplementedError: must implement get_logits or
  must define a logits output in fprop

A: Without the original code snippet that caused the error, my guess is that you are using a model defined in a framework that is not originally CleverHans and you tried to wrap it into a CleverHans model (it would help clarify your question) if you can post a snippet of code defining your model). If that is the case, then the error you are seeing means that the model class you wrapped your original model in does not have a method get_logits or fprop that is properly implemented. You either need to have a get_logits method that takes in an input tensor and returns the output tensor of the model, or a fprop method that takes in an input tensor and populates a dictionary with keys set to the layer names and values to the activation tensor of each layer. One of the keys of this dictionary must be logits or probs. You can find more guidance in the model.py file of the library: https://github.com/tensorflow/cleverhans/blob/master/cleverhans/model.py


text:
Q: Number of functions to receive 2 values I have a set $A$ with $5$ items: $1,2,3,4,5$
I want to know how many functions are there that make $|f[A]|=2$ if $f: A->A$
So what I thought is that it's the same like to put $5$ balls in $2$ boxes out of $5$ boxes.
My direction to the solution would be: choose $2$ boxes out of the $5$ boxes and put the $5$ balls in the two boxes so you have at least one ball in each box.
So there are $10$ ways to choose the two boxes out of $5$, and $D(2,5-2)$ ways to put the $5$ balls in the $2$ boxes.
So $10\cdot4 = 40$
However, this is not the solution. What am I missing?

A: Having chosen the two elements in the image of $f$, you have to assign one of the two as the function value for each element of $A$.  There are $2$ ways to assign each one, so there are $2^5$ ways to make the assignment.  We require that at least one element go to each value, and $2$ of the possible assignments take all five elements to the same value, so there are $30$ ways to assign the values of $f$.  The total number of functions is then $10 \cdot 30=300$


text:
Q: Foreground service not working in android oreo In my app, it loads a url(API) after every 15 seconds in the background. I dont need any kind of UI in my app so I just load the url in my service class. To work properly on oreo+ devices I used startForgroundService(). But it is not working in Oreo after the app is killed. My testing device is OPPO Oreo 8.1.0. It is perfectly working on Samsung 7.0.
Here is my Service code :
public class MyService extends Service {
    Handler handler = new Handler();
    Runnable runnable;
    int delay = 15 * 1000;
    String data;

    @Override
    public IBinder onBind(Intent intent) {
            return null;
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
            data = intent.getStringExtra("data");
            loadURL(data);

            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("URL App status :")
                    .setContentText("The app is running in background")
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setContentIntent(pendingIntent)
                    .build();
            startForeground(1, notification);

            handler.postDelayed(runnable = new Runnable() {
                    public void run() {
                            Toast.makeText(MyService.this, "" + data, Toast.LENGTH_SHORT).show();
                            loadURL(data);

                            handler.postDelayed(runnable, delay);
                    }
            }, delay);
            return START_STICKY;
    }

    @Override
    public void onDestroy() {
            stopSelf();
    }

    public void loadURL(String data) {
            try {
                    RequestFuture<JSONObject> requestFuture = RequestFuture.newFuture();
                    final String mURL = "http://localhost/att.php?emp_id=" + data + "&status=&submit=Insert";
                    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
                            mURL, new JSONObject(), requestFuture, requestFuture);
                    MySingleton.getInstance(this).addToRequestQueue(request);
                    Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();

            } catch (Exception e) {
                    Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
    }
}

App.class for notifications :
public class App extends Application {
public static final String CHANNEL_ID = "channel ID";

@Override
public void onCreate() {
    super.onCreate();
    createnotificationChannel();
}
private void createnotificationChannel(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID, "URL channel ID",
                NotificationManager.IMPORTANCE_DEFAULT);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(serviceChannel);
    }
}

}
And the MainActivity where the foreground service is started :
public class MainActivity extends AppCompatActivity {

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

    data = getIntent().getStringExtra("ID");
    Intent intent = new Intent(MainActivity.this, MyService.class);
    intent.putExtra("data", data);
    ContextCompat.startForegroundService(this,intent);
}

I have searched alot but I cant fint out what is wrong with my code. Just need help !

A: Read this answer

Every service can be killed depending on its phone situation. From Android 8, there are some limits for Background Execution.
Foreground services continue running even when the user isn't
  interacting with the app.but it may be killed after the app closed.

if you want to run your service after closing the app read this answer

A: This is due battery Optimiser from manufacture itself. You have manually allow background in setting.


text:
Q: During Hydra OAuth 2.0 integration facing Error : "Client authentication failed" We are using ORY Hydra for oAuth 2 and OpenId connection using Docker.
I am following this tutorial to configuring OAuth 2.0 on the server. I get the 404 Error when I check the log than find out the error which is

I have applied the Docker code which displayed in the tutorial, then also I get a 404 Error from 0.0.0.0:9000 port.


text:
Q: Dynamic changing of the text color of Toolbar MenuItem text In the app I am working on colors for various UI elements come from an HTTP response, ie coloring is done at runtime, and cannot be done using Android theming.
Other questions exist on this topic, but most are using themes, or if dynamic code, the code is not working. For example using spans:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    menuItemGoalSave = menu.findItem(R.id.action_goal_edit_save);
    SpannableString s = new SpannableString(menuItemGoalSave.getTitle() + "XX");
    ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
    s.setSpan(span, 0, s.length(), 0);
    menuItemGoalSave.setTitle(s);
    return true;
}

Or similar approaches applying HTML strings.
The code above in theory applies a span with coloring, but although the title has "XX" appended (ie the code is running, and affecting the menu item) the colour does not change.
Is there any way to dynamically affect the color of this Toolbar action item text?

A: Updated
Also it works as expected in case if you're using 'Toolbar' directly. See example
public class MainActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {

    private Toolbar mToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.inflateMenu(R.menu.menu_main);
        mToolbar.setOnMenuItemClickListener(this);
    }

    private void applyMenuItemTextColor() {
        MenuItem item = mToolbar.getMenu().findItem(R.id.action_settings);
        SpannableString s = new SpannableString(item.getTitle());
        ForegroundColorSpan span = new ForegroundColorSpan(System.currentTimeMillis() % 2 == 0 ? Color.RED :Color.GREEN);
        s.setSpan(span, 0, s.length(), 0);
        item.setTitle(s);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            applyMenuItemTextColor();//supportInvalidateOptionsMenu();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Original answer
Your spans example works as expected. See results:

Here's code used for this sample:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem item = menu.findItem(R.id.action_settings);
        SpannableString s = new SpannableString(item.getTitle());
        ForegroundColorSpan span = new ForegroundColorSpan(System.currentTimeMillis() % 2 == 0 ? Color.RED :Color.GREEN);
        s.setSpan(span, 0, s.length(), 0);
        item.setTitle(s);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            supportInvalidateOptionsMenu();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

I hope this will be helpful. Please let me know if there are any questions.

A: Try this:
TextView liveitem = (TextView )mOptionsMenu.findItem(R.id.action_live);
liveitem.setTextColor(Color.RED);


text:
Q: jQuery .fadeIn flicker caused by browse back / forward I'm using the following code to fade in images:

However, anytime I browse back/forward, with my links, or the browser's back/forward buttons, I tend to get a flicker. It's random. On initial load it never happens.
So, do I need to set a time out..? Prevent caching..? Or, is there a better method..?
I have also hidden .slides_control img in my css file.

A: Using:
$(window).load(function(){
    var $p = $('
Refresh
').appendTo(document.body);
    $p.find('a').click(function(){
        window.location.reload();
        return false;
    });
    $('.slides_control img').css('display', "none");
    $('.slides_control img').fadeIn(800);
});

http://jsfiddle.net/fhF5E/
It does flicker when you click Refresh several times in a row.
Using:
.slides_control img {
    display: none;
}

$(window).load(function(){
    var $p = $('
Refresh
').appendTo(document.body);
    $p.find('a').click(function(){
        window.location.reload();
        return false;
    });
    $('.slides_control img').fadeIn(800);
});

http://jsfiddle.net/fhF5E/1/
I haven't been able to get it to flicker once.
Even this doesn't flicker:

$(window).load(function(){
    var $p = $('
Refresh
').appendTo(document.body);
    $p.find('a').click(function(){
        window.location.reload();
        return false;
    });
    $('.slides_control img').fadeIn(800);
});

http://jsfiddle.net/fhF5E/3/
EDIT
After reviewing the actual page that demonstrated the problem, it was discovered that the display: none was being applied to the img in such a way that on page load, the display: none selector was not selecting anything, but then was selecting after the slider effect was added (on ready).
So...
.slides_control img {
    display: none;
}

Needs to change to:
.slider img {
    display: none;
}


text:
Q: pyqtgraph: align the ticks of the x-axes in different plots This is a follow up to this question.
The question is how to adapt the x-axis scaling of multiple pyqtgraphs when one of the graphs is rescaled. My desired result is that the ticks of all graphs align perfectly, so that you can directly compare the content of both graphs.
The given answer archives that task, of rescaling the graphs on changes but when the content of the graphs differs the y-Axis description tends to be of different size which somehow messes everything up.
For example in the image below I adjusted the bottom plot to roughly cover the 0-100 range. Strangely the upper plot is showing a bigger interval.
Any ideas how to align the ticks while rescaling?

Source code of the example:
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
from pyqtgraph.dockarea import *
import sys

def onSigRangeChanged(r):
    w1.sigRangeChanged.disconnect(onSigRangeChanged)
    w2.sigRangeChanged.disconnect(onSigRangeChanged)
    if w1==r:
        w2.setRange(xRange=r.getAxis('bottom').range)
    elif w2 == r:
        w1.setRange(xRange=r.getAxis('bottom').range)

    w1.sigRangeChanged.connect(onSigRangeChanged)
    w2.sigRangeChanged.connect(onSigRangeChanged)

app = QtGui.QApplication(sys.argv)

win = QtGui.QMainWindow()
area = DockArea()
win.setCentralWidget(area)
win.resize(1000,500)
win.setWindowTitle('pyqtgraph example: dockarea')

d1 = Dock("Dock1")
d2 = Dock("Dock2")
area.addDock(d1, 'bottom')
area.addDock(d2, 'bottom', d1)

w1 = pg.PlotWidget(title="Dock 1 plot")
w1.plot(np.random.normal(size=100)*1e12)
w1.plotItem.showGrid(x=True,y=True,alpha=1)
d1.addWidget(w1)

w2 = pg.PlotWidget(title="Dock 2 plot")
w2.plot(np.random.normal(size=100))
w2.plotItem.showGrid(x=True,y=True,alpha=1)
d2.addWidget(w2)

w1.sigRangeChanged.connect(onSigRangeChanged)
w2.sigRangeChanged.connect(onSigRangeChanged)

win.show()

sys.exit(app.exec_())

A: I just found the answer in this question.
Instead of connecting to the sigRangeChanged event we can directly link the axes scales by w2.setXLink(w1). Of course we have to remove the connections to  sigRangeChanged or the scales will shoot to the sky. Here is the example code:
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
from pyqtgraph.dockarea import *
import sys

app = QtGui.QApplication(sys.argv)

win = QtGui.QMainWindow()
area = DockArea()
win.setCentralWidget(area)
win.resize(1000,500)
win.setWindowTitle('pyqtgraph example: dockarea')

d1 = Dock("Dock1")
d2 = Dock("Dock2")
area.addDock(d1, 'bottom')
area.addDock(d2, 'bottom', d1)

w1 = pg.PlotWidget(title="Dock 1 plot")
w1.plot(np.random.normal(size=100)*1e12)
w1.plotItem.showGrid(x=True,y=True,alpha=1)
d1.addWidget(w1)

w2 = pg.PlotWidget(title="Dock 2 plot")
w2.plot(np.random.normal(size=100))
w2.plotItem.showGrid(x=True,y=True,alpha=1)
w2.setXLink(w1)
d2.addWidget(w2)

win.show()

sys.exit(app.exec_())


text:
Q: Order unversioned files in PhpStorm by folder I wonder if there is any way in PhpStorm IDE to order the Unversioned Files (in the bottom window under "9: Changes" tab) by the folder in which they are, instead than by their file name.

A: Found the "Group by Directory" button (or CTRL + P) that groups the files into folders.
This is not exactly what I wanted though, because in this way I have to explore the folder tree.
Instead, I would like a list of files (as before), but ordered by folder name.


text:
Q: Custom tooltip or custom labels (chart.js 2)? I need to get a chart like this and I have no idea how to get it.

I've tried with custom tooltips but I need show them all of them at the same time. I've tryed as well with chartjs-plugin-datalabels but the labels are inside the canvas and they appear cut.
Do I need to create a html tooltip for every data?
Any ideas?
Updated:
Here is my code:
options: {
    responsive: true,
    maintainAspectRatio: true,
    legend: {
        display: false
    },
    animation: {
        animateScale: true,
        animateRotate: true
    },
    cutoutPercentage: 60,
    circumference: 2 * Math.PI,
    showAllTooltips: true,
    tooltips: {
        enabled: false
    },
    plugins: {
        datalabels: {
            backgroundColor: function(context) {
                return context.dataset.backgroundColor;
            },
            borderColor: 'white',
            borderRadius: 50,
            borderWidth: 1,
            anchor: 'end',
            align: 'end',
            color: 'white',
            padding: 10,
            font: {
                weight: 'normal',
                size: '10'
            },
            formatter: function(value, context) {
                var percentageNum = context.chart.data.datasets[0].data[context.dataIndex]
                return percentageNum + '\n  %';
            }
        }
    }
}

and this is what I get:


text:
Q: a+ command in python reads but does not append For example, I have a text file that contains 4 lines of this statement "this is shirin" when I run the following code nothing happens on my file:
file = open('test.txt', 'a+')
for i in file:
    if len(i) == 0 or 'this' in i:
        file.write('test')
file.close()

A: When you open the file in append mode, the initial position is at the end, so there's nothing to read and the loop ends immediately. You need to rewind to the beginning of the file to read. And if you want to keep reading, you need to seek again after writing at the end.
with open('test.txt', 'a+') as file:
    file.seek(0)
    while True:
        i = file.readline()
        if not i:
            break
        oldpos = file.tell()
        if 'this' in i:
            file.write('test')
            file.seek(oldpos)


text:
Q: Can't find LESS bootstrap 3 files in download Ok so this is more a general question then an issue with code however I used the compiler on Bootstrap 3 website and changed the point at which the navbar collapses and goes mobile or whatever you want to call it.
This worked fine I re-uploaded the new bootstrap files over the old one (of course any additional changes to CSS are defined in a separate styles.css sheet so that is safe and sound.
My question is I keep reading everywhere that I should have .less files yet my changes work perfectly and I just have css js and font files containing files like bootstrap.css bootstrap.min.css and so on.
Where are these less files I am meant to have? Or is this only in an older version of Bootstrap for example.
If someone can shred some light on this that would be great.

A: https://github.com/twbs/bootstrap/archive/v3.1.1.zip here you finde the less files.
Less is a CSS pre-processor, which can handle Variables etc. So Less Files can be compiled to css.
So you don't need them if you edit the css directly.


text:
Q: Vaadin - Lazy Query Container I'm doing my project in Vaadin 7. I need to implement a Lazy Query Container for a Treetable. I will get data for the Treetable from a web service.
Could someone please show how to use a Lazy Query Container with a web service as my data source?
Please let me know the steps required to implement this or show sample code to get me started.

A: There is good documentation for LQC here: https://vaadin.com/wiki/-/wiki/Main/Lazy%20Query%20Container
The examples in documentation are implementing MovieQuery using javax.persistence API, but it might be  easier to use the simple MockQuery example as basis and replace the actual data fetching with webservice calls.

A: Have a look at the following lazy loading Hierarchical interface. All data is read from a webservice IViewService. The example uses the Tree component but it also works for TreeTable.

It's very important to store all elements in a local structure (in my case in the HashMap hierarchy), do not read elements multiple times this does not work. I think because Vaadin does not use equals() and hashCode().
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.softmodeler.common.CommonPlugin;
import com.softmodeler.model.OutputNode;
import com.softmodeler.service.IViewService;
import com.vaadin.data.Container.Hierarchical;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.util.BeanItem;

/**
 * @author Flavio Donzé
 * @version 1.0
 */
public class OutputNodeHierachical implements Hierarchical {
    private static final long serialVersionUID = 8289589835030184018L;

    /** the view service */
    private IViewService service = CommonPlugin.getService(IViewService.class);

    /** collection of all root nodes */
    private List<OutputNode> rootNodes = null;
    /** parent=>children mapping */
    private Map<OutputNode, List<OutputNode>> hierarchy = new HashMap<>();

    /**
     * constructor
     *
     * @param rootNodes collection of all root nodes
     */
    public OutputNodeHierachical(List<OutputNode> rootNodes) {
        this.rootNodes = Collections.unmodifiableList(rootNodes);

        addToHierarchy(rootNodes);
    }

    @Override
    public Collection<?> getChildren(Object itemId) {
        try {
            List<OutputNode> children = hierarchy.get(itemId);
            if (children == null) {
                OutputNode node = (OutputNode) itemId;
                children = service.getChildren(node.getNodeId(), false);

                hierarchy.put(node, children);

                // add children to hierarchy, their children will be added on click
                addToHierarchy(children);
            }
            return children;
        } catch (Exception e) {
            VaadinUtil.handleException(e);
        }
        return null;
    }

    /**
     * add each element to the hierarchy without their children hierarchy(child=>null)
     *
     * @param children elements to add
     */
    private void addToHierarchy(List<OutputNode> children) {
        for (OutputNode child : children) {
            hierarchy.put(child, null);
        }
    }

    @Override
    public boolean areChildrenAllowed(Object itemId) {
        return !((OutputNode) itemId).getChilds().isEmpty();
    }

    @Override
    public boolean hasChildren(Object itemId) {
        return !((OutputNode) itemId).getChilds().isEmpty();
    }

    @Override
    public Object getParent(Object itemId) {
        String parentId = ((OutputNode) itemId).getParentId();
        for (OutputNode node : hierarchy.keySet()) {
            if (node.getNodeId().equals(parentId)) {
                return node;
            }
        }
        return null;
    }

    @Override
    public Collection<?> rootItemIds() {
        return rootNodes;
    }

    @Override
    public boolean isRoot(Object itemId) {
        return rootNodes.contains(itemId);
    }

    @Override
    public Item getItem(Object itemId) {
        return new BeanItem<OutputNode>((OutputNode) itemId);
    }

    @Override
    public boolean containsId(Object itemId) {
        return hierarchy.containsKey(itemId);
    }

    @Override
    public Collection<?> getItemIds() {
        return hierarchy.keySet();
    }

    @Override
    public int size() {
        return hierarchy.size();
    }

    @Override
    public boolean setParent(Object itemId, Object newParentId) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Item addItem(Object itemId) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Object addItem() throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean removeItem(Object itemId) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean removeAllItems() throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Class<?> getType(Object propertyId) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Collection<?> getContainerPropertyIds() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Property<?> getContainerProperty(Object itemId, Object propertyId) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean removeContainerProperty(Object propertyId) throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

}

Adding the container to the Tree like this:
OutputNodeHierachical dataSource = new OutputNodeHierachical(rootNodes);

Tree mainTree = new Tree();
mainTree.setSizeFull();
mainTree.setContainerDataSource(dataSource);
mainTree.addItemClickListener(new ItemClickListener() {
    private static final long serialVersionUID = -413371711541672605L;

    @Override
    public void itemClick(ItemClickEvent event) {
        OutputNode node = (OutputNode) event.getItemId();
        openObject(node.getObjectId());
    }
});


text:
Q: My php $_SESSION is not saving I'm starting with PHP, so I have no idea what's going wrong. I'm trying to update some value in my $_SESSION var using a function, but is not working.
First of all, I started the session and set a default value to the session if it is "undefined" in my header.php:
  <?php
    session_start();
    if (!isset($_SESSION["locale"])) {
      $_SESSION["locale"] = 'pt_BR';
    }
  ?>

Then I have some ajax which calls my PHP function.
  $('#change_locale_br').click(function() {
    $.ajax({
      type: "POST",
      url: "i18n/i18n_functions.php",
      data: { action: "changelocale", new_locale: "pt_BR" },
      success: function() {
      }
    });
  });

After in the php file, I have the following code:
  <?php
    function changelocale($l) {
      $_SESSION["locale"] = $l;
    }

    if(isset($_POST['action']) && $_POST['action'] == 'changelocale'){
        $l = $_POST['new_locale'];
        changelocale($l);
    }
  ?>

So the changelocale function is being called with the different values (pt_BR, es and etc), but after called it doesn't really change the $_SESSION["locale"] value.
I made a lot of research and NONE of the suggestions made here or in the PHP documentation page worked. Does someone knows what could be done in this case?
Thanks in advance.

A: You need to include session_start() at the top of your page, which you intend to set or access $_SESSION information.

A: Here is the solution: I called session_write_close(); (which is used to assure session data will be "unlocked", since php doesn't allow concurrent writes) right after setting the default values for the session in my header.php:
  <?php
    ini_set('session.cookie_domain', 'localhost');
    if(!isset($_SESSION)) session_start();

    if (!isset($_SESSION["locale"])) {
      $_SESSION["locale"] = 'pt_BR';
    }
    session_write_close();
  ?>

Then in my changelocale.php I called the session_start() and at the end called the session_write_close(). It's like this now:
  <?php
    if(!isset($_SESSION)) session_start();

    function changelocale($new_locale) {
      $_SESSION["locale"] = $new_locale;
    }

    if(isset($_POST['action']) && $_POST['action'] == 'changelocale'){
        $l = $_POST['new_locale'];
        changelocale($l);
    }
    session_write_close();
  ?>


text:
Q: How to remove border on input while being active Currently studying a little bit of simple coding for school. I tried copying the Twitter UI but how do I remove the border on the input element while typing?
Here's what it's look like
And here's what it's look like while typing in it
Here is my code

<!DOCTYPE html>
<html>
  <head>
    <style>
      .twitter-dp {
        width: 50px;
        height: 50px;
        object-fit: cover;
        border-radius: 25px;
        vertical-align: middle;
        margin-right: 5px;
      }

      .text {
        font-size: 17px;
        border: none;
        width: 300px;
        vertical-align: middle;
      }

      .tweet {
        vertical-align: middle;
        background-color: rgb(74, 171, 240);
        border-style: none;
        font-style: arial;
        font-size: 17px;
        color: white;
        padding-top: 5px;
        padding-bottom: 5px;
        padding-left: 15px;
        padding-right: 15px;
        border-radius: 25px;
        cursor: pointer;
      }

      .tweet:hover {
        opacity: 0.8;
      }

      input {
        border: none;
        background-color: transparent;
        resize: none;
        outline: none;
      }
    </style>
  </head>
  <body>
    <img class="twitter-dp" src="practiceimage.jpg" />
    <input class="text" type="text" placeholder="What's happening?" />
    <button class="tweet">Tweet</button>
  </body>
</html>

A: It's hard to say for sure without seeing the html codes, but you can try to add these codes between style tags.
input {
    border: none;
    background-color: transparent;
    resize: none;
    outline: none;
}


text:
Q: Can't use static library in a titanium module I am trying to add a static library to a titanium iphone module i have created, and it seems that whenever i add the library to the "Link binary with libraries", and use titanium run titanium returns the following error:
[ERROR] Error: Traceback (most recent call last):
[DEBUG] File "/Library/Application Support/Titanium/mobilesdk/osx/1.7.2/iphone/builder.py", line 1148, in main
[DEBUG] execute_xcode("iphonesimulator%s" % link_version,["GCC_PREPROCESSOR_DEFINITIONS=__LOG__ID__=%s DEPLOYTYPE=development TI_DEVELOPMENT=1 DEBUG=1 TI_VERSION=%s %s" % (log_id,sdk_version,debugstr)],False)
[DEBUG] File "/Library/Application Support/Titanium/mobilesdk/osx/1.7.2/iphone/builder.py", line 1066, in execute_xcode
[DEBUG] output = run.run(args,False,False,o)
[DEBUG] File "/Library/Application Support/Titanium/mobilesdk/osx/1.7.2/iphone/run.py", line 39, in run
[DEBUG] sys.exit(rc)
[DEBUG] SystemExit: 65
[ERROR] Build Failed. See: /var/folders/ot/ot5FPlA3EZyk6n8ZnYeWxk+++TI/-Tmp-/m9mX89ati/test2/build/iphone/build/build.log

build.log shows:
** BUILD FAILED **

The following build commands failed:
    Ld build/Debug-iphonesimulator/test2.app/test2 normal i386
(1 failure)
EXIT CODE WAS: 65

Exception detected in script:
Traceback (most recent call last):
  File "/Library/Application Support/Titanium/mobilesdk/osx/1.7.2/iphone/builder.py", line 1148, in main
    execute_xcode("iphonesimulator%s" % link_version,["GCC_PREPROCESSOR_DEFINITIONS=__LOG__ID__=%s DEPLOYTYPE=development TI_DEVELOPMENT=1 DEBUG=1 TI_VERSION=%s %s" % (log_id,sdk_version,debugstr)],False)
  File "/Library/Application Support/Titanium/mobilesdk/osx/1.7.2/iphone/builder.py", line 1066, in execute_xcode
    output = run.run(args,False,False,o)
  File "/Library/Application Support/Titanium/mobilesdk/osx/1.7.2/iphone/run.py", line 39, in run
    sys.exit(rc)
SystemExit: 65

I'm desperate, anyone help?
Thank you!

A: take a look at this section of the documentation
http://wiki.appcelerator.org/display/guides/Module+Developer+Guide+for+iOS#ModuleDeveloperGuideforiOS-AddingSpecialCompilerDirectives

A: add this line to the module.xcconfig
OTHER_LDFLAGS=$(inherited) -framework GameKit

where GameKit is your missing framework that is used in your library.


text:
Q: Python Strings in Python Dictionary to Integers is there any method to converts python dictionary with strings to python dictionary with corresponding integer arrays
Dictionary with String Arrays:
 {1: '[8, 9, 10, 11, 12, 13, 14, 15, 16]',
 2: '[17, 18, 19, 20, 21, 22, 23]',
 3: '[1, 2, 3, 4, 5, 6, 7]',
 4: '[24, 25, 26]'}

Converted to Dictionary with corresponding Integer Arrays:
{1: [8, 9, 10, 11, 12, 13, 14, 15, 16],
 2: [17, 18, 19, 20, 21, 22, 23],
 3: [1, 2, 3, 4, 5, 6, 7],
 4: [24, 25, 26]}

A: Using ast.literal_eval we can loop over the dictionary and "cast" the string into their literals:
>>> import ast
>>> x =  {1: '[8, 9, 10, 11, 12, 13, 14, 15, 16]',
...  2: '[17, 18, 19, 20, 21, 22, 23]',
...  3: '[1, 2, 3, 4, 5, 6, 7]',
...  4: '[24, 25, 26]'}
>>>
>>> {k: ast.literal_eval(v) for k,v in x.items()}
{1: [8, 9, 10, 11, 12, 13, 14, 15, 16], 2: [17, 18, 19, 20, 21, 22, 23], 3: [1, 2, 3, 4, 5, 6, 7], 4: [24, 25, 26]}


text:
Q: Tweepy error Stream.__init__() missing 2 required positional arguments: 'access_token' and 'access_token_secret' I'm trying to set up a Retweet bot using the Tweepy module for Twitter's API, and have been working through errors bit by bit as the tutorial I was following was an older version of Tweepy. I'm new-ish to Python coding, and certainly haven't integrated API's before, so bear with me on this :)
Here's my code:
# import dependencies
import tweepy
import os
from dotenv import load_dotenv
from streamlistener import StreamListener

# load our .env file to make use of the environment variables
load_dotenv()

# import and assign our environment variables
API_KEY = os.getenv('twitter_api_key')
API_SECRET = os.getenv('twitter_api_secret')
ACCESS_TOKEN = os.getenv('twitter_access_token')
TOKEN_SECRET = os.getenv('twitter_access_secret')

# instantiate oauth handler and set access token
twitter_oauth = tweepy.OAuthHandler(API_KEY, API_SECRET)
twitter_oauth.set_access_token(ACCESS_TOKEN, TOKEN_SECRET)

# instantiate tweepy api object using the authentication handler object
twitter_api = tweepy.API(twitter_oauth)

# attempt credential verification. prints exception if something is wrong
try:
    print(twitter_api.verify_credentials())
    print("Successfully logged in")
except tweepy.errors.TweepyException as e:
    print(e)
except Exception as e:
    print(e)

# instantiate a StreamListener object
tweets_listener = StreamListener(twitter_api)

#instantiate a tweepy.Stream object
tweet_stream = tweepy.Stream(twitter_api.auth, tweets_listener)

# Use the filter method
tweet_stream.filter(track=["#VTuber", "#ENVTuber", "vtuber", "Vtuber", "VTuberEN"], languages=["en"])

And the error I'm getting is:
Traceback (most recent call last):   File "C:\Python\bot.py", line 36, in <module>     tweet_stream = tweepy.Stream(twitter_api.auth, tweets_listener) TypeError: Stream.__init__() missing 2 required positional arguments: 'access_token' and 'access_token_secret'

I've tried adding ACCESS_TOKEN and TOKEN_SECRET into line 36 (tweepy.Stream arguments), but either I did it wrong or that's not the fix.

A: You're using syntax from an older version of Tweepy.
Tweepy v4.0.0 changed Stream to accept consumer_key, consumer_secret, access_token, and access_token_secret parameters for initialization.


text:
Q: How to use the Paint event to draw shapes at mouse coordinates I recently started programming in C# obviously and was trying to do a simple WinForms app that takes mouse coordinates and scales a Rectangle according to the coordinates.
The issue I am facing is that I don't know how to call a method that uses more arguments (in this case is x, y and PaintEventArgs). Or, I do know what to do with the PaintEvent.
Here is the whole code, since its pretty short and rather simple:
using System;
using System.Drawing;
using System.Windows.Forms;

public partial class Form1 : Form
{
    public void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        int x = e.X;
        int y = e.Y;
        String data = (x.ToString() + " " + y.ToString());
        DrawRect(Something, x, y);
    }

    PaintEventArgs pEventArgs;
    private void Form1_Paint(object sender, PaintEventArgs e)
    {

    }

    public void DrawRect(PaintEventArgs e, int rey, int rex)
    {
        Graphics gr = e.Graphics;
        Pen pen = new Pen(Color.Azure, 4);
        Rectangle rect = new Rectangle(0, 0, rex, rey);
        gr.DrawRectangle(pen, rect);
    }
}

I'm trying to call the DrawRect() method to draw the Rectangle with width and height according to the mouse coordinates.
So how can I call the DrawRect() with coordinates and PaintEventArgs?

A: When drawing on a Control's surface, you always use the Paint event of that Control or override the OnPaint method of a Custom/User Control.
Do not try to store its Graphics object: it becomes invalid as soon as the Control is invalidated (repainted).
Use the Graphics object provided by the PaintEventArgs object.
When a more complex procedure is required to draw different shapes, you can pass the e.Graphics object to different methods which will use this object to perform specialized drawings.

In the example, the coordinates and other properties of each drawn shape are assigned to a specialized class, DrawingRectangle (a simplified structure here, it can hold more complex functionalities).
A List<DrawingRectangle>() stores the references of all the DrawingRectangle objects generated in a session (until the drawing is cleared).
Each time a Left MouseDown event is generated on the Control's surface, a new DrawingRectangle object is added to the List.
The e.Location is stored both as the DrawingRectangle.StartPoint (a value that doesn't change) and the DrawingRectangle.Location: this value will be updated when the mouse pointer is moved.
When the Mouse is moved, the current e.Location value is subtracted from the starting point coordinates previously stored. A simple calculation allows to draw the shapes from all sides.
This measure determines the current Size of the Rectangle.
To remove a Rectangle from the drawing, you just need to remove its reference from the List and Invalidate() the Control that provides the drawing surface.
To clear the drawing surface, clear the List<DrawingRectangle>() (drawingRects.Clear()) and call Invalidate().
Some other examples here:
Transparent Overlapping Circular Progress Bars
GraphicsPath and Matrix classes
Connecting different shapes
Drawing Transparent/Translucent Custom Controls
// Assign the Color used to draw the border of a shape to this Field
Color SelectedColor = Color.LightGreen;
List<DrawingRectangle> drawingRects = new List<DrawingRectangle>();

public class DrawingRectangle
{
    public Rectangle Rect => new Rectangle(Location, Size);
    public Size Size { get; set; }
    public Point Location { get; set; }
    public Control Owner { get; set; }
    public Point StartPosition { get; set; }
    public Color DrawingcColor { get; set; } = Color.LightGreen;
    public float PenSize { get; set; } = 3f;
}

private void form1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button != MouseButtons.Left) return;
    DrawingRects.Add(new DrawingRectangle() {
        Location = e.Location,
        Size = Size.Empty,
        StartPosition = e.Location,
        Owner = (Control)sender,
        DrawingcColor = SelectedColor // <= Shape's Border Color
    });
}

private void form1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button != MouseButtons.Left) return;
    var dr = DrawingRects[DrawingRects.Count - 1];
    if (e.Y < dr.StartPosition.Y) { dr.Location = new Point(dr.Rect.Location.X, e.Y); }
    if (e.X < dr.StartPosition.X) { dr.Location = new Point(e.X, dr.Rect.Location.Y); }

    dr.Size = new Size(Math.Abs(dr.StartPosition.X - e.X), Math.Abs(dr.StartPosition.Y - e.Y));
    this.Invalidate();
}

private void form1_MouseUp(object sender, MouseEventArgs e)
{
    // The last drawn shape
    var dr = DrawingRects.Last();
    // ListBox used to present the shape coordinates
    lstPoints.Items.Add($"{dr.Location}, {dr.Size}");
}

private void form1_Paint(object sender, PaintEventArgs e)
{
    DrawShapes(e.Graphics);
}

private void DrawShapes(Graphics g)
{
    if (DrawingRects.Count == 0) return;
    g.SmoothingMode = SmoothingMode.AntiAlias;
    foreach (var dr in DrawingRects) {
        using (Pen pen = new Pen(dr.DrawingcColor, dr.PenSize)) {
            g.DrawRectangle(pen, dr.Rect);
        };
    }
}

// A Button used to save the current drawing to a Bitmap
private void btnSave_Click(object sender, EventArgs e)
{
    using (var bitmap = new Bitmap(panCanvas.ClientRectangle.Width, panCanvas.ClientRectangle.Height))
    using (var g = Graphics.FromImage(bitmap)) {
        DrawShapes(g);
        bitmap.Save(@"[Image Path]", ImageFormat.Png);
        // Clone the Bitmap to show a thumbnail
    }
}

// A Button used to clear the current drawing
private void btnClear_Click(object sender, EventArgs e)
{
    drawingRects.Clear();
    this.Invalidate();
}

A:
app that takes mouse coordinates and scales rectangle according to the coordinates

I'd expect to see something like this (pseudocode):
Point _point;

void Form1_MouseMove(object sender, MouseEventArgs e)
{
    ... // calculate new coordinates/scale factor/whatever here
    _point = ... ; // store results in fields
    Invalidate(); // this will cause repaint every time you move mouse
}

void Form1_Paint(object sender, PaintEventArgs e)
{
    ... // take values from fields
    e.Graphics.DrawRectangle(pen, rect); // draw
}

It's pretty simply. Painting is a combination of Invalidate() calls, which rise up paint event. The variables you pass using fields.

A: The PaintEventArgs allows you to access to the Graphics object, you need that one to draw something.
If you don't want to use the PaintEventArgs, i suggest that you call the CreateGraphics() method of your Form, and it will allow you to draw the rectangle.
To improve performance, i suggest that you use the using(...){ } keywork in order to dispose the Graphics object and the Pen object.
You need to include System.Drawing in order to use Graphics and Pen.
You're code will look like that :
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        Point _coordinates;

        public Form1()
        {
            this._coordinates = new Point();
            this.InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        public void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            this._coordinates = new Point(e.X, e.Y);
            this.Invalidate();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            // Don't draw on first Paint event
            if(this._coordinates.X != 0 && this._coordinates.Y != 0)
            {
                this.DrawRect(e);
            }
        }

        public void DrawRect(PaintEventArgs e)
        {
            using (Pen pen = new Pen(Color.Azure, 4))
            {
                Rectangle rect = new Rectangle(0, 0, this._coordinates.X, this._coordinates.Y);
                e.Graphics.DrawRectangle(pen, rect);
            }
        }
    }
}

A: Drawing in WinForms application works in a slightly different way then you probably expect. Everything on screen now is considered to be temporary, if you e.g. minimize and restore your window, the onscreen stuff will be erased and you'll be asked to repaint it again (your window's Paint event will be fired by the system).
That's why that DrawRect method expects PaintEventArgs argument: it is supposed to be called only withing your Paint event handler. If you call it from outside (like it is suggested in other answer) your rectangles might behave inconsistently.
I would suggest remember your rectangles in some internal variable and then repaint them when asked for that by the system:
private Point pointToDrawRect = new Point(0,0);
public void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        int x = e.X;
        int y = e.Y;
        String data = (x.ToString() + " " + y.ToString());
        pointToDrawRect= new Point(x, y);
        Invalidate();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
         if(pointToDrawRect.X != 0 || pointToDrawRect.Y != 0)
         {
             DrawRect(e, pointToDrawRect.X, pointToDrawRect.Y);
         }
    }

    public void DrawRect(PaintEventArgs e, int rey, int rex)
    {
            using (Pen pen = new Pen(Color.Azure, 4))
            {
                Rectangle rect = new Rectangle(0, 0, rex, rey);
                e.Graphics.DrawRectangle(pen, rect);
            }
    }


text:
Q: About log information when using Java Adapter of MobileFirst Platform Foundation 7.1 When I use Java Adapter with MFPF 7.1 and generate the log as below code.
@Produces("application/xml")
public String hello(){
    //log message to server log
    logger.info("Logging info message111...");

    return "<title>Hello111 from the Java REST adapter</title><body>Hello from the Java REST adapter</body>";
}

But When deploying the adapter in mobilefirst Studio and calling the adapter, I failed to find the log information.
Another question is that I found AnalyticsAPI is not valid in MFPF 7.1. How can I generate log information into the analystics console?

A: You are writing your log in INFO level; you need to ensure that the server is running in reporting mode that will display INFO-level messages in its messages.log.
From the Servers view, double-click on MobileFirst Development Server and change the logging level.


text:
Q: ELI5: What is a macro name? I'm following this tutorial about the basics of Code::Blocks projects. To use multiple files in a project, you need a header file. This section gives the source code for the most basic of header files, but gives no explanation.
#ifndef HELLO_H_INCLUDED
#define HELLO_H_INCLUDED

void hello();

#endif // HELLO_H_INCLUDED

I got curious about the significance of HELLO_H_INCLUDED. I changed it to various names, and the project parsed and ran properly regardless of what I named it.
However, if you delete HELLO_H_INCLUDED entirely, it an error arises saying no macro name given in #ifndef directive.
So, explain to me like I'm five years old: What is a macro name, what does it do, and why is it required?


text:
Q: Import a client side module in NextJs I am trying to import the @azure/communication-calling module to my NextJs application. Although I when I try to build the project I get this error: > Build error occurred
ReferenceError: window is not defined.
I tried to use dynamic import, but it didn't work for me because it returns react.componenttype element but I need my original module. Can someone help how can I achieve this?
const AzureCommunicationCallingSDKLocalVideoStream = dynamic(
() =>
import("@azure/communication-calling").then(
  (module) => module.LocalVideoStream
),
{ ssr: false }
);


text:
Q: I'm trying to play a video using vlcj inside a JPanel I'm trying to play a video using vlcj inside a JPanel but it doesn't work for me. The message exception I am getting is:

"java.lang.IllegalStateException: The video surface component must be displayable"

The code:
public class MediaPlayerPanel extends JPanel {

    private static final long serialVersionUID = 1L;

    MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
    EmbeddedMediaPlayer mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
    Canvas c = new Canvas();
    JPanel p = new JPanel();

    public MediaPlayerPanel()   {

        c.setBackground(Color.black);

        p.setLayout(new BorderLayout());
        p.add(c, BorderLayout.CENTER);

        mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(c));
        c.setVisible(true);
        p.setVisible(true);
    }

    public  void play(String video) {

        mediaPlayer.playMedia(video);

    }

}

public class VideoPlayer {

     public static void main(final String[] args) {

         NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
         Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);

            JFrame frame = new JFrame("Video Player");
            MediaPlayerPanel mpp = new MediaPlayerPanel();

            frame.setLocation(100, 100);
            frame.setSize(1050, 600);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            frame.add(mpp, BorderLayout.CENTER);
            frame.setVisible(true);

            mpp.play("E:\\Filmek\\Game.of.Thrones.S04E02.HDTV.x264-2HD\\game.of.thrones.s04e02.hdtv.x264-2hd.mp4");

     }
}

A: That error message usually means that you tried to do mediaPlayer.play() before you showed (or pack()'ed) the application frame that contains the video surface.
In the code you posted, you are not adding your panel p to the MediaPlayerPanel panel that you create. So your video surface Canvas is not actually attached to any visible component hierarchy.
Your MediaPlayerPanel should set a BorderLayout on itself and add p to that.


text:
Q: How to search for an element in a vector? i have a code like this....
std::vector<string>::iterator p;
p =  find(v.begin(),v.end(),"asdasda");
cout << *p << endl;

if "asdasda" is not a part  of the vector, p points to some garbage and cout gives a seg fault. what should be the if statement that would make the cout execute onlyif "asdasda" was found?
and also the position of "asdasda" in v.. like if we had earlier declared v[3] as "asdasda",
then how can i know from the find that v[3] is "asdasda"?

A: If std::find doesn't find anything, the iterator is set to v.end() in this case.
if ( p != v.end() )
{
    // iterator is good
}

Also note the general case of std::find.
Here's a typical definition of it:
namespace std {
  template <class InputIterator, class T>
  InputIterator find(InputIterator start,
                     InputIterator finish,
                     const T& value);
}

In case std::find fails, it will return the finish iterator because the search is [start, finish) and includes start but excludes finish.

A: p doesn't point to "garbage", it simply becomes v.end() when the content is not found.
if (p != v.end()) {
   std::cout << "v[" << (p - v.begin()) << "] = ";
   std::cout << *p << std::endl;
}

A: Find returns the end iterator if it doesn't find the value you search.
You can avoid your error by adding if (p != v.end()) right before your display line.


text:
Q: GROUP BY tsql, multiple records to return one I have a table as follows:
INSTR_ID    PRC_TMS     PRC_CURR_CDE    PRC_TYP    PRC_QUOTE_AMT
5901        31/03/2015  EUR             CLO         89.73
5901        31/03/2015  EUR             LST         89.53
1123        31/03/2015  USD             CLO         12.35

What I need to be able to do is query a select on this, but where I've got multiple INSTR_ID's, if I have a CLO PRC_TYP then return that PRC_QUOTE_AMT, else the LST PRC_QUOTE_AMT.
I've looked at group by, but unsure of how to build the logic to select CLO else LST?
Can someone point me in the right direction?

A: You can prioritize the rows (choosing one) by using row_number():
select t.*
from (select t.*,
             row_number() over (partition by INSTR_ID
                                order by (case when PRC_TYP = 'CLO' then 1
                                               when PRC_TYPE = 'LST' then 2
                                               else 3
                                          end)
                               ) as seqnum
      from table t
     ) t
where seqnum = 1;

For the data you provide, you can also use group by:
select INSTR_ID, PRC_TMS, PRC_CURR_CDE,
       coalesce(max(case when PRC_TYP = 'CLO' then PRC_QUOTE_AMT end),
                max(PRC_QUOTE_AMT) ) as PRC_QUOTE_AMT
from table t
group by INSTR_ID, PRC_TMS, PRC_CURR_CDE;

A: Return if CLO, also return if no row with same id and CLO exists.
select * from tablename t1
where PRC_TYP = 'CLO'
 or not exists (select 1 from tablename t2
                where t1.INSTR_ID = t2.INSTR_ID
                 and t2.PRC_TYP = 'CLO')


text:
Q: Minimize integral of polynomial interpolation error Given $\mathrm{f}\in C\left[-1,1\right]$ solve:
$$
\min\int_{-1}^{1}\sqrt{\, 1 - x^{2}\,}\,\,\left\vert\,\mathrm{f}\left(x\right)-\mathrm{p}_n\left(x\right)\,\right\vert^{\,2}\,\mathrm{d}x
$$
where $\mathrm{p}_n$ is a polynomial of degree $n$ or less.
I'm assuming this problem is related to Chebyshev polynomials of the second kind because of the weight on the integral, but I'm lost after that.

A: You are correct: Chebyshev polynomials of the second kind provide an orthogonal base of $L^2(-1,1)$ with respect to the inner product
$$ \langle f,g\rangle = \int_{-1}^{1} f(x)\,g(x)\,\sqrt{1-x^2}\,dx $$
and they fulfill
$$ \int_{-1}^{1} U_n(x)\,U_m(x)\sqrt{1-x^2}\,dx =\frac{\pi}{2}\delta(m,n),\qquad \deg U_m(x) = m. $$
Given some $f(x)\in C[-1,1]\subset L^2(-1,1)$ we may assume
$$ f(x)\stackrel{L_2}{=}\sum_{m\geq 0}c_m\cdot U_m(x),\qquad c_m=\frac{2}{\pi}\int_{-1}^{1}U_m(x)\,f(x)\,\sqrt{1-x^2}\,dx $$
then, by Parseval's identity,
$$\operatorname*{argmin}_{\substack{p\in\mathbb{R}[x]\\ \deg p\leq n}}\int_{-1}^{1}\sqrt{1-x^2}\left[f(x)-p(x)\right]^2\,dx = \sum_{m=0}^{n}c_m U_m(x) $$
where
$$\int_{-1}^{1}\sqrt{1-x^2}\left[f(x)-p(x)\right]^2\,dx =\frac{\pi}{2}\sum_{m>n}c_m^2.$$


text:
Q: how to draw a popover view instead of using image on iPhone? just like the popover in the attached screenshots, the popover allow user to change themes.
I know that there are some examples around but they are all using images to achieve this, make it hard to change themes.
I believe the app in the screenshots doesn't using images to do it.
thanks for any help!

A: In my Win background such skins (called "Flat" in Delphi and WinForms) were made by drawing in code: select a color, draw a line, select another color, draw a rounded rectangle and so on.
Also, it is necessary to introduce a class "ColorTheme" with a set of fields for every color used. You may have several ColorTheme instances and swap them when you need to change color theme.


text: Q: Debug an active x dll in vb6 i am trying to debug an application in vb6 which has output type ActiveX Exe , and have reference of active dll , i have tried changing to binary compability for both of projects. but i am not able to step into that activex dll project code. can you help me with step into other project dll and debug code ? i have even tried creating project group but even i am setting up Exe project as start up , i think it is trying to run dll project first and giving an error.


text:
Q: Duplicates in table MYSQL Ok i have table in MySQL
SMESTAJ and column MESTO
I want to get all values from row MESTO, but no duplicates
Can somebody help me and tell me the correct MySQL Query?

A: Assuming: Table name  = 'SMESTAJ'
          Column name = 'MESTO'
SELECT DISTINCT MESTO FROM SMESTAJ

You can read more about the DISTINCT keyword here

A: is what you are looking for:
select distinct columnName from table;

if that is the case:
select distinct SMESTAJ from MESTO

A: If I have understood correctly:
SELECT DISTINCTROW mesto FROM SMESTAJ

Generally, the correct format is: SELECT DISTINCTROW row FROM table.
Hope this helps.


text:
Q: Merge column of 2 Dataframes if 2 are equal I have 4 csv files with different correlations (and different number of rows) and I am trying to create a new one with all correlations:
DF1:
|Var1|Var2|Corr1|
DF2:
|Var1|Var2|Corr2|
Objective:
|Var1|Var2|Corr1|Corr2|
(EDIT:
DF1:                                DF2:
Var1  Var2  Corr                    Var1   Var2  Corr2
a     b      2                      a      b     3
a     s      1                      a      z     4
c     d      0                      c      d     2

Spected Out:
DF1:
Var1  Var2  Corr  Corr2
a     b      2    3
a     s      1    NaN
c     d      0    2
a     z      NaN  4

Finish edit)
The condition is if Var1 and Var2 are the same, add Corr2 value in new column
(It would be also good to add new rows if they are new correlations in DF2)
I have this but is not working:
corr=[]
for row in DF1['Var1']:
        if DF1['Var2'] == DF2['Var2'] :    corr.append(DF2["Corr2"])

        ##else: add DF2["Var1]["Var2"]["Corr2"]

DF1["Corr2"]=corr
print(DF1)

Any idea to create this condition?
Thank you

A: Thank you for your ideas, merge works!
Your clue make it more easier.
I must edit your code to get what I asked:
DF1:                                DF2:
Var1  Var2  Corr                    Var1   Var2  Corr2
a     b      2                      a      b     3
a     s      1                      a      z     4
c     d      0                      c      d     2

This only merge if ["Var1"] and ["Var2"] are the same and the result is only a Df with the ones in common:
pd.merge(df1, df2, on=['Var1', 'Var2'])

Out:

Var1  Var2  Corr  Corr2
a     b      2     3
c     d      0     2

This merge the ones in common and keep DF1 rows and adds DF2 rows not in common:
result = DF1.merge(DF2, on=['Var1', 'Var2'], how= "outer")

Out:
DF1:
Var1  Var2  Corr  Corr2
a     b      2    3
a     s      1    NaN
c     d      0    2
a     z      NaN  4


text:
Q: Embedded System Hangs I am using TIOMAP/AM3517 based custom board which has ARM7 core + Linux 2.6.32 running on it.
Recently, I started observing an issue in which all the interfaces serial console, RNDIS/USB, Network stops responding (my type on keyboard connected to serial port/console port doesn't go through + no device is detected upon removal/insertion of USB sticks/BT dongle + Ethernet/network activities are stopped (can't login over ssh or access webPage that the system has.
I checked the power to the CPU and other power rails using DMM and it looks fine.
There is no keyboard attached so MagicSysRq cannot be used while the issue happens.
I have watchdog on the system which rebooted the system, however to reproduce the issue and to get more information of the system's state, now i have disabled the watchdog.
Finally, my system/linux is configured to reboot upon detecting softlockup which is not happening either. Also, I have enabled verbose debug options under kernel hacking but nothing seems to give any more information.
How do I debug the issue to identify the rot cause of it?


text:
Q: How to get definition of a SimpleName? Here is my setting code
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setSource(content.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    String[] sourcepathEntries = { folderPath };
    String[] encodings = { "UTF-8" };
    parser.setEnvironment(null, sourcepathEntries, encodings, true);
    parser.setUnitName(filePath);
    parser.setStatementsRecovery(true);
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);

The test file is
public class A {
    B b = new B();
    C c = new C();
    int name = 15;
    public void run() {
        int x = 25;
        int d = x + 10;
        if (x != 25) {
            d = 99;
        }
        System.out.println(d);
    }

    public B getB() {
        b.run();
        return b;
    }
}

My debug code is here
I have already get the Ibinding from SimpleName.resolveBinding() but I can't get any field information from IBinding binding. I am surprised that binding instanceof VaribleBinding return false although debug view shows that.
I can see the LocalDeclaration but I can not get it. Can anyone help me to solve this? Or provide an alternative solution.