_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d2801
train
To catch the focused input when clicking a button, you have to listen to the mousedown event as it fires before the input loses focus. The click event is too late, the input has already lost focused by that time. To get the currently focused (active) element, one can use document.activeElement. So something like this : $('#btnAdd').on('mousedown', function() { var el = document.activeElement; insertDataVarables(el, 'insertedText') }); FIDDLE A: When a cursor is positioned in a textbox save it in a global variable. The on button click insert the value to the saved element. Hope following code snippet will help you. var selctedElm; $(document).on('click', '#btnAdd', function () { selctedElm && selctedElm.val('insertedText'); }); $(document).on('click', 'input[type=text]', function() { selctedElm = $(this); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <input type="text" id="txt1" /> <input type="text" id="Text2" /> <input type="text" id="Text3" /> <br/><br/> <input type="button" value="Add" id="btnAdd" /> </div> A: This is the answer given by adeneo $('#btnAdd').on('mousedown', function() { var el = document.activeElement; insertDataVarables(el, 'insertedText') }); function insertDataVarables(myField, myValue) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA and others else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); myField.selectionStart = startPos + myValue.length; myField.selectionEnd = startPos + myValue.length; } else { myField.value += myValue; } } <div> <input type="text" id="txt1" /> <input type="text" id="Text2" /> <input type="text" id="Text3" /> <input type="button" value="Add" id="btnAdd" /> </div>
unknown
d2802
train
You can't return a cfform, because tags can't be used inside of a CFScript based component. You're far better off doing something like this with a custom tag, which then references your component to get pieces to build out the form. I would avoid (if at all possible) putting any cfform related pieces into a component, script-based or not. If you did want to ultimately go this route, you'd need to put the cfform (and it's relevant pieces) either in another component that gets called by the script based one, or in an include that then is saved to a variable. All of the solutions related to trying to get the cfform into your CFC are going to be messy. A: If you absolutely must do this (though I would shy away from it myself) you might want to have a look at this: http://www.madfellas.com/blog/index.cfm/2011/1/26/Using-CFML-tags-in-cfscript-C4X-prototype
unknown
d2803
train
You are using three params instead of two, use it like this. //Handle post register req. at '/register' app.post("/register", function(req, res) { User.register(new User({ username: req.body.username, password: req.body.password }), function(err, user) { if(err) { console.log(err); return res.render("register"); } passport.authenticate("local")(req, res, function() { res.redirect("/secret") }) }); }); A: Check to make sure your versions of mongoDB and mongoose are compatible. You can find a compatibility chart here. In addition to checking your MongoDB and mongoose versions, you should also check if it's actually connecting to the database by using a callback function when you connect to the server, like so: //Connecting to database using mongoose.connect with a callback mongoose.connect("mongodb://localhost:27017/customerapp", function(error) { if(error) { console.log("There was an error connecting to MongoDB."); console.log(error); } else { console.log("Successfully connected to MongoDB!"); } }); This callback may also work with mongoose.createConnection instead of mongoose.connect, but I haven't tried. If neither message prints to the console, then the app is not getting any response from the server, not even an error. For some reason, as long as mongoDB is running at all, GET requests still seem to work even if the connection attempt hangs, but POST requests run into trouble. Source: Mongoose never connects to mongodb
unknown
d2804
train
I'd suggest you wrapping what you have used to get the update in a function then do the function call after you hit the success method after submitting the form... In your js for example: $(document).ready(function(){ $("#contactForm").submit(function(e){ // prevent from normal form behaviour e.preventDefault(); // serialize the form data var serializedData = $(this).serialize(); $.ajax({ type : 'POST', url : "{% url 'BFS:contact_submit' %}", data : serializedData, success : function(response){ //reset the form after successful submit $("#contactForm")[0].reset(); // This will then call for the get request to update the id "myText" live_update(); }, error : function(response){ console.log(response) } }); }); function live_update(){ $.ajax({ url: "{% url 'BFS:get_user_info' %}", type: 'get', // This is the default though, you don't actually need to always mention it success: function(data) { var number = data; document.getElementById("myText").innerHTML = number; }, error: function() { alert('Got an error dude'); } }); } }); Also, for the success method within the live_update function... You could also use, success: function(data) { $("#myText").hide(); $("#myText").html(data); $("#myText").fadeIn(1000); }, That should give it a nice little fade in effect as it updates. :) A: This might be the time to introduce a frontend framework to your pipeline as it will make life easier to refresh pages upon DOM state changes. I had challenges myself trying to implement similar functionality with Django alone some years back until i introduced React Js. Here is something that could help you without learning another software altogether: Update DOM without reloading the page in Django However, you will notice that the marked answer there still uses Javascript i.e jQuery. So there is no denying the fact that you will need to implement javascript to achieve what you want. Which is why i mentioned React Js. Good luck!
unknown
d2805
train
You can use the following functions to sanitize user inputs. Custom regex functions might have some corner cases. sanitize --------- htmlspecialchars(filter_var($string, FILTER_SANITIZE_STRING), ENT_QUOTES, 'UTF-8'); wordsanitize ------------ $string = preg_replace('~\W+~', '', $string); htmlspecialchars(filter_var($string, FILTER_SANITIZE_STRING), ENT_QUOTES, 'UTF-8'); charactersanitize ----------------- $string = preg_replace('~[^A-Za-z_.]~', '', $string); htmlspecialchars(filter_var($string, FILTER_SANITIZE_STRING), ENT_QUOTES, 'UTF-8'); numbersanitize -------------- $string = preg_replace('~\D+~', '', $string); htmlspecialchars(filter_var($string, FILTER_SANITIZE_STRING), ENT_QUOTES, 'UTF-8');
unknown
d2806
train
Fixed it by using a shiny server version of the docker - not sure why but this sorted out some connection issue. Dockerfile: FROM rocker/r-ver:3.6.3 RUN apt-get update --allow-releaseinfo-change && apt-get install -y \ lbzip2 \ libfftw3-dev \ libgdal-dev \ libgeos-dev \ libgsl0-dev \ libgl1-mesa-dev \ libglu1-mesa-dev \ libhdf4-alt-dev \ libhdf5-dev \ libjq-dev \ liblwgeom-dev \ libpq-dev \ libproj-dev \ libprotobuf-dev \ libnetcdf-dev \ libsqlite3-dev \ libssl-dev \ libudunits2-dev \ netcdf-bin \ postgis \ protobuf-compiler \ sqlite3 \ tk-dev \ unixodbc-dev \ libssh2-1-dev \ r-cran-v8 \ libv8-dev \ net-tools \ libsqlite3-dev \ libxml2-dev \ wget \ gdebi ##No version control #then install shiny RUN wget --no-verbose https://download3.rstudio.org/ubuntu-14.04/x86_64/VERSION -O "version.txt" && \ VERSION=$(cat version.txt) && \ wget --no-verbose "https://download3.rstudio.org/ubuntu-14.04/x86_64/shiny-server-$VERSION-amd64.deb" -O ss-latest.deb && \ gdebi -n ss-latest.deb && \ rm -f version.txt ss-latest.deb #install packages RUN R -e "install.packages(c('xtable', 'stringr', 'glue', 'data.table', 'pool', 'RPostgres', 'palettetown', 'deckgl', 'sf', 'shinyWidgets', 'shiny', 'stats', 'graphics', 'grDevices', 'datasets', 'utils', 'methods', 'base'))" ##No version control over ##with version control and renv.lock file ##With version control over #copy shiny server config over COPY shiny-server.conf /etc/shiny-server/shiny-server.conf #avoid some errors #already in there #RUN echo 'sanitize_errors off;disable_protocols xdr-streaming xhr-streaming iframe-eventsource iframe-htmlfile;' >> /etc/shiny-server/shiny-server.conf # copy the app to the image COPY .Renviron /srv/shiny-server/ COPY global.R /srv/shiny-server/ COPY server.R /srv/shiny-server/ COPY ui.R /srv/shiny-server/ # select port EXPOSE 3838 # Copy further configuration files into the Docker image COPY shiny-server.sh /usr/bin/shiny-server.sh RUN ["chmod", "+x", "/usr/bin/shiny-server.sh"] # run app CMD ["/usr/bin/shiny-server.sh"] application.yml: proxy: title: apps - page # logo-url: https://link/to/your/logo.png landing-page: / favicon-path: favicon.ico heartbeat-rate: 10000 heartbeat-timeout: 60000 container-wait-time: 40000 port: 8080 authentication: simple admin-groups: admins container-log-path: /etc/shinyproxy/logs # Example: 'simple' authentication configuration users: - name: admin password: password groups: admins - name: user password: password groups: users # Docker configuration docker: cert-path: /home/none url: http://localhost:2375 port-range-start: 20000 # internal-networking: true - id: 10_asela_rshiny_shinyserv display-name: ASELA Dash internal shiny server version description: container has own shinyserver within it functions on docker network only not on host container-network version container-cmd: ["/usr/bin/shiny-server.sh"] access-groups: [admins] container-image: asela_r_app_shinyserv_ver:latest container-network: asela-docker-net logging: file: name: /etc/shinyproxy/shinyproxy.log
unknown
d2807
train
There is another way to create your custom AWS resources when localstack freshly starts up. Since you already have a bash script for your resources, you can simply volume mount your script to /docker-entrypoint-initaws.d/. So my docker-compose file would be: localstack: image: localstack/localstack:latest container_name: localstack_aws ports: - '4566:4566' volumes: - './localSetup.sh:/etc/localstack/init/ready.d/init-aws.sh' Also, I would prefer awslocal over aws --endpoint in the bash script, as it leverages the credentials work and endpoint for you. A: try adding hostname to the docker-compose file and editing your entrypoint file to reflect that hostname. docker-compose.yml version: '3' services: localstack: build: . hostname: localstack ports: - "8080:8080" - "4567-4582:4567-4582" localSetup.sh #!/bin/bash aws --endpoint-url=http://localstack:4572 s3 mb s3://localbucket This was my docker-compose-dev.yaml I used for testing out an app that was using localstack. I used the command docker-compose -f docker-compose-dev.yaml up, I also used the same localSetup.sh you used. version: '3' services: localstack: image: localstack/localstack hostname: localstack ports: - "4567-4584:4567-4584" - "${PORT_WEB_UI-8082}:${PORT_WEB_UI-8082}" environment: - SERVICES=s3 - DEBUG=1 - DATA_DIR=${DATA_DIR- } - PORT_WEB_UI=${PORT_WEB_UI- } - DOCKER_HOST=unix:///var/run/docker.sock volumes: - "${TMPDIR:-/tmp/localstack}:/tmp/localstack" - "/var/run/docker.sock:/var/run/docker.sock" networks: - backend sample-app: image: "sample-app/sample-app:latest" networks: - backend links: - localstack depends_on: - "localstack" networks: backend: driver: 'bridge'
unknown
d2808
train
It works for me: "no-underscore-dangle": ["error", { allow: ["_id"] }] If you are using the @typescript-eslint/naming-convention rule, you may also need to add this: "@typescript-eslint/naming-convention": [ "error", { selector: ["variable"], format: ["strictCamelCase", "PascalCase", "UPPER_CASE"], filter: { regex: "^_id$", match: false, }, }, ],
unknown
d2809
train
You should looks to Celery project. It allows to schedule delayed function calls (after response generated). So you can read that file to a variable and schedule task to remove that file. # views.py def some_view(request): zipdir = condown(idx)#condown creates zip file in zipdir logging.info(os.path.basename(zipdir)) response = HttpResponseNotFound() if os.path.exists(zipdir): with open(zipdir, 'rb') as fh: response = HttpResponse(fh.read(), content_type="multipart/form-data") response['Content-Disposition'] = 'inline; filename=download.zip' task_delete_zipfile.delay(zipdir) return response # tasks.py import os from webapp.celery import app @app.task def task_delete_zipfile(filePath): if os.path.exists(filePath): os.remove(filePath) else: print("Can not delete the file as it doesn't exists")
unknown
d2810
train
myAudio.source = "Sounds/Impact_1.mp3"; This is incorrect. You want the src property: myAudio.src = 'Sounds/Impact_1.mp3'; Additionally, you don't need .load() before .play() like that. And, ensure that you're calling .play() on a user action so that you don't run afoul of autoplay policies.
unknown
d2811
train
It looks like valid json. Use jq. Replace my echo with your curl: $ echo '{"@odata.context":"h...","value":"_tlCijtcSZG0CNTl_cnFxmkz2rjbQtSJQ"}' \ | jq -r .value _tlCijtcSZG0CNTl_cnFxmkz2rjbQtSJQ In other words, just do curl ... | jq -r .value > /output/path
unknown
d2812
train
Even though you are developing locally, the assets still need to be delivered securely and pass the CORS policy to load in a-frame. Your scene is most likely throwing some errors related to not being able to load that file securely, timing out in the process. Ideally you would want to load that gltf file via the asset management system and then reference it in an entity below. Helps avoid scene timeouts and crashing as well. I don't know the Flask environment, but you will want a way to declare a specific asset or a local folder of assets for the app to host(again locally) to be pulled from in your a-scene. Otherwise you may want to look into other local hosting environments like the popular and free XAMPP. A-Frame Asset Management System : https://aframe.io/docs/1.3.0/core/asset-management-system.html#sidebar CORS docs : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS CORS Simplified breakdown exmaple : https://riptutorial.com/aframe/example/30904/cross-origin-resource-sharing--cors- Free Local hosting development application (XAMPP) : https://www.apachefriends.org/index.html Asset Management Test Example : <!DOCTYPE html> <html> <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script> <!-- we import arjs version without NFT but with marker + location based support --> <script src="https://raw.githack.com/AR-js-org/AR.js/master/aframe/build/aframe-ar.js"></script> <body style="margin : 0px; overflow: hidden;"> <a-scene embedded arjs> <!-- Asset management system. --> <a-assets timeout="10000"> <a-asset-item id="sceneAsset" src="file:///C:/Users/user123/Desktop/scene.gltf" preload="auto" crossorigin="anonymous"></a-asset-item> </a-assets> <a-marker preset="hiro"> <a-entity position="0 0 0" scale="0.05 0.05 0.05" gltf-model="#sceneAsset" ></a-entity> </a-marker> <a-entity camera></a-entity> </a-scene> </body> </html>
unknown
d2813
train
The following code will present the UIImagePickerController in a way that resembles the screenshot given. UIImagePickerController *eImagePickerController = [[UIImagePickerController alloc] init]; eImagePickerController.delegate = self; eImagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; eImagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto; eImagePickerController.cameraDevice= UIImagePickerControllerCameraDeviceRear; eImagePickerController.showsCameraControls = YES; eImagePickerController.navigationBarHidden = NO; [self presentViewController:eImagePickerController animated:YES completion:nil]; Just make sure that you hide the status bar or it will be displayed in the UIImagePickerController as well.
unknown
d2814
train
If you can guarantee that the input XML will only have single digits, you could achieve this with simple look-up tables, which return the name of either the cardinal number (one, two, three, etc) or the ordinal form of the number (Half, Third, Fourth, etc) <ref:cardinals> <ref:cardinal>One</ref:cardinal> <ref:cardinal>Two</ref:cardinal> <ref:cardinal>Three</ref:cardinal> ... and so on... </ref:cardinals> <ref:ordinals> <ref:ordinal>Half</ref:ordinal> <ref:ordinal>Third</ref:ordinal> ... and so on ... </ref:ordinals> (Where the ref namespace would have to be declared at the top of the XSLT) To look up values in these look-up tables, you could set up a variable which references the XSLT document itself <xsl:variable name="cardinals" select="document('')/*/ref:cardinals"/> <xsl:value-of select="$cardinals/ref:cardinal[position() = $numerator]"/> (Where $numerator is a variable containing the top half of the fraction) Here is a full XSLT document which can cope with all single digit fractions <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ref="http://stackoverflow.com/users/723763/abdul-muqtadir"> <xsl:output method="xml" indent="yes"/> <ref:cardinals> <ref:cardinal>One</ref:cardinal> <ref:cardinal>Two</ref:cardinal> <ref:cardinal>Three</ref:cardinal> <ref:cardinal>Four</ref:cardinal> <ref:cardinal>Five</ref:cardinal> <ref:cardinal>Six</ref:cardinal> <ref:cardinal>Seven</ref:cardinal> <ref:cardinal>Eight</ref:cardinal> <ref:cardinal>Nine</ref:cardinal> </ref:cardinals> <ref:ordinals> <ref:ordinal>Half</ref:ordinal> <ref:ordinal>Third</ref:ordinal> <ref:ordinal>Quarter</ref:ordinal> <ref:ordinal>Fifth</ref:ordinal> <ref:ordinal>Sixth</ref:ordinal> <ref:ordinal>Seventh</ref:ordinal> <ref:ordinal>Eigth</ref:ordinal> <ref:ordinal>Ninth</ref:ordinal> </ref:ordinals> <xsl:variable name="cardinals" select="document('')/*/ref:cardinals"/> <xsl:variable name="ordinals" select="document('')/*/ref:ordinals"/> <xsl:template match="Fraction"> <xsl:variable name="numerator" select="number(substring-before(., '/'))"/> <xsl:variable name="denominater" select="number(substring-after(., '/'))"/> <xsl:copy> <xsl:value-of select="$cardinals/ref:cardinal[position() = $numerator]"/> <xsl:text> </xsl:text> <xsl:value-of select="$ordinals/ref:ordinal[position() = $denominater - 1]"/> <xsl:if test="$numerator != 1">s</xsl:if> </xsl:copy> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> When applied to your input XML, the following XML is returned <Fractions> <Fraction>One Third</Fraction> <Fraction>One Half</Fraction> </Fractions> Note that you may have to look at handling plurals better. For example, if you had 3/2 as a fraction, the above solution returns Three Halfs, and not Three Halves. A: If there's only a few, then use templates like these: <xsl:template match="Fraction/text()[.='1/2']">half</xsl:template> <xsl:template match="Fraction/text()[.='1/3']">one-third</xsl:template> etc..
unknown
d2815
train
Cake means the result of the successfully called promise, in this example they probably want to mean the cake result, and the cake result is a "black forest". You could write it like this jeffBuysCake3('black forest') .then(result => console.log(result)) .catch(error => console.log(error)) and the result is going to be "black forest cake", if the promise function was like this const jeffBuysCake3 = cakeType => { return new Promise((resolve, reject) => { setTimeout(()=> { if (cakeType === 'black forest') { resolve('Strawberry cake !') //Callback function } else { reject('No cake for you today') //Callback function } }, 1000) }) } the result is going to be "Strawberry Cake !", while if there was an error it would print out "No cake for you today". In case you don't know how promises work, when we supply .then it means if the promise resolved (successfully) then give me back the result. If it couldn't be resolved, then catch the error which then we use .catch.
unknown
d2816
train
You cannot browse any files on iOS device. You have to update your app to say what type of files it can edit/read. Then another app would have to share that file. When that source app shares a file type tht your app accept, it would listed as a destination the user can select. A: Asper my knowledge because of the security reasons we can't access all files. You can access albums,images,contacts ... but not documents. I think try to load the png files of the resume in Photos and try to access it.
unknown
d2817
train
I'm not quite sure what you're looking for, but I think sweep function fits well for your goal. Try: result <- sweep(test, c(2,3,4), colSums(test), FUN='/') Where test is the array created by @user2068776. dimnames are preserved. dimnames(result) $a [1] "a1" "a2" $b [1] "b1" "b2" $c [1] "c1" "c2" $d [1] "d1" "d2" A: It is really ambiguous to answer question without a reproducible example. I answer this question, because producing an example here is interesting. dat <- array(rnorm(16*10*15*39)) dim(dat) <- c(16,10,15,39) dimnames(dat) <- lapply(c(16,10,15,39), function(x) paste('a',sample(1:1000,x,rep=F),sep='')) dat2 <- apply(dat, c(2,3,4), function(x){x/sum(x)}) identical(dimnames(dat2) ,dimnames(dat)) [1] TRUE I get the same dimanmes for dat and dat2. So surely I miss something here. A: I can't reproduce this behavior using a non-casted array. Could you provide a reproducable example of what your dataframe/array actually looks like? Otherwise it is difficult to find out where the problem is. Here is the code I used for testing this: # example a <- c(1,2,11,22) b <- c(3,4,33,44) c <- c(5,6,55,66) d <- c(7,8,77,88) test <- array(c(a,b,c,d), c(2,2,2,2), dimnames=list( a=c("a1","a2"), b=c("b1","b2"), c=c("c1","c2"), d=c("d1","d2") ) ) dimnames(test) names(dimnames(test)) # apply test2 <- apply(test, c(2,3,4), function(x){ entry <- sum(x) }) dimnames(test2) names(dimnames(test2)) Sorry for the comment "diguised" as an answer. I am new to SO and as it seems you need a higher rep to post comments. Edit: Your dimnames might get lost, because for whatever reason the function your defined produces unnamed results. You can try saving x/sum(x) as an object (like I did) and then naming that object inside your function. I skipped the last part, because for me there were no missing names / dimnames
unknown
d2818
train
Here should be a complete code public static String[][] CPUship(String[][]board3){ int rowGenerate; int colGenerate; for (int CPUships = 0; CPUships < 6; CPUships++) { boolean valid2=false; while (!valid2){ //instead of valid = false " rowGenerate = (int) ( 9* Math.random() + 0); colGenerate = (int) ( 9* Math.random() + 0); if (!board3[rowGenerate][colGenerate].equalsIgnoreCase ("#")){ board3[rowGenerate][colGenerate]="#"; valid2=true; } //removed the valid2=false, it does not "reset" automatically //removed the CPUships++ ... already done by the for loop } } return board3; } or use break instead of the valid boolean public static String[][] CPUship(String[][]board3){ int rowGenerate; int colGenerate; for (int CPUships = 0; CPUships < 6; CPUships++) { while (true){ //instead of valid = false " rowGenerate = (int) ( 9* Math.random() + 0); colGenerate = (int) ( 9* Math.random() + 0); if (!board3[rowGenerate][colGenerate].equalsIgnoreCase ("#")){ board3[rowGenerate][colGenerate]="#"; break; } //removed the valid2=false, it does not "reset" automatically //removed the CPUships++ ... already done by the for loop } } return board3; }
unknown
d2819
train
There might be different reasons for OOM exception. One reason readily comes to my mind is is setting AUTO_READ option on the channel. The default value is true. you can get more information about this in stack overflow posts here and here If setting AUTO_READ option doesn't help, netty provides an option to check if any message to ChannelHandler is not released. Please set -Dio.netty.leakDetectionLevel=ADVANCED JVM option in the system properties. A: This happens because the client is writing faster than what the server can process. This ends up filling up the client buffer (memory) and eventual crash. The solution is to adjust the client send rate based on the server. One way to achieve this is that the server periodically reports the reading rate to the client and the client adjusts the write speed based on that.
unknown
d2820
train
server.js const express = require('express') const mongoose = require('mongoose') const Shipment= require('./models/shipment') const app = express() mongoose.connect('mongodb://localhost/myFirstDatabase ', { useNewUrlParser: true, useUnifiedTopology: true }) app.set('view engine', 'ejs') app.use(express.urlencoded({ extended:false })) app.get('/', async (req,res) => { const data= await Shipment.find() res.render('index', { data: data}) }) app.listen(process.env.PORT || 5000); index.ejs below is part of your ejs file <table class="table table-striped table-hover"> <thead> <tr> <th>#</th> <th>Customer</th> <th>Address</th> <th>City</th> <th>State</th> <th>Zip</th> <th>Phone</th> <th>Status</th> </tr> </thead> <tbody> <% data.forEach((e, index)=> { %> <tr> <td><%= index %></td> <td><%= e.Customer %></td> <td><%= e.Address %></td> <td><%= e.City %></td> <td><%= e.State %></td> <td><%= e.Zip %></td> <td><%= e.Phone %></td> <td><%= e.Status %></td> </tr> <% }) %> </tbody> </table>
unknown
d2821
train
The expression mentioned in the question works. Just make sure that you have included the "example.nzb" file within your project and also make sure that you restart the REPL.
unknown
d2822
train
CS = Case Sensitive CI= Case Insensitive you need to have one or the other. AS = Accent sensitive, AI = Accent Insensitive. These codes specify how to sort. You need to select CI or CS and AS or AI https://msdn.microsoft.com/en-us/library/ms143726.aspx A: You can use the SQL replace function to remove instances of '_CI' in your query. For example, the code below will remove _CI and _AI from collation names. You can use similar logic to remove the other characters you don't want. SELECT name, REPLACE(REPLACE(name, '_CI',''), '_AI','') description FROM sys.fn_helpcollations(); A: Here you are a customable solution to exlude any falg you want from a table of names (for example collation names). If you want you can prepare a procedure or function to do it easier in your batches. -- declaration of the input table declare @input as table (name varchar(max)); -- declaration of the output table declare @output as table (name varchar(max)); -- declaration of the table with flags you want to exclude from names declare @exclude as table (flag varchar(max)); -- put flags you want to exclude into array insert into @exclude (flag) values ('CI'), ('CS'), ('AI'), ('AS'); -- put some collations into input table (as example for testing) insert into @input select distinct name from sys.fn_helpcollations(); -- now we need to loop over all value in exclude table declare @excludeCursor as cursor; declare @flag as varchar(max); set @excludeCursor = cursor for select flag from @exclude; open @excludeCursor; fetch next from @excludeCursor INTO @flag; while @@FETCH_STATUS = 0 begin update @input set name = replace(name, concat('_', @flag), '') where name like concat('%_', @flag) or name like concat('%_', @flag, '_%') -- The where clause above ensure that you replace exactly the flag added to your exclude table. -- Without this caluse if you want to excldue for example a BIN flag and you have a BIN and BIN2 flags in your names -- then the '2' character from the BIN2 will stay as a part of your collation name. fetch next from @excludeCursor INTO @flag; end close @excludeCursor; deallocate @excludeCursor; -- prepare the output table with distinct values insert into @output select distinct name from @input; -- print the output select * from @output
unknown
d2823
train
Shell expansion does not happen in Dockerfile ENV. Then workaround that you can try is to pass the name during Docker build. Grab the filename during build name and discard the file or you can try --spider for wget to just get the filename. ARG FULLNAME ENV FULLNAME=${FULLNAME} Then pass the full name dynamically during build time. For example docker build --build-args FULLNAME=$(wget -nv https://upload.wikimedia.org/wikipedia/commons/5/54/Golden_Gate_Bridge_0002.jpg 2>&1 |cut -d\" -f2) -t my_image . A: The ENV ... ... syntax is mainly for plaintext content, docker build arguments, or other environment variables. It does not support a subshell like your example. It is also not possible to use RUN export ... and have that variable defined in downstream image layers. The best route may be to write the name to a file in the filesystem and read from that file instead of an environment variable. Or, if an environment variable is crucial, you could set an environment variable from the contents of that file in an ENTRYPOINT script.
unknown
d2824
train
Microsoft has answered this question on this thread as follows: Hi All · Thank you for reaching out. There seems to be an issue with the UI. I will report the issue to the product team and get it addressed. However, as of now, you can follow below steps and use PowerShell to add application to the User Administrator role: * *Install latest Azure AD PowerShell Module. *Run Connect-AzureAD -TenantId Your_B2CTenant.onmicrosoft.com and sign in with Global Administrator account in that tenant. *Run Get-AzureADDirectoryRole cmd and copy the object id of the User Administrator role. *Navigate to Azure AD > Enterprise Applications > Search the app and copy the object id of the app. *Run Add-AzureADDirectoryRoleMember -ObjectId object_ID_copied_in_Step3 -RefObjectId object_ID_copied_in_Step4 cmdlet. To verify, navigate to Azure AD B2C > Roles and Administrators > User Administrator. You should see the application present under this role
unknown
d2825
train
You need to have access to cellid to lat/lng db from mobile network operator to get lat/long of your device. Other way of getting this is by using location apis provided by android, iphone etc. A: Signal Strength could possibly give you an indication of how far from a tower you are, thus improving accuracy What platform are you using?
unknown
d2826
train
You have to rethink the design. addition.py: import Main def addStock(): # The 2 last lines Main.choices() return shipCost A module is a library of reusable components, so they can not depend on some "Main", they must work anyhere, specially on unit tests. Also, you call addition.addStock() in Main.choices(), so there is a circular call. When does it return shipCost? A: First off, your welcome function is not defined(I dont see it if it is) Second, module purchase doesnt exist publicly so it may be the problem
unknown
d2827
train
If you allocate memory on the heap (with new) then it is valid until you explicitly delete it.
unknown
d2828
train
Refer to previous answer, ng-click = "alert('Hello World!')" will work only if $scope points to window.alert i.e $scope.alert = window.alert; But even it creates eval problem so correct syntax must be: HTML <div ng-click = "alert('Hello World!')">Click me</div> Controller $scope.alert = function(arg){ alert(arg); } A: As far as I know, ng-click works only within your $scope. So you would only be able to call functions, defined in your $scope itself. To use alert, you may try accessing the window element, just by using window.alert('Clicked'). EIDT: Thanks to Ibrahim. I forgot. You shouldn't be able to use window.alert, as far as you won't define: $scope.alert = window.alert; In this case, using alert('Clicked') in your ng-clicked directive should work. But at the end, this method would not solve your problem of not touching your controller. A: You can use onclick="alert('Clicked')" for debugging purposes A: As Neeraj mentioned, the accepted answer does not work. Add something like this to your controller to avoid an Illegal Invocation error: $scope.alert = alert.bind(window);
unknown
d2829
train
My preffered method is to upload the video to YouTube and place it on your site using their embed code which is an iframe tag. This provides the benefit of your users using YouTube's bandwidth when they are watching the video rather than yours. Alternatively you could look at using the HTML5 VIDEO tag. http://www.w3schools.com/tags/tag_video.asp A: <video width="300" height="300" controls> <source src="images/K36U21TR.wmv" type="video/wmv"> </video> A: video tag : (Supprot : IE, Firefox, Chrome, Opera, Safari) <video width="320" height="240" controls="controls"> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> <source src="movie.webm" type="video/webm"> </video> embed tag : (Supprot : IE, Firefox, Chrome, Opera, Safari) <embed src="helloworld.swf">
unknown
d2830
train
You should use relative includes from their own file, otherwise, it will run from the current path. To force this you can use __DIR__ and start with a slash plugin.php function process(){ include_once(__DIR__.'/processes/process.php' ); } add_action('wp_ajax_process', 'process' ); process.php include_once(__DIR__.'/../snippets.php'); //here not includes 'snippets.php' Also, you forgot the semicolumn ; in process.php
unknown
d2831
train
Since the modules and dependencies (AMD) are working fine on browser I assume the shims config are correct . That's an incorrect assumption. The problem is that Node.js operates with a set of basic assumptions that are very different from how browsers work. Consider this statement: var foo = "something"; If you execute this at the top of your scope in Node.js, you've created a variable which is local to the file Node is executing. If you really want to make it global, then you have to explicitly shove it into global. Now, put the same statement at the top of the scope of a script you load in a browser with the script element. The same statement creates a global variable. (The variable is global whether or not var is present.) RequireJS' shim configuration is used for scripts that expect the second behavior. They expect a) that anything they declare at the top of their scope is leaked to the global space and b) that anything that has been leaked to the global space by scripts they depend on is available in the global space. Both expectations are almost always false in Node. (It would not be impossible for a module designed for node to manipulate global but that's very rare.) The author of RequireJS explained in this issue report that he does not see it advisable for RequireJS to try to replicate the browser behavior in Node. I agree with him. If you want to run front-end code in the back-end you should replace those modules that need shim in the browser with modules that are designed to run in Node.
unknown
d2832
train
This type of formatting is tricky. You need to pay attention to the white spaces when the parse=TRUE is used. To format the text you need proceed in two steps of pasting. Let's create a simple reproducible example: ggData <- data.frame(x=rnorm(100), y=rnorm(100) ) I recommend you to store the text AND the correlation value R outside of the ggplot function for readability of the code: textPart1 <- "paste(italic(R), \" =\")" # check the ?annotate example for \" =\" corVal <- round(cor(ggData$x, ggData$y, use = "complete.obs"), 3) The trick is to paste the two variables with the sep="~" instead of the white space. ggplot(ggData, aes(x = x, y = y) ) + geom_point(alpha = 0.4) + annotate("text", x = 2, y = 1.5, label = paste(textPart1, corVal, sep="~"), size = 4 , parse=TRUE)
unknown
d2833
train
You just pass the function as a value. E.g.: let apply_twice f x = f (f x) should do what you expect. We can try it out by testing on the command line: utop # apply_twice ((+) 1) 100 - : int = 102 The (+) 1 term is the function that adds one to a number (you could also write it as (fun x -> 1 + x)). Also remember that a function in OCaml does not need to be evaluated with all its parameters. If you evaluate apply_twice only with the function you receive a new function that can be evaluated on a number: utop # let add_two = apply_twice ((+) 1) ;; val add_two : int -> int = <fun> utop # add_two 1000;; - : int = 1002 A: To provide a better understanding: In OCaml, functions are first-class values. Just like int is a value, 'a -> 'a -> 'a is a value (I suppose you are familiar with function signatures). So, how do you implement a function that returns a function? Well, let's rephrase it: As functions = values in OCaml, we could phrase your question in three different forms: [1] a function that returns a function [2] a function that returns a value [3] a value that returns a value Note that those are all equivalent; I just changed terms. [2] is probably the most intuitive one for you. First, let's look at how OCaml evaluates functions (concrete example): let sum x y = x + y (val sum: int -> int -> int = <fun>) f takes in two int's and returns an int (Intuitively speaking, a functional value is a value, that can evaluate further if you provide values). This is the reason you can do stuff like this: let partial_sum = sum 2 (int -> int = <fun>) let total_sum = partial_sum 3 (equivalent to: let total_sum y = 3 + y) (int = 5) partial_sum is a function, that takes in only one int and returns another int. So we already provided one argument of the function, now one is still missing, so it's still a functional value. If that is still not clear, look into it more. (Hint: f x = x is equivalent to f = fun x -> x) Let's come back to your question. The simplest function, that returns a function is the function itself: let f x = x (val f:'a -> 'a = <fun>) f ('a -> 'a = <fun>) let f x = x Calling f without arguments returns f itself. Say you wanted to concatenate two functions, so f o g, or f(g(x)): let g x = (* do something *) (val g: 'a -> 'b) let f x = (* do something *) (val f: 'a -> 'b) let f_g f g x = f (g x) (val f_g: ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>) ('a -> 'b): that's f, ('c -> 'a): that's g, c: that's x. Exercise: Think about why the particular signatures have to be like that. Because let f_g f g x = f (g x) is equivalent to let f_g = fun f -> fun g -> fun x -> f (g x), and we do not provide the argument x, we have created a function concatenation. Play around with providing partial arguments, look at the signature, and there will be nothing magical about functions returning functions; or: functions returning values.
unknown
d2834
train
The error was caused that capacity was 0 value (which might not allow from math divide), if your expected result is 0 when capacity is 0 from occupancy/capacity AVG((COALESCE(occupancy / NULLIF(capacity,0), 0) * 100)) Edit You can try to use CASE WHEN expression to judge the value whether zero then return NULL AVG(CASE WHEN capacity <> 0 AND occupancy <> 0 THEN ((occupancy::decimal/capacity * 1.0) * 100) END) If you want to show all of columns you can try to use the window function. SELECT *,AVG(CASE WHEN capacity <> 0 AND occupancy <> 0 THEN ((occupancy::decimal/capacity * 1.0) * 100) END) OVER(PARTITION BY id) FROM occu_cap NOTE If your occupancy or capacity is not a type of a float-point number we need to CAST that as a float-point number before doing AVG sqlfiddle
unknown
d2835
train
I have only made some improvements in regards to the views, I haven't looked at the models. * *First you should change from the generic generic.View to generic.CreateView since you are creating stuff. *When deriving from generic.CreateView you can move out the template_name and context from the functions and put them in the class instead, since they stay the same for both the GET and POST operations. *Then you don't need to user the render functions, you can just call the super that should handle the render for you. *And lastly you can create a mixin that handles the logic in the user creation, as it's largely the same. With the suggestions above it should look something like this. You might need to tweak it, I haven't been able to test it fully. from extra_views import CreateWithInlinesView, InlineFormSet class ClientCompanyMixin(object): def create_user(self, form_user, form_second, type): # get data for auth and login email = form_user.cleaned_data["email"] password_raw = form_user.cleaned_data["password1"] # add user_type = client/company instance_user = form_user.save(commit=False) instance_user.user_type = type instance_user.save() instance = form_second.save(commit=False) user = authenticate(email=email, password=password_raw) return instance, user class UserInline(InlineFormSet): model = User class ClientFormView(CreateWithInlinesView, ClientCompanyMixin): template_name = "users/registration/form_client.html" model = Client inlines = [UserInline] def get_context_data(self, **kwargs): context = super(ClientFormView, self).get_context_data(**kwargs) context["form_user"] = UserForm context["form_client"] = ClientForm return context def post(self, request, *args, **kwargs): form_user = UserForm(request.POST) form_client = ClientForm(request.POST) if form_user.is_valid() and form_client.is_valid(): instance_client, user = self.create_user(form_user, form_client, "cl") if user is not None: # add the user in related user field instance_client.user = user instance_client.save() login(request, user) return redirect("main:home") return super(ClientFormView, self).post(request, *args, **kwargs) class CompanyFormView(CreateWithInlinesView, ClientCompanyMixin): template_name = "users/registration/form_company.html" model = Company inlines = [UserInline] def get_context_data(self, **kwargs): context = super(CompanyFormView, self).get_context_data(**kwargs) context["form_user"] = UserForm context["form_company"] = CompanyForm return context def post(self, request, *args, **kwargs): form_user = UserForm(request.POST) form_company = CompanyForm(request.POST) if form_user.is_valid() and form_company.is_valid(): instance_company, user = self.create_user(form_user, form_company, "comp") if user is not None: # add the user in related user field instance_company.user = user instance_company.save() login(request, user) return redirect("main:home") return super(CompanyFormView, self).post(request, *args, **kwargs)
unknown
d2836
train
Here you can find pre-release builds using MinGW 4.7. http://releases.qt-project.org/digia/5.0.1/latest/ They work well with the MinGW builds distributed here: http://sourceforge.net/projects/mingwbuilds/ The Qt builds come with Qt Creator, so you can install it and should be good to go after setting up your kits. A: You can find binaries here: http://qt-project.org/forums/viewthread/23002/ But then you ought to reconfigure installation manual or you may use this utility. Some guy from Digia promised MinGW builds by the end of January, so you can wait instead.
unknown
d2837
train
"Z" is kind of a unique case for DateTimes. The literal "Z" is actually part of the ISO 8601 DateTime standard for UTC times. let x = new Date(); let gmtZone = x.toGMTString(); console.log(gmtZone)
unknown
d2838
train
On real device, you can't see these folders if it's not rooted. see this question. If you want to write files in your app directory, then your code is OK. You can check that it is there in the same way you created it - from your application: File myFile = new File(getFilesDir() + "/test1.txt"); if (myFile.exists()) { //Good! }
unknown
d2839
train
<script type="text/javascript"> window.fbAsyncInit = function() { FB.init({appId: 'your apikey', status: true, cookie: true, xfbml: true}); FB_RequireFeatures(["CanvasUtil"], function(){ FB.XdComm.Server.init("xd_receiver.htm"); FB.CanvasClient.startTimerToSizeToContent(); }); FB.Canvas.setAutoResize(true,500); }; (function() { var e = document.createElement('script'); e.async = true; e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; document.getElementById('fb-root').appendChild(e); }()); </script> A: FB.Canvas.setAutoResize function will be removed on January 1st, 2012 as announced in this blog post. Please use FB.Canvas.setAutoGrow instead. You can read more about here. FB.Canvas.setAutoGrow (Working perfect!) Note: this method is only enabled when Canvas Height is set to "Settable (Default: 800px)" in the Developer App. Starts or stops a timer which will grow your iframe to fit the content every few milliseconds. Default timeout is 100ms. Examples This function is useful if you know your content will change size, but you don't know when. There will be a slight delay, so if you know when your content changes size, you should call setSize yourself (and save your user's CPU cycles). window.fbAsyncInit = function() { FB.Canvas.setAutoGrow(); } If you ever need to stop the timer, just pass false. FB.Canvas.setAutoGrow(false); If you want the timer to run at a different interval, you can do that too. FB.Canvas.setAutoGrow(91); // Paul's favourite number Note: If there is only 1 parameter and it is a number, it is assumed to be the interval. A: You cant do that with PHP SDk (i think) You should use the magic javascript provided by Facebook in order to resize according to the contents : <div id="FB_HiddenIFrameContainer" style="display:none; position:absolute; left:-100px; top:-100px; width:0px; height: 0px;"> </div> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script> <script type="text/javascript"> FB_RequireFeatures(["CanvasUtil"], function(){ FB.XdComm.Server.init("xd_receiver.htm"); FB.CanvasClient.startTimerToSizeToContent(); }); </script> http://developers.facebook.com/docs/reference/oldjavascript/FB.CanvasClient.startTimerToSizeToContent A: The solution with FB_HiddenIFrameContainer doesn't work for me. Try http://fbforce.blogspot.com/2011/01/how-to-use-fbcanvassetautoresize.html. This works. <body style="overflow: hidden"> <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.Canvas.setAutoResize(); }; (function() { var e = document.createElement('script'); e.async = true; e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; document.getElementById('fb-root').appendChild(e); }()); </script> <div style="height:2000px; width:500px; background:blue;"> test page </div> </body>
unknown
d2840
train
See here or here on how to delete by query. In Elasticsearch 2.*, you might find the Delete by Query plugin useful. A: Deleting "types" is no longer directly supported in ES 2.x A better plan is to have rolling indexes, that way deleting indexes older than 7 days becomes very easy. Take the example of logstash, it creates an index for every day. You can then create an alias for logstash so that it queries all indexes. And then when it comes time to delete old data you can simply remove the entire index with: DELETE logstash-2015-12-16
unknown
d2841
train
For starters, the difference between static and instance variables is that, only ONE static variable exists for all the instances of the class, whereas an instance variable exists for EVERY instance of the class. Now, when you are talking about methods, in most cases you need to make a method static when you are trying to call it from another static method (such as main). In general this practice is wrong for OOP, and chances are you should rethink the way the program is structured. If you could provide more details about the code you use to call these methods, I would be able to help you with more details on how to fix this. EDIT: In light of the new info you provided: 1) I believe that bmrMain,BMRMain and Calculations can all be merged into one class. The constructor of the new class should be adjusted to read input (as well as getters and setters for each variable for added flexibility - optional) 2) Regarding the calculation of the bmr part, there are many ways to tackle this, so I will go ahead and suggest the one that is best in my opinion. Add a Button with a text "Click to calculate" or something similar, and implement an ActionListener. The action Listener will in turn call (whenever the button is clicked) the method that calculates everything, and finally it will change the text on the JLabel. sample code for the action Listener: JButton button = new JButton("Text Button"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Call the methods for the calculation // bmr and tdee are temporary variables to store the results from the methods //handle them properly, or remove them if not needed (I just wrote a sample) int bmr = calcBMR(...); //pass the correct variables as arguments here int tdee; if(userHasPickedTDEE) { tdee = calcTDEE(...); } //and here label.setText(....); } }); These 2 steps will take care of your "static" problem. I recommend that you do some research on event-driven programming And here is some extra and more in-depth reading on Action Listeners If you need further help, or clarifications let me know :) EDIT2: In general, yes it is a good practice to separate classes in order to keep the code manageable. But in this case I think it is a bit superfluous to create a new class just for 2 methods. Nevertheless if you would like to keep the current structure, the way to fix the "static" is: 1) remove static from the 2 calculation methods. 2)line 332 should be Calculations c = new Calculations(); bmrValue = c.calcBMR(userAge, userGender, userHeight, userWeight); FINAL_EDIT: Well, these questions can easily be transferred to a thread of their own. But here is a useful link from a quick google search I just did, that will help demistify the static keyword: Static keyword in Java A: My thumb rule for using static variables goes somewhat like this: * *Do not use static *When it is needed to use static refer to (1) For most cases, the above thumb rule works. But then, we have standard idioms popularized by JDK, apache-commons libraries. Looking into them you find that: * *It is OK to have utility classes that contain all static methods. *It is OK to create constants using static fields in classes. Though, for this using Enum might be a better choice. *It is OK to one off utility functions that work on the same class into the class. As for the restructuring the code goes, you should be looking at who owns the data. In this case, both the methods from Calculations class looks to be using data from the other class. Move the methods into the other class. The only reason for existence of Calculations class should be that if you are using the methods from multiple other classes which are not related. If they are related, you try to model their relationship and see where these methods go. A: I use static whenever my class is just used to call those methods (i.e. my main method calls the static methods to set variables in the main class, etc). I believe that is the "utility" class that KDM mentioned. A small example of when I use static or utility classes: class Utility { public static int add(int a, int b) { // You would, of course, put something besides simple addition here return a + b; } } class Main { public static void main(String[] args) { int a = 2, b = 3; int sum = Utility.add(a, b); System.out.println(sum); } } On the other hand, if you have a class that is closer to an actual object, with properties of its own, stay away from static. If you use static, then each instance of the class which you want to be separate objects will end up with same values. Based on the name and functionality of your class, it appears you have a utility class. Static should be fine, but it may not be necessary. Hypothetically, though, if you wanted to use this class with multiple "people" class instances for which to calculate the BMR (where each instance is unique), then I would put calcBMR() in a person class and make it non-static so that each person has their own calcBMR(). Edit: Maybe this will help too: Instance -> Instantiate: new Calculations().instanceMethod(); Static -> Class itself, the class's "state": Calculations.staticMethod(); A: If you think in terms of, do I want instance methods or static methods, you're going to be lost. Java isn't method-oriented, it's object-oriented. So for your functionality, decide whether you want an object or a pure function (where pure function means no dependencies and no side-effects, it's strictly a function that given this returns that). It might be good to model this as an object, since you have information describing some aspect of the User and it may make sense to keep it together: public class User { private int age; private String gender; // todo: use an Enum private double height; private double weight; private String activityLevel; // todo: use an Enum public User(int age, String gender, double height, double weight, String activityLevel) { this.age = age; this.gender = gender; this.height = height; this.weight = weight; this.activityLevel = activityLevel; } public double calculateBmr() { int offset = gender.equals("M") ? 5 : -161; return (int) (Math.round((10 * weight) + (6.25 * height) - (5 * age) + offset)); } } etc. This way we don't have to preface the variables with "user", they're all placed together in one object. Objects are an organizational scheme for collecting related information, the instance methods are functions that use the object's information. The alternative route is to create a utility class: public final class UserCalcUtil { private UserCalcUtil() {} // no point instantiating this public static int calculateBmr(String gender, double height, double weight, int age) { int offset = gender.equals("M") ? 5 : -161; return (int) (Math.round((10 * weight) + (6.25 * height) - (5 * age) + offset)); } } Here you're keeping track of the user data separately, and passing it in to the static method when you want to calculate something. The utility class is a dumping ground for separate static methods (which you can think of as functions). Whether you want to use objects or utility classes depends on how you want to organize your data and do calculations on it. Packing the data for a User together with the methods that act on that data may be more convenient if you always do the calculations on the individual objects, or moving the calculations into a utility class might make sense if there are multiple unrelated classes that you want to do calculations for. Since Java has more support for object-oriented constructs it often makes sense to take the object approach. And you can use static methods, but avoid static variables for anything but constants (public static final, with a type that's immutable).
unknown
d2842
train
Since last two years I have been using this divider code below. It working well for all platforms. To fix your issue, provide your code. Widget commonDividerWidget(Color color) { return Divider( thickness: 1.0, color: color, ); }
unknown
d2843
train
Try this code setInterval(function(){ reloadIFrame2(); }, 5000); function reloadIFrame2() { var elements = document.getElementsByClassName("idcw"); for (var i = 0, len = elements.length; i < len; i++) { elements[i].src = elements[i].src; } } <iframe class="idcw" src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt="></iframe> <iframe class="idcw" src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt="></iframe> <iframe class="idcw" src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt="></iframe> <iframe class="idcw" src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt="></iframe> Run this fiddle http://phpfiddle.org/main/code/asn7-zfvq
unknown
d2844
train
When you do Debug->Attach to Process you'll see that VS displays a list of processes and along with them it displays the types of code that you can debug which are running in those processes. To get this information VS queries the various installed debug engines. So when we get queried we go and inspect a bunch of processes to see what's going on. If it's a 32 bit process life is easy - we can use various APIs to enumerate the modules and try and figure out if there's a Python interpreter in the process. If it's a 64-bit process life is a little tougher because we're running inside of VS and it's a 32-bit process. We can't use the APIs from a 32-bit to a 64-bit process so instead we spawn a helper process to do the work. It sounds like this helper process is somehow becoming a zombie on your system. It'd be great if you could attach VS to it and send any stack traces back in a bug. But we should also provide some defense in depth and timeout if the helper process isn't responding. Finally killing it should generally be safe, it's not doing anything stateful, and we'll start a new one when we need it. If you never use Debug->Attach to Process for Python debugging there's probably a trivial file update to our .pkgdef file which I could track down and post which would make this problem go away entirely.
unknown
d2845
train
Use filter_var functions. // url filter_var($url, FILTER_VALIDATE_URL) // email filter_var('[email protected]', FILTER_VALIDATE_EMAIL) A: Except in some very particular cases you should never 'sanitize' input - only ever validate it. (Except in the very particular cases) the only time you change the representation of data is where it leaves your PHP - and the method should be appropriate to where the data is going (e.g. htmlentities(), urlencode(), mysql_real_escape_string()....). (the filter functions referenced in other posts validate input - they don't change its representation)
unknown
d2846
train
I can't figure out what you think is wrong with your approach, but here is the code I was using to test with: class Program { static void Main(string[] args) { RAMDirectory dir = new RAMDirectory(); IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer()); AddDocument(writer, "John Doe", "NY"); AddDocument(writer, "John Foo", "New Jersey"); AddDocument(writer, "XYZ", "NY"); writer.Commit(); BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term("Name", "john")), BooleanClause.Occur.SHOULD); query.Add(new TermQuery(new Term("Location", "NY")), BooleanClause.Occur.SHOULD); IndexReader reader = writer.GetReader(); IndexSearcher searcher = new IndexSearcher(reader); var hits = searcher.Search(query, null, 10); for (int i = 0; i < hits.totalHits; i++) { Document doc = searcher.Doc(hits.scoreDocs[i].doc); var explain = searcher.Explain(query, hits.scoreDocs[i].doc); Console.WriteLine("{0} - {1} - {2}", hits.scoreDocs[i].score, doc.ToString(), explain.ToString()); } } private static void AddDocument(IndexWriter writer, string name, string address) { Document objDocument = new Document(); Field objName = new Field("Name", name, Field.Store.YES, Field.Index.ANALYZED); Field objLocation = new Field("Location", address, Field.Store.YES, Field.Index.NOT_ANALYZED); objLocation.SetBoost(2f); objDocument.Add(objName); objDocument.Add(objLocation); writer.AddDocument(objDocument); } } This code does return the results in the order you wish. In fact it returns them in that order for this set if you exclude the boost. I'm not an expert on Lucene scoring, but I believe this is because you are matching "NY" exactly for "XYZ, NY", and the "John" query is a partial match. You can read the details printed out via the Explain class. A: Have you tried MultiFieldQueryParser?
unknown
d2847
train
This sounds like a problem that can be solved using a writable store. Stores (if you don't know) are essentially storage for things such as variables and other data which apply across all your components (if imported from your stores file). The documentation can be found here: https://svelte.dev/tutorial/writable-stores
unknown
d2848
train
In the ctor: Populating m_w: up to (m_N-1) for (int i(0); i < m_N; ++i) { m_pt.push_back(QPointF(mesureList[i]->getX(), mesureList[i]->getY())); m_w.push_back(mesureList[i]->getAngle()); } Later: accessing m_w[m_N], beyond the end of the vector for (i = m_N; i >= 0; --i) { sum = m_w[i]; for (j = i+1; j < m_N; j++) sum -= LU[i][j]*m_w[j]; m_w[i] = sum / LU[i][i]; } A: Something inside the constructor Interpolation::Interopolation() or the destructor Interpolation::~Interpolation() is writing beyond the size of the object.
unknown
d2849
train
My recommendation would be to use an MSI based installer instead of trying to roll your own using Windows Forms. Look into using the Windows Installer XML (WiX) toolset which is a popular free open source toolset for creating installers. Using MSI has many advantages, in particular it makes it fairly difficult to mix installer logic and UI (kind of like falling into the pit of success) and so making an unattended installer suitable for running on a remote machine is a piece of cake. If you are already committed to your current installation method then you need to work on separating your UI and logic to the point where you can run an installation without showing any UI - its difficult to give any specific advice on how to do this without a more concrete example.
unknown
d2850
train
".pipe(cmq())" should be before ".pipe(gulp.dest())" gulp.task('sass', function() { return gulp.src("./*.scss") .pipe(sass()) .pipe(cmq()) .pipe(gulp.dest(".css/")) .pipe(reload({stream: true})) });
unknown
d2851
train
It sounds like you're talking about a library that will be used by other applications. You can't (thankfully!) modify the standard library this way - otherwise just importing a package could have incredibly broad and potentially disastrous side-effects. If you want to apply some special hardware-specific optimizations to the standard library, for use by other people in a broad range of projects, your best bet is to make your changes to the standard library and submit a patch.
unknown
d2852
train
I was able to devise a sort of hacky solution since the import system throws an ImportError if something is imported and sys.modules has a None in it: class hide_module_2: def __enter__(self): self.module_2 = sys.modules.get('module_2') sys.modules['module_2'] = None def __exit__(self, exc_type, exc_value, traceback): if self.module_2 is None: sys.modules.pop('module_2') else: sys.modules['module_2'] = self.module_2 with hide_module_2(): import module_1
unknown
d2853
train
Thanks @molbdnilo I made a stupid mistake that I forgot to include the SFML header in "block.h" #include <SFML/Graphics.hpp> Now problem solved! Thanks for all advices. I am new to C++ projects, please feel free to speak out all my bad practices in the code. Very helpful!
unknown
d2854
train
This is why the warning exists: When the value is specified as undefined, React has no way of knowing if you intended to render a component with an empty value or if you intended for the component to be uncontrolled. It is a source of bugs. You could do a null/undefined check, before passing the value to the input. a source A: @Kokovin Vladislav is right. To put this in code, you can do this in all your input values: <TextInput // your other code value={user.firstName || ''} /> That is, if you don't find the value of first name, then give it an empty value.
unknown
d2855
train
Before calling the view, print_r($report['savings']); With above code are you getting any result?? A: just try it <?php if(isset($savings) && count($savings) > 0) { foreach($savings as $vs) { echo $vs['username']; echo $vs['stype']; echo $vs['inst_name']; echo $vs['acc_name']; echo $vs['smonth']; echo $vs['syear']; } } ?> Good Luck ['} A: Use this in your view <?php foreach($savings->result() as $vs) { echo $vs->username; echo $vs->stype; echo $vs->inst_name; echo $vs->acc_name; echo $vs->smonth; echo $vs->syear; } ?>
unknown
d2856
train
* *Brackets (free) *VBSEdit (paid) *Systemscripter (paid)
unknown
d2857
train
* *1.0 / (pow(x,2) + pow(y,2)) *sqrt(pow(b,2) - 4*a*c) See pow() and sqrt() functions manual. You can also write x*x instead of pow(x, 2). Both will have the exact same result and performance (the compiler knows what the pow function does and how to optimize it). (For commenters) GCC outputs the exact same assembler code for both of these functions: double pow2_a(double x) { return pow(x, 2); } double pow2_b(double x) { return x * X; } Assembler: fldl 4(%esp) fmul %st(0), %st ret
unknown
d2858
train
Try: df = df1.merge(df2, on='ID', how='left') df[['NAME', 'EMAIL', 'ROLE-ID']] It gives the following: Screenshot A: You did not exactly state what should happen if id is not found or is avail multiple times this may not be 100% what you want. It will leave the id untouched then.B ut guess otherwise its what you wanted. import pandas as pd import numpy as np df1 = pd.DataFrame([[1,'a'], [7,'b'], [3,'e'], [2,'c']], columns=['id', 'name']) df2 = pd.DataFrame([[1,2], [3,8], [2,10]], columns=['id', 'role']) # collect roles roles = [] for id in df1.loc[:, 'id']: indices = df2.loc[:,'id'] == id if np.sum(indices) == 1: roles.append(df2.loc[indices, 'role'].iloc[0]) else: # take id if role id is not given roles.append(id) # could also be None if not wanted # add role id col df1.loc[:,'role-id'] = roles # delete old id del df1['id'] print(df1) DF1: id name 0 1 a 1 7 b 2 3 e 3 2 c DF2: id role 0 1 2 1 3 8 2 2 10 Output name role-id 0 a 2 1 b 7 2 e 8 3 c 10 A: Seems like a merge problem pd.merge(df2, df1, how='inner')
unknown
d2859
train
CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing or concurrent.futures.ProcessPoolExecutor.
unknown
d2860
train
You are really close my friend. Just a little tweak and you will get what you are looking for Category.select('parents_categories.name as parent_category, categories.name as category').joins(:parent).as_json(except: :id) Note if you have belongs_to :parent, parent cannot be named as selected key so we need to change it to parent_category
unknown
d2861
train
To add to other answers, consider that any function exposed through a shared object or DLL (depending on platform) can be overridden at run-time. Linux provides the LD_PRELOAD environment variable, which can specify a shared object to load after all others, which can be used to override arbitrary function definitions. It's actually about the best way to provide a "mock object" for unit-testing purposes, since it is not really invasive. However, unlike other forms of monkey-patching, be aware that a change like this is global. You can't specify one particular call to be different, without impacting other calls. A: Considering the "guerilla third-party library use" aspect of monkey-patching, C++ offers a number of facilities: * *const_cast lets you work around zealous const declarations. *#define private public prior to header inclusion lets you access private members. *subclassing and use Parent::protected_field lets you access protected members. *you can redefine a number of things at link time. If the third party content you're working around is provided already compiled, though, most of the things feasible in dynamic languages isn't as easy, and often isn't possible at all. A: I suppose it depends what you want to do. If you've already linked your program, you're gonna have a hard time replacing anything (short of actually changing the instructions in memory, which might be a stretch as well). However, before this happens, there are options. If you have a dynamically linked program, you can alter the way the linker operates (e.g. LD_LIBRARY_PATH environment variable) and have it link something else than the intended library. Have a look at valgrind for example, which replaces (among alot of other magic stuff it's dealing with) the standard memory allocation mechanisms. A: Not portably so, and due to the dangers for larger projects you better have good reason. The Preprocessor is probably the best candidate, due to it's ignorance of the language itself. It can be used to rename attributes, methods and other symbol names - but the replacement is global at least for a single #include or sequence of code. I've used that before to beat "library diamonds" into submission - Library A and B both importing an OS library S, but in different ways so that some symbols of S would be identically named but different. (namespaces were out of the question, for they'd have much more far-reaching consequences). Similary, you can replace symbol names with compatible-but-superior classes. e.g. in VC, #import generates an import library that uses _bstr_t as type adapter. In one project I've successfully replaced these _bstr_t uses with a compatible-enough class that interoperated better with other code, just be #define'ing _bstr_t as my replacement class for the #import. Patching the Virtual Method Table - either replacing the entire VMT or individual methods - is somethign else I've come across. It requires good understanding of how your compiler implements VMTs. I wouldn't do that in a real life project, because it depends on compiler internals, and you don't get any warning when thigns have changed. It's a fun exercise to learn about the implementation details of C++, though. One application would be switching at runtime from an initializer/loader stub to a full - or even data-dependent - implementation. Generating code on the fly is common in certain scenarios, such as forwarding/filtering COM Interface calls or mapping OS Window Handles to library objects. I'm not sure if this is still "monkey-patching", as it isn't really toying with the language itself. A: As monkey patching refers to dynamically changing code, I can't imagine how this could be implemented in C++...
unknown
d2862
train
EclEmma - is Eclipse plugin based on Java Code Coverage Library called JaCoCo that performs analysis of Java bytecode. Description of coverage counters provided by JaCoCo can be found in its documentation. As you can see in it - JaCoCo and hence EclEmma provide * *instructions coverage *branch coverage *line coverage *and cyclomatic complexity Don't know what you call node coverage, and I'm guessing that what you call edge coverage - is branch coverage. Regarding condition coverage - Wikipedia says if (a && b) { /* ... */ } condition coverage can be satisfied by two tests a=true, b=false, a=false, b=true what seems a bit weird in case of Java where && is a short-circuit operator - second test can't trigger retrieval of value of "b". Regarding path coverage - JaCoCo does not provide it, what can be demonstrated using following example: void fun(boolean a, boolean b) { if (a) { /* ... */ } if (b) { /* ... */ } } Not counting exception there are 4 paths thru this method. And so for full path coverage 4 tests will be required - a = true, b = true, a = true, b = false, a = false, b = true and a = false, b = false. However JaCoCo and EclEmma would report 100% coverage after just 2 tests - a = true, b = true and a = false, b = false.
unknown
d2863
train
SELECT * FROM Playlist WHERE NOT EXISTS ( SELECT NULL FROM PlaylistTrack INNER JOIN Track USING (TrackId) INNER JOIN Genre USING (GenreId) WHERE Playlist.PlaylistId = PlaylistTrack.PlaylistId AND Genre.Name IN ('Latin', 'Rock', 'Pop') )
unknown
d2864
train
<video autoplay loop> <source src="movie.mp4" type="video/mp4" /> <source src="movie.ogg" type="video/ogg" /> </video> You mean this? A: You’ll need to mute the video (adding the muted attribute on the <video> tag) as videos with sound don’t autoplay in all browsers. Then also add the attributes autoplay and playsinline. Also you can use the videoEnd event and call play() to ensure it loops.
unknown
d2865
train
I've found you just need to pipe echo "no" into avdmanager create then start the emulator. Something like this: echo "y" | sdkmanager "system-images;android-31;google_apis_playstore;x86_64" echo "no" | avdmanager create avd -n MyEmulator -k "system-images;android-31;google_apis_playstore;x86_64" emulator64-arm -avd MyEmulator -noaudio -no-window -accel on sleep 300 # wait for avd to start # or detect when booting is finished See also: How to create Android Virtual Device with command line and avdmanager? You'll also need to wait for the avd to start. You can either sleep for a reasonably long period of time or try something more sophisticated like polling adb -e shell getprop init.svc.bootanim to see if the output says "stopped" -- example reference.
unknown
d2866
train
It redirects you to outlook mostly because you click on mailto: link. You can connect to smtp server to send e-mail via php. Here you will find how to do it You don't need FTP which is file transfer protocol you need connection to SMTP which is Simple Mail Transfer Protocol. Also check PHP manual If you doesn't want to use PHP and you want send it via your client for example outlook you need do something like this: <form enctype="text/plain" method="get" action="mailto:[email protected]"> Your First Name: <input type="text" name="first_name"><br> Your Last Name: <input type="text" name="last_name"><br> Comments: <textarea rows="5" cols="30" name="comments"></textarea> <input type="submit" value="Send"> </form> Code from this page. However, I don't recommend this solution. Connecting to SMTP via PHP is better.
unknown
d2867
train
In this line request_uri: 'locations/show' in place of 'locations/show' try using '/locations/show.json' instead. Hope this one helps!
unknown
d2868
train
Here: void add(std::vector<T> new_vec) { vv.push_back(&new_vec); } You store a pointer to the local argument new_vec in vv. That local copy will only live till the method returns. Hence the pointers in the vector are useless. Dereferencing them later invokes undefined behavior. If you really want to store pointers you should pass a pointer (or reference) to add. Though, you should rather use smart pointers.
unknown
d2869
train
for all statements you should do: ... if(event.target.currentFrame == 1 || event.target.currentFrame == 30) { gotoAndPlay(31); } ....
unknown
d2870
train
When you call via callSIP, you make a call to a 3rd-party PBX. If the PBX allows calling to phone numbers, yes, you can do it, but you need to find out what format the PBX accepts. In most cases, you can specify the number in the To field in the username part of the SIP address, for example: number_to_call@domain. Alternatively, you can call a phone number directly through Voximplant via the callPSTN() method.
unknown
d2871
train
Hope this will help you! Paste the following code in your activity. ArrayList<Object> imagearraylist = (ArrayList<Object>) getIntent().getSerializableExtra("Arraylist"); Reference: How to pass ArrayList<CustomeObject> from one activity to another? A: Use Interface Like Mentioned In Link Passing Data Between Fragments to Activity Or You Can Simply Use Public static ArrayList<String> imagearraylist; (Passing Huge Arraylist Through Intent May Leads To Crash) A: For this, you have to use interface public interface arrayInterface { public void onSetArray(ArrayList<T>); } Implement this interface in your activity public class YrActivity extends Activity implements arrayInterface.OnFragmentInteractionListener { private ArrayList<T> allData; @override public void arrayInterface(ArrayList<T> data) { allData = data; } } Then you have to send the data with listner arrayInterface listener = (arrayInterface) activity; listener.onSetArray(allData) And its done
unknown
d2872
train
You can find everything you need to know in the Asset Pipeline Rails Guide. A: Caching is a related, but separate topic. The purpose of compiling assets includes the combining and minimizing of assets, e.g. javascript that is all on 1 line with 1 letter variables, as opposed to the originals which are used in development mode and let you debug there using the original source code.
unknown
d2873
train
Try the following, using regex_search the if/else can be written in shorter and cleaner format. "{{ developmenthosts if ( ansible_hostname|regex_search('dev|tst|test|eng') ) else productionhosts }}" Example: --- - name: Sample playbook connection: local # gather_facts: false hosts: localhost vars: developmenthosts: MYDEVHOST productionhosts: MYPRODHOST tasks: - debug: msg: "{{ ansible_hostname }}" - debug: msg: "{{ developmenthosts if ( ansible_hostname |regex_search('dev|tst|test|eng') ) else productionhosts }}"
unknown
d2874
train
Your setup is complete with a wsdl file and a couple of xsd files. The reason you're having that problem is because the link 'http://localhost/DService/AllService.svc?xsd=xsd0'. is broken. The solution is to search the folder that has the xsd files for AllService . To make it easier, place all the files in a single folder. Next is that you copy the absolute path to the file that contain the search phrase AllService, replace the localhost url with the absolute path to the file. Run the command again and watch it work. Note: Do not remove the url as this is essential in making your complete proxy.
unknown
d2875
train
Can you try this? SELECT [id] ,[timestamp] ,[current load count] ,LAG([current load count]) OVER (ORDER BY [timestamp] ASC, [id]) AS [previous load count] FROM [table] The LAG function can be used to access data from a previous row in the same result set without the use of a self-join. It is available after SQL Server 2012. In the example I added ordering by id, too - in case you have records with same date, but you can remove it if you like. A: If you need exactly one day before, consider a join: select t.*, tprev.load_count as prev_load_count from t left join t tprev on tprev.timestamp = dateadd(day, -1, t.timestamp); (Note: If the timestamp has a time component, you will need to convert to a date.) lag() gives you the data from the previous row. If you know you have no gaps, then these are equivalent. However, if there are gaps, then this returns NULL on the days after the gap. That appears to be what you are asking for. You can incorporate either this or lag() into an update: update t set prev_load_count = tprev.load_count from t join t tprev on tprev.timestamp = dateadd(day, -1, t.timestamp);
unknown
d2876
train
In the default style of Button, there is a ContentPresenter control to display the content of Button, it uses HorizontalContentAlignment property to control the horizontal alignment of the control's content. The default value is Center. So if you want to put the image in the right of Button, you can change the HorizontalContentAlignment to Right. <Button HorizontalContentAlignment="Right" BorderThickness="0" Background="Black" Grid.Column="0" Width="400" > <Image Height="20" Source="ms-appx:///Assets/LockScreenLogo.scale-200.png" Width="20" /> </Button>
unknown
d2877
train
I dont claim to be an expert on REST but here is what I would probably do. In your domain model, if a resource cannot exist without a user then its perfectly OK to model URL calls such as GET /user/{userId}/resource //Gets all resources of a user On the other hand if resources can exist without users then this link on stackoverflow gives a nice way of modelling such calls. RESTful Many-to-Many possible? Another thing which we did for one of our projects was that, we had the linking table (UserResource table(id,userId,resourceId) ,and we had a unique ID for that and had something like GET /userResource/{userResourceId} GET /userResource //Retrieve all the resources user has access to If security is your concern , there are links on StackOverflow on how to integrate Security with Rest calls. Ideally such logic should be handled on the serverside. You typically do not want to put that logic into the REST url. For example if you get a call for GET /resource //Get all resources Depending on who the user is, you return only that subset of resources he has access to. Bottom Line : Dont build your resources around permissions. Again, I am not an expert. Just my humble views. :-)
unknown
d2878
train
You can use awk or vim macro. awk is really great for such text manipulation awk '{count++; print count " " $2 " "$3;}' data.stat > /tmp/data.stat && mv /tmp/data.stat data.stat A: in Vim: :let i=1 | g/^[^/\t]*\t/s//\= i. "\t"/ | let i=i+1 Reference Update For splitting the first two columns and saving into another file, I recommend using awk as in Tomáš Šíma's answer, specifically: awk '{print $1 "\t" $2;}' data.stat > newfilename.txt If you want to to do everything in Vim: * *Copy the current file to a new one :w newfilename.txt * *Open the newly copied file: :o newfilename.txt * *Split the first two columns of the rest of the line: :%s/^\([^\t]*\)\t\([^\t]*\).*$/\1\t\2/g * *Save your edits of course :w newfilename.txt
unknown
d2879
train
If you aim to manipulate your actions before handle them you can use beforeAction in your controller/component, with something like this: protected function beforeAction($action) { #check a preg_match on a url sanitization pattern, like "[^-A-Za-z0-9+&@#/%?=~_|!:,.;\(\)]", for instance return parent::beforeAction($action); } A: This articles shows how you can make your application secure with SQL Injections, XSS Attacks and CSRF. Hope it helps you. A: Firstly, you can use regular expressions to validate your inputs, you can generalize your inputs in some regular expresions, something like this: $num = $_GET["index"]; if (preg_match("^\d{2}$", $num)) { //allowed } else { //not allowed } Also you can create a white list or black list, if your inputs can be grouped into what is allowed in your application, use a white list, otherwise use a black list. This lists can be sotored in your database or files, something you can easily upgrade without affecting your application. You just have to compare your inputs with that list before proccesing your inputs. My last recommendation is encoding, you should encode your inputs and outputs, because your data from database can contain malicious code, maybe someone put it by mistake or mischief, always think in all possibilities. For this case, I remember the functions htmlspecialchars and utf8_encode, I think you should the first function, also you can analyze your inputs and build your own encoding function. I share the following links: * *http://php.net/manual/es/function.preg-match.php *http://php.net/manual/es/function.utf8-encode.php *http://php.net/manual/es/function.htmlspecialchars.php *https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet I hope this information helps you. Good Luck. A: for all actions in same just add a event handle to onBeginRequest: $this->attachEventHandler('onBeginRequest', [$this, 'purifyParams']); public function purifyParams($event) { $userAgent = $this->getRequest()->getUserAgent(); $isIE = preg_match('/(msie)[ \/]([\w.]+)/i', $userAgent, $version); if (!empty($isIE) && (int) $version[2] < 11) { $purifier = new CHtmlPurifier(); $_GET = array_map(function ($param) use ($purifier) { return $purifier->purify($param); }, $_GET); } }
unknown
d2880
train
Fixed the problem. I needed to set the Label's AutoSize property to true.
unknown
d2881
train
According to the documentation you can use options to define the type of loading you want. I believe it will override your default value defined in your relationship Useful links Joined Loads Select Loads Lazy Load A: So, basically, if you are using lazy=' select', lazy load, and want to switch to joinedload to optimize your query, use the following: from sqlalchemy.orm import joinedload # import the joinedload user_list = db.session.query(UserModel).options(joinedload("person")) # running a joinedload which will give you access to all attributes in parent and child class for x in user_list: # now use x.account directly
unknown
d2882
train
Loosely speaking, if the purpose of your method is to retrieve data from the server use GET. e.g. getting information to display on the client. If you are sending data to the server use POST. e.g. sending information to the server to be saved on a database somewhere. There is a limit to the size of data you can send to the server with a GET request. A: The server side GET or POST is used to specify what the server expects to receive in order to accept the request. The client side GET or POST is used to specify what will be sent to the server. These two must match. You cannot send a GET request when server expects a POST and vice-versa. When you are building a server application, it is important to know the appropriate request type to use, which by itself is a whole big different topic which you should research if it is you the one that builds the server side part.
unknown
d2883
train
No, you send the data however you like but keep in mind how you send it will affect how you can retrieve it. Also you aren't sending JSON in your request as .serialize() does not return JSON it returns a text string in standard URL-encoded notation. A: No, you don't need to send it as JSON. You can send it in any other format, but your receiver will need to know how to interpret it. Usually people use JSON or XML since your receiver can easily parse these types of data. You'll need to set the content-type, then you can tell the receiver how to process this content-type.
unknown
d2884
train
Git's merge operation considers exactly three points when doing a merge: the two heads (usually branches) that you want to merge, and the merge base, which is usually the point at which one was forked from the other. When a merge occurs, Git considers the changes computed between each head and the merge base. It then produces a result exactly like the merge base, but with both sets of changes added. In other words: * *If you made a change on one side and not the other, Git will include the change. A change in this case includes the addition, removal, or modification of a file or part of it. *If you made a change to the same location on both sides, Git will produce a conflict. *If you made no changes to a file or part of it, Git will include those portions unchanged. So in your case, you've only added and modified things, so the merge result will include only additions and modifications, not removals. It is possible you'll see a conflict, though.
unknown
d2885
train
Of course jewelsea already answered that question here. Just the topic of the question was little misleading, but it works the same way for TreeTableView.
unknown
d2886
train
To answer your question: To use that code you've got to download the Managed Task Scheduler Wrapper first. Then to make it run with administrative privileges you've got to set the RunLevel to TaskRunLevel.Highest on your TaskDefinition: td.Principal.RunLevel = TaskRunLevel.Highest However like Plutonix says you shouldn't be writing files to the directory of your program (as that's usually located in the restricted %ProgramFiles% folder). Instead, use the %ProgramData% directory. You can get the path to it from your code via Environment.GetFolderPath(): Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) 'Example: Dim ConfigPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "AppName") Dim ImagePath As String = Path.Combine(ConfigPath, "MyImage.png") If Directory.Exists(ConfigPath) = False Then Directory.CreateDirectory(ConfigPath)
unknown
d2887
train
You are making things too complex for yourself. Why do you first find then again find and then update? Simply go with the following flow Update using filter Code Sample: exports.updateToken = async (id, forgotToken) => {//function return User.updateOne({ _id: id }, { resetPasswordToken: forgotToken });//_id:id is a filter while the reset is code to update }
unknown
d2888
train
This isn't really a problem - the different renderers are rendering the report appropriately for their output. The web viewer is optimised for screen-based reading and generally allows more content per page than the PDF viewer does as the PDF viewer is constrained by the paper size that it formats to. Thus you get more pages when rendering for PDF than web; however, the content of the report is exactly the same. The best illustration of this is the Excel renderer - the Excel renderer renders the entire report onto a single worksheet in most cases (for reports with grouping and page breaks set on the group footer it will render each group on its own worksheet). You wouldn't want the Excel renderer to artificially create worksheets to try to paginate your report. It does the appropriate thing which is to include all the data in one big worksheet even though that may be logically thought of as one big "page". The web renderer page length is determined by the InteractiveHeight attribute of the report (in the InteractiveSize property in the Properties pane for the report) but the interactive height is an approximation rather than a fixed page break setting and your page breaks may still not conform to the PDF version even though the InteractiveHeight is set to the same length as your target page length.
unknown
d2889
train
From the $http documentation you can clearly see request parameters: https://docs.angularjs.org/api/ng/service/$http var req = { method: 'POST', url: 'http://example.com', headers: { 'Content-Type': undefined }, data: { test: 'test' } } $http(req).then(function(){...}, function(){...}); So, in your case you need to switch params with data: var req = { url: SupplierURL, method: 'POST', data: Indata, headers: {'Content-Type': 'application/json'} };
unknown
d2890
train
Get a tool like Firebug for Firefox and learn to use it. It makes finding issues like this simple. The answer is clear, once you have the right tool: the gradient, which is applied to the body element, does not extend all the way down because the body element does not go the full height of the browser. Add: html, body { height: 100%; } and it will be fixed.
unknown
d2891
train
Generics are made for this: class Foo { bar = this.createDynamicFunction((param: string) => { return "string" + param; }); baz = this.createDynamicFunction((param: number) => { return 1 + param; }); createDynamicFunction<Type>(fn: (param: Type) => Type) { return (param : Type) => fn(param); } } const foo = new Foo() //console.log(foo.baz(2)) // => 3 console.log(foo.bar('baz')) // => barbaz console.log(foo.baz(2)) // => 3 You create a generic function, for which the type can be anything. And you can define your overall function type based on that type Playground Link
unknown
d2892
train
My first thought would be to profile the application on the machines you're seeing the leak with something like Red Gate's Memory Profiler. It'll be a lot more reliable than attempting to guess what the leak might be. As for chosing the right technology, if all your machines will have .NET 3.5 installed you might want to consider migrating to WCF (primarily Named Pipes) for your inter-process communication. Check this SO post for more detail...
unknown
d2893
train
my problem is an error 415, i don´t know why is saying the payload is not supported In your Angular client side code, we can find that you set {headers: new HttpHeaders({'Content-Type': 'json'})}, which cause the issue. You can set Content-Type with application/json, like below. this.httpClient .post( config.Urlsite + "Utilizador/register", this.utilizador, { headers: new HttpHeaders({ "Content-Type": "application/json" }) } ) .subscribe( resultado => { console.log(resultado); }, casoErro => { console.log(casoErro); } ); Test Result
unknown
d2894
train
So I just have to create them in a certain order so at the moment they are created, the PID of the process they will send a signal is already created? Right - in particular H4 has to be forked before H3/N3, so that H4 is known to N3. Demo: #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> void handler(int signum, siginfo_t *si, void *u) { printf("%d received signal from %d %s\n", getpid(), si->si_pid, si->si_value.sival_ptr); } main() { // for demo, defer signal delivery until process unmasks the signal sigset_t set, oldset; sigemptyset(&set); sigaddset(&set, SIGRTMIN); sigprocmask(SIG_BLOCK, &set, &oldset); sigaction(SIGRTMIN, &(struct sigaction){ .sa_sigaction = handler, .sa_flags = SA_SIGINFO }, NULL); pid_t P = getpid(); pid_t H1 = fork(); if (H1 < 0) perror("H1"), exit(1); if (H1 == 0) { // use sigqueue() instead of kill(), so can pass sender ID sigqueue(P, SIGRTMIN, (union sigval){.sival_ptr = "H1"}); sigsuspend(&oldset); exit(0); } pid_t H2 = fork(); if (H2 < 0) perror("H2"), exit(1); if (H2 == 0) { pid_t N2 = fork(); if (N2 < 0) perror("N2"), exit(1); if (N2 == 0) { sigqueue(H1, SIGRTMIN, (union sigval){.sival_ptr = "N2"}); sigsuspend(&oldset); exit(0); } sigqueue(N2, SIGRTMIN, (union sigval){.sival_ptr = "H2"}); sigsuspend(&oldset); exit(0); } sigqueue(H2, SIGRTMIN, (union sigval){.sival_ptr = "P"}); pid_t H4 = fork(); if (H4 < 0) perror("H4"), exit(1); if (H4 == 0) { sigqueue(P, SIGRTMIN, (union sigval){.sival_ptr = "H4"}); sigsuspend(&oldset); exit(0); } pid_t H3 = fork(); if (H3 < 0) perror("H3"), exit(1); if (H3 == 0) { pid_t N3 = fork(); if (N3 < 0) perror("N3"), exit(1); if (N3 == 0) { sigqueue(H4, SIGRTMIN, (union sigval){.sival_ptr = "N3"}); sigsuspend(&oldset); exit(0); } sigqueue(N3, SIGRTMIN, (union sigval){.sival_ptr = "H3"}); sigsuspend(&oldset); exit(0); } sigqueue(H3, SIGRTMIN, (union sigval){.sival_ptr = "P"}); sigprocmask(SIG_UNBLOCK, &set, NULL); do ; while (wait(NULL) > 0 || errno != ECHILD); } Example output: 1074 received signal from 1072 P 1072 received signal from 1073 H1 1072 received signal from 1076 H4 1075 received signal from 1074 H2 1073 received signal from 1075 N2 1077 received signal from 1072 P 1076 received signal from 1078 N3 1078 received signal from 1077 H3
unknown
d2895
train
By default Express Checkout is for PayPal accountholder payments; originally you would pair this with some other product for credit card payments (such as collecting the card information on your site and calling PayPal DirectPay or some other card processing partner). PayPal also has several somewhat-similar products that collect the card information on their site (so you don't have to) and do that as well as accountholder payments; these vary in whether they end up giving you access to the credit card information (more flexible, but means you have to safely handle the card information and meet industry regulations, including vetting) or you do not ever see the card, just the money (simpler). This is often called some form of "guest checkout." And eventually PayPal did add a guest checkout option to Express Checkout called "Account Optional." So you can use Express Checkout and get a guest checkout experience. See this link: PayPal: express checkout pay without account So in short you can get this from EC if you configure things for it, although some other PayPal products might be a better fit depending upon your particular requirements.
unknown
d2896
train
No, afraid not. You can either try to find a library / sample code in C/C++/ObjC that will generate a vCard from provided information, or attempt to roll your own. You can find more information about vCard including the specs here; http://www.imc.org/pdi/
unknown
d2897
train
I was able to replicate your problem like this: mysql> create table `index` (url varchar(50)); Query OK, 0 rows affected (0.05 sec) mysql> insert into index(url) values ('http://www.google.com'); ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index(url) values ('http://www.google.com')' at line 1 mysql> insert into `index`(url) values ('http://www.google.com'); Query OK, 1 row affected (0.00 sec) index is a keyword in MySQL. Your life will be easier if you do not use it as a table name. However, if you really want to, you can use it, but then you have to quote it: cursor.execute("""INSERT INTO `index`(url) VALUES(%s)""", (url,)) PS: No need to call url = mdb.escape_string("http://www.google.com") MySQLdb will do that automatically for you when you call cursor.execute("""INSERT INTO index(url) VALUES(%s)""", (url,)) In fact, since cursor.execute calls mdb.escape_string for you, doing it yourself could cause undesired values to be inserted into the database depending on the value of url: In [105]: MySQLdb.escape_string("That's all folks") Out[105]: "That\\'s all folks" In [106]: MySQLdb.escape_string(MySQLdb.escape_string("That's all folks")) Out[106]: "That\\\\\\'s all folks"
unknown
d2898
train
I think the following regexp fit the job. Howevever you don't have to have nested curly bracket (nested curly bracket can't be parsed using regular expression as far as I know) >>> s= "{abc, xyz}, 123, {def, lmn, ijk}, {uvw}, opq" >>> re.findall(r",?\s*(\{.*?\}|[^,]+)",s) ['{abc, xyz}', '123', '{def, lmn, ijk}', '{uvw}', 'opq'] A: given = "{abc,{a:b}, xyz} , 123 , {def, lmn, ijk}, {uvw}, opq" #expected = ["{abc, xyz}", "123", "{def, lmn, ijk}", "{uvw}", "opq"] tmp_l = given.split(',') tmp_l = [i.strip() for i in tmp_l] result_l = [] element = '' count = 0 for i in tmp_l: if i[0] == '{': count += 1 if i[-1] == '}': count -= 1 element = element + i + ',' if count == 0: element = element[0:-1] result_l.append(element) element = '' print str(result_l) this one can handle nested curly bracket, although it seems not so elegant.. A: Does the following not provide you with what you are looking for? import re given = "{abc, xyz}, 123, {def, lmn, ijk}, {uvw}, opq" expected = re.findall(r'(\w+)', given) I ran that in Terminal and got: >>> import re >>> given = "{abc, xyz}, 123, {def, lmn, ijk}, {uvw}, opq" >>> expected = re.findall(r'(\w+)', given) >>> expected ['abc', 'xyz', '123', 'def', 'lmn', 'ijk', 'uvw', 'opq'] A: You can use the below regex to do that. Rest is same as the similar link you provided. given = "{abc, xyz}, 123, {def, lmn, ijk}, {uvw}, opq" regex = r",?\s*(\{.*?\}|[^,]+)" print re.findall(regex,given) OP: ['{abc, xyz}', '123', '{def, lmn, ijk}', '{uvw}', 'opq'] Just import the re module. and do the same as the link says. It will match anything inside the curly braces { } and any string.
unknown
d2899
train
Here's the full code Sub test() ' Open the text file Workbooks.OpenText Filename:="C:\Excel\test.txt" ' Select the range to copy and copy Range("A1", ActiveCell.SpecialCells(xlLastCell)).Select Selection.Copy ' Assign the text to a variable Set my_object = CreateObject("htmlfile") my_var = my_object.ParentWindow.ClipboardData.GetData("text") ' MsgBox (my_var) ' just used for testing Set my_object = Nothing pos_1 = InStr(1, my_var, "How to fix:", vbTextCompare) pos_2 = InStr(pos_1, my_var, "Related Links", vbTextCompare) my_txt = Mid(my_var, pos_1, -1 + pos_2 - pos_1) ' Return to the original file and paste the data Windows("stackoverflow.xls").Activate Range("A1") = my_txt ' Empty the clipboard Application.CutCopyMode = False End Sub This works for me... first, assign the text in the text file to a variable (my_var in the example below) pos_1 = InStr(1, my_var, "How to fix:", vbTextCompare) pos_2 = InStr(pos_1, my_var, "Related Links", vbTextCompare) my_txt = Mid(my_var, pos_1, -1 + pos_2 - pos_1) Range("wherever you want to put it") = my_txt You can also clean up my_txt using the "replace" function if you like. A: This code * *uses a RegExp to remove the linebreaks (replaced with a |) to flatten then string *then extracts each match with a second RegExp change your filepath here c:\temo\test.txt sample input and output at bottom code Sub GetText() Dim objFSO As Object Dim objTF As Object Dim objRegex As Object Dim objRegMC As Object Dim objRegM As Object Dim strIn As String Dim strOut As String Dim lngCnt As Long Set objRegex = CreateObject("vbscript.regexp") Set objFSO = CreateObject("scripting.filesystemobject") Set objts = objFSO.OpenTextFile("c:\temp\test.txt") strIn = objts.readall With objRegex .Pattern = "\r\n" .Global = True .ignorecase = True strOut = .Replace(strIn, "|") .Pattern = "(How to Fix.+?)Related" Set objRegMC = .Execute(strOut) For Each objRegM In objRegMC lngCnt = lngCnt + 1 Cells(lngCnt, 7) = Replace(objRegM.submatches(0), "|", Chr(10)) Next End With End Sub input test How To Fix: To remove this functionality, set the following Registry key settings: Hive: HKEY_LOCAL_MACHINE Path: System\CurrentControlSet\Services... Key: SomeKey Type: DWORD Value: SomeValue Related Links: Some URL otherstuff How To Fix: To remove this functionality, set the following Registry key settings: Hive: HKEY_LOCAL_MACHINE Path: System\CurrentControlSet\Services... Key: SomeKey Type: DWORD Value: SomeValue2 Related Links: Some URL2 output
unknown
d2900
train
DateTime.Now itself may take too much time being calculated, you'll be better off using a System.Diagnostics.Stopwatch. Something like this: Stopwatch stopwatch = new Stopwatch(); int counter = 0; public void OnSensorChanged(SensorEvent e) { if (!stopwatch.IsRunning) { // start the stopwatch stopwatch.Start(); } else { if (stopwatch.ElapsedMiliseconds <= 10) { counter++; return; } } Console.WriteLine(counter); // 10ms passed, restart the stopwatch stopwatch.Restart(); }
unknown