id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23531100
Simply pull out the mute state (if possible) to set the value in the front end, problem being is I don't know if its possible to get a mute state. Anyone any guidance on this, been trying in the CLI and searching for commands which would help me and getting detail about the channel never states if a channel is muted or not. Is it even possible to do this without using developed applications like fop/fop2 and just use the CLI/ARI to do this? Am still relatively new to ARI and asterisk. EDIT: Tried various CLI Commands and it only gives state "Up" "down" when showing channels or channel. A: Please check already developed projects like fop/fop2. Use core "show channels"&'sip show peers"/"iax2 show peers" to get current state.
doc_23531101
My expected result: I can achieve polymorphism with the Interface Segregation Principle. My actual result: No I can't. I am forced to create boilerplate and use the Liskov Substitution Principle (If there is a Worker, there must be a Worker that can't eat, so create an interface for Worker that can eat that extends Worker). I think I misunderstand the Interface Segregation Principle. This is the code that violates the Interface Segregation Principle. public interface IWorker { void work(); void eat(); } class Human implements IWorker { public void work() { System.out.println("Human is working."); } public void eat() { System.out.println("Human is eating."); } } class Robot implements IWorker { public void work() { System.out.println("Robot is working."); } public void eat() { throw new UnsupportedOperationException("Robot cannot eat"); } } I was told to separate the interface into 2. public interface IEatable { void eat(); } interface IWorkable { void work(); } class Human implements IWorkable, IEatable { public void work() { System.out.println("Human is working."); } public void eat() { System.out.println("Human is eating."); } } class Robot implements IWorkable { public void work() { System.out.println("Robot is working."); } } The solution is to use the Liskov Substitution Principle. public interface IWorkable { void work(); } interface IEatable { void eat(); } interface IWorker extends IWorkable { } interface IHumanWorker extends IWorker, IEatable { } A: Your second step looks good, you have split the interface in two more specific interfaces. It does not make sense for a Robot to "eat". (I dont really get the third step) On the caller side you can now work with your abstractions: //Polymorphism List<IWorkable> workers = Arrays.asList(new Robot(), new Human()); //do some work List<IEatable> eaters = Arrays.asList(new Human(), new Human()); //send for lunch break If you want to have both behaviours in the same thing, than your abstraction/design seems to be wrong, since Robots cannot eat by definition (indicated by the code smell of not implemented methods). A Robot is not an IWorker (your first code), because it does not full fill the (full) contract (interface, eat method), no matter how similar it seems to be. A: I'd recommend using abstract classes for that matter instead of interfaces. If you need every Workable to work, then you make the method abstract. If it's only optional that they eat, you don't. An example of that would be: abstract class Workable { protected String name; public Workable(String name) { this.name = name; } protected abstract void work(); public void eat() { System.err.println("\"" + name + "\" can't eat"); } } class Human extends Workable { public Human(String name) { super(name); } @Override public void work() { System.out.println("Human " + name + " is working!"); } @Override public void eat() { System.out.println("Human " + name + " is eating!"); } } class Robot extends Workable { public Robot(String name) { super(name); } public void work() { System.out.println("Robot " + name + " is working!"); } } public class Test { public static void main(String[] args) { Workable[] workers = new Workable[] { new Human("Jerry"), new Robot("XAE12") }; for (Workable worker : workers) { worker.work(); worker.eat(); } } } I'm not sure if I understood your question correctly tho, so please let me know if that helped you.
doc_23531102
var Browser = require("zombie"); var assert = require("assert"); // Load the page from localhost browser = new Browser() browser.visit("http://localhost:3000/", function () { // Fill email, password and submit form browser. fill("email", "zombie@underworld.dead"). fill("password", "eat-the-living"). pressButton("Sign Me Up!", function() { // Form submitted, new page loaded. assert.ok(browser.success); assert.equal(browser.text("title"), "Welcome To Brains Depot"); }) }); but all sort of errors ensued. Specially memory errors after trying to load the 100th item. What am I doing wrong? I wish I could run this every iteration of the loop and also cleaning the resource after every successful try. A: If it were me, I would create a queue of URLs to visit... var urls = ['http://example.com/something', 'http://example.com/somethingElse', /* etc. */] Then, I would create a function that reads from this queue. function runNextJob() { if (!urls.length) { return; // W're done! } var url = urls.pop(); browser.visit(url, function () { // yada yada browser.pressButton('Sign Me Up!', function () { // On next tick, call runJext Job(). It's important that // this is next tick! Otherwise our call stack gets enormous. process.nextTick(runNextJob); } } } To start the cycle, just call runNextJob() once. If you want to run multiple at a time, run that function as many times as you want to have simultaneous jobs. (Say, 4 times for a 4 CPU box, depending on how browser does its work, but you'll want to experiment.)
doc_23531103
id job_type run_dt 1 A 2020-05-25 2 A 2020-05-25 3 A 2020-05-25 4 A 2020-05-25 5 A 2020-05-25 6 A 2020-05-24 7 A 2020-05-24 8 A 2020-05-23 9 B 2020-05-25 10 B 2020-05-25 11 B 2020-05-25 12 B 2020-05-25 13 B 2020-05-25 14 B 2020-05-25 15 B 2020-05-24 16 B 2020-05-24 In my case the number of jobs by type per day varies drastically and some days have a skew. select job_type, run_dt, count(*) from run_schedule group by job_type, run_dt order by job_type; job_type run_dt count A 2020-05-23 1 A 2020-05-25 5 A 2020-05-24 2 B 2020-05-25 6 B 2020-05-24 2 Is there any way in postgres that I can re-distribute the job run dates (run_dt column) so that it's more uniformly distributed? Ideally I would like to see a distribution like the one below, job_type run_dt count A 2020-05-23 3 A 2020-05-25 3 A 2020-05-24 2 B 2020-05-25 3 B 2020-05-24 4 So effectively, I've re-scheduled 2 jobs of type A which were originally scheduled to run on the 25th to the 23rd and 2 jobs of type B to run on the 24th bringing them closer to the average of each job type across those days. A: You could use window functions to get the minimum and maximum date of each job type, along with the total number of records and the rank of each record within the group. Using this information, you can equally spread jobs across dates: select id, job_type, date(min_run_dt + (max_run_dt - min_run_dt + 1) * (rn - 1) / cnt * interval '1 day') run_dt from ( select t.*, min(run_dt) over(partition by job_type) min_run_dt , max(run_dt) over(partition by job_type) max_run_dt, count(*) over(partition by job_type) cnt, row_number() over(partition by job_type order by run_dt) rn from mytable t ) t order by job_type, run_dt For your sample data, this produces: id | job_type | run_dt -: | :------- | :--------- 8 | A | 2020-05-23 6 | A | 2020-05-23 7 | A | 2020-05-23 4 | A | 2020-05-24 1 | A | 2020-05-24 5 | A | 2020-05-24 2 | A | 2020-05-25 3 | A | 2020-05-25 16 | B | 2020-05-24 15 | B | 2020-05-24 11 | B | 2020-05-24 12 | B | 2020-05-24 13 | B | 2020-05-25 14 | B | 2020-05-25 9 | B | 2020-05-25 10 | B | 2020-05-25
doc_23531104
like in C#, in C#: SaveData(txtUsername.value,txtAge.value){ } HOW WE CAN SEND DATA WHICH IS ENTERED FROM UI TO C++ FUNCTION THANKING YOU, A: If your calling SaveData and passing txtUsername.value and txtAge.value as the value in the ui text boxes like: SaveData(txtUsername.value,txtAge.value); You should be able to do something like this to store those values to predefined variables: SaveData(string username, int age) { usernameVar.setValue(username); ageVar.setValue(age); }
doc_23531105
http://localhost:5001/my-app/us-central1/myFunc I would like to either get a whole url or assemble it somehow. The my-app could be in theory read from .firebaserc where the default is specified. However, I am not sure about port or region.
doc_23531106
doc_23531107
In VS2008 something like public Color Foreground {get;set;} the keyword Color would be highlighted because it's a well known and defined struct. In VS2012 the highlighting feature doesn't work for structs anymore. Does anyone else also noticed? Has anyone a solution? I went through all the Color Options and tried everything but I can't get the good old struct highlighting color back. A: It works fine for me, in VS2012: What you're looking for is the User Types (Value types) color in Tools -> Options -> Environment -> Fonts and Colors If that doesn't help, you should check that you don't have an external addin that might be changing the colors... Update - based on your comment - if you're using the Productivity Power Tools you might need to disable the Colorized Parameter Help Option from Tools -> Options -> Productivity Power Tools -> Colorized Parameter Help... Another option is to try to Repair your installation of VS2012 A: I have also run into this problem and I have found the culprit to be the Productivity Power Tools. There is a workaround to get the syntax highlighting for structs to reappear. You have to turn off Colorized Parameter Help in the Productivity Power Tools options and restart Visual Studio. This can be found at Tools > Options > Productivity Power Tools > Colorized Parameter Help Also see this bug report for more information. A: I think I found another solution to this problem, which lets you leave the Colorized Parameter Help feature turned on. In Fonts and Colors, I specified a value for the "Signature Help - User Types(Value Types)" item, and I don't have the problem any more. Note: I also have the Color Theme Editor extension installed - I'm not sure if this plays any part in the effectiveness of the workaround (but I had it installed before as well, so the extension alone didn't fix the problem). Also, someone posted the bug on MS Connect: http://connect.microsoft.com/VisualStudio/feedback/details/770603/text-editor-the-type-color-for-structs-is-black A: I've tried turning off the Colorized Power Tools parameter, uninstall and reinstall Power Tools and "Repair" of Visual Studio, none of which worked. What ended up working was deleting the .suo and .dotSettings files in the same directory as the Solution File (.sln).
doc_23531108
Can anyone comment on the different permissions Windows 2008 might require for an install4j executable when using java 6 compared to java 1.4? FYI Windows 2008 64bit, java 32bit, install4j 32bit thank you A: There are no differences in permission handling between Java 1.4 and Java 6. Permissions in install4j are handled by the "Request privileges" action which is typically located in the "Startup" node of your installer. For installing into C:\Program Files (x86), you need elevated privileges. If your installer works with Java 1.4 and does not work with Java 6, there must be some other error. I would suggest to look at the file .install4j/installation.log for more information.
doc_23531109
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://.......' and same code and services works on my another server and loacalhost .... what can be the reason for this error ? A: This error occurs when the client can't download the remote WSDL. The PHP configuration setting allow_url_fopen must be On in order for the SOAP Client to access the remote WSDL. If that doesn't solve it then it means that your current server is stopping PHP from connecting and loading the WSDL. This could be due to a firewall rule or some other outbound connectivity problem.
doc_23531110
* *appends spaces at the end of the line until at least some column is reached, *if the preceding line also had a comment tailing the code, aligns the comment character, and *inserts the comment character for the mode, followed by one space. In Python one feature is missing to comply with the stringent rules: *at least two spaces must separate code from the trailing comment. How can I configure comment-dwim to leave at least two spaces in python-mode? A: Fiddling with comment-dwim may be holding the wrong end of the stick. For me, M-; automatically inserts two spaces, the '#' character, and a space, following which point is placed. If it's not doing that for you, then you may have reconfigured it somewhere else, possibly accidentally. I suggest an alternative is to have a 'format-on-save' option enabled, which will do this for you without fussing in your .emacs or with customize. (use-package python-black :after python :hook (python-mode . python-black-on-save-mode) :bind ("C-c p C-f" . 'python-black-buffer)) I use black, but any alternative formatter should do the same. I never worry about how my file is formatted, because black fixes it for me automatically. From the docs for black: Black does not format comment contents, but it enforces two spaces between code and a comment on the same line, and a space before the comment text begins.
doc_23531111
when the screen resizes I want the entire menu to resize but the list items just jump to the next line. I have tried width/height as well as max-width/height I have tried using different units % and vh, also tried display block and different positions but I cannot get this to work, I am cannot find where I am going wrong. Any help is greatly appreciated thank you. codePen : http://codepen.io/mikegr/pen/YNYjLJ HTML <div class="ground"> <img src="http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620608/ground_dhn37w.png" /> <!--nav menu--> <ul id="menu"> <li id="home"><a class="current" href="index.html">Home</a></li> <li id="about"><a href="about.html">About</a></li> <li id="audio"><a href="audio.html">Audio</a></li> <li id="art"><a href="design.html">Art</a></li> <li id="threed"><a href="modeling.html">3d</a></li> <li id="coding"><a href="coding.html">Programming</a></li> </ul> </div> CSS .ground { position:fixed; left:0px; bottom:-1%; height:auto; width:100%; background:#999; } ul { list-style: none; } /* nav menu */ #menu { position: absolute; top: 6vh; z-index: 2; width:60%; overflow: hidden; margin: 0 auto; left: 0; right: 0; max-width: 100%; height: auto; } #menu li { float:left; /*--- Make the list go horizontal ---*/ margin:auto; padding-right: 2vh; } #menu li a { display:block; text-indent: -9999px; /*--- Push the text off screen to hide text---*/ } #menu li#home a { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/home_menu_svyjuj.png) no-repeat; width:150px; height: 75px; } #menu li#home a:hover { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/home_menu_hover_g4rwhe.png) no-repeat; } #menu li#home a.current { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/home_menu_hover_g4rwhe.png) no-repeat; cursor:default; /*--- Show pointer instead of hand cursor for the current page ---*/ } /* About */ #menu li#about a { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/about_menu_jcz8yx.png) no-repeat; width:150px; height: 75px; } #menu li#about a:hover { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/about_menu_hover_uurcba.png) no-repeat; } #menu li#about a.current { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/about_menu_hover_uurcba.png) no-repeat; cursor:default; } /* Graphic design */ #menu li#art a { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/art_menu_mbywzq.png) no-repeat; width:150px; height: 75px; } #menu li#art a:hover { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/art_menu_hover_afaypq.png) no-repeat; } #menu li#art a.current { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/art_menu_hover_afaypq.png) no-repeat; cursor:default; } /* Modeling/Animation */ #menu li#threed a{ background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/3d_menu_dptfpv.png) no-repeat; width:150px; height: 75px; } #menu li#threed a:hover { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/3d_menu_hover_pqnxfs.png) no-repeat; } #menu li#threed a.current { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/3d_menu_hover_pqnxfs.png) no-repeat; cursor:default; } /*Programming*/ #menu li#coding a { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620608/programming_hzslwa.png) no-repeat; width:170px; height: 75px; } #menu li#coding a:hover { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620608/programming_hover_crywht.png) no-repeat; } #menu li#coding a.current{ background: url(.http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620608/programming_hover_crywht.png) no-repeat; cursor:default; } /* Audio */ #menu li#audio a { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/audio_vvgdur.png) no-repeat; width:150px; height: 75px; } #menu li#audio a:hover { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/audio_hover_bnrvb0.png) no-repeat; } #menu li#audio a.current { background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/audio_hover_bnrvb0.png) no-repeat; cursor:default; } A: Ok I just fixed it myself, sorry that is typical thing to happen. I just changed the width to vh and the problem was i needed to add background-size: cover; background-repeat: no-repeat; background-position: center center; A: You are setting a width in pixels for the images. That will prevent them from resizing as you would like.
doc_23531112
My basic code skeleton is: child = Fork.new do |child| ## something something something ## loop loop loop ## something something something end child.execute child.wait That follows the sample code I believe but it always returns a very counter-intuitive error: C:/Ruby187/lib/ruby/gems/1.8/gems/fork-1.0.0/lib/fork.rb:237:in `fork': fork() f unction is unimplemented on this machine (NotImplementedError) from C:/Ruby187/lib/ruby/gems/1.8/gems/fork-1.0.0/lib/fork.rb:237:in `ex ecute' I do have the proper gems installed: *** LOCAL GEMS *** addressable (2.2.8) childprocess (0.3.3) ffi (1.0.11) fork (1.0.0) libwebsocket (0.1.4) multi_json (1.3.6) mysql2 (0.3.11 x86-mingw32) net-sftp (2.0.5) net-ssh (2.5.2) net-ssh-gateway (1.1.0) rdiscount (1.6.8) rubyzip (0.9.9) selenium-webdriver (2.24.0) I attempted to use the classes' future/call method combo but that doesn't seem to work for me either. I installed and reinstalled several times to ensure this wasn't an environmental issue. I also tried to work with the win32-process gem but this requires an existing binary from what I can understand, to be called as a subprocess. I really don't want to resort to cygwin but that might be the only way to address it. What has been your experience with this gem? A: you can't "fork" per se in windows, but you can call out to other methods using one of ruby's system calls: http://en.wikibooks.org/wiki/Ruby_Programming/Running_Multiple_Processes or win32-process or some other gem, or the winapi directly.
doc_23531113
A: Sendkeys did the trick Dim numberoftabs as Long Dim numberofdownarrows1 as long numberoftabs = yourvalue numberofdownarrows1 = yourvalue Application.SendKeys "{TAB " & numberoftabs & "}", True Application.SendKeys "{DOWN " & numberofdownarrows1 & "}", True Application.SendKeys "~", True
doc_23531114
<?php //... class Post extends Model { //... public function user() { return $this->belongsTo(User::class); // User model is previously defined } } Now I can get the user (author) info of a specific post: Post::find(1)->user()->username; Of course laravel has to run some DB queries to get the data; and I wanna know what is the query behind this belongsTo() method. A: You cant use the toSql() method to check query will run on laravel illuminate, $sql = Person::query()->with('user')->find(1)->toSql(); dd($sql); A: try use this $result=Post::with('user')->find(1); dd($result); and look the response belongs to is meaning to relation between tables if the relation is one to one use belongsTo and hasOne if the relation is one to many use belongsTo and hasMany
doc_23531115
Android-Audio Streaming From Pc Android: Streaming audio over TCP Sockets Java - Broadcast voice over Java sockets http://eurodev.blogspot.com/2009/09/raw-audio-manipulation-in-android.html Can you help me?? A: since I'm new and cannot comment on your question or ask for clarifications, but just answer it, I'll do my best here. This is how I would try to solve the problem if it was mine: * *record the audio on the android device *send it to the laptop via email/ftp/whatever transport is easier for me *open it in the laptop and send it to the Windows Speech Recognition Api for conversion to text *send it back via email/ftp/whatever transport is easier for me hope it helps. Gustavo.
doc_23531116
from google.colab import files files.upload() fileReader = PyPDF4.PdfFileReader('ITC-1.pdf') s="" for i in range(2, fileReader.numPages): s+=fileReader.getPage(i).extractText() sentences = [] while s.find('.') != -1: index = s.find('.') sentences.append(s[:index]) s = s[index+1:] text_ds = tf.data.TextLineDataset('ITC-1.pdf').filter(lambda x: tf.cast(tf.strings.length(x), bool)) vectorize_layer.adapt(text_ds.batch(1024)) inverse_vocab = vectorize_layer.get_vocabulary() The last line in the code above shows the error. I saw several posts to understand what it means, but none of the solutions seem to work for me. I cannot use my local machine because I would be needing access to GPUs. Please suggest a workaround for this. Thanks! PS: Following the code here https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/text/word2vec.ipynb#scrollTo=haJUNjSB60Kh, the difference is in the way I am reading the file. If there are better ways to do it, pleasee let me know! A: import pdfplumber from tensorflow.keras.layers.experimental import preprocessing import tensorflow as tf f = open('test.txt', 'w') with pdfplumber.open(r'test.pdf') as pdf: for page in pdf.pages: f.write(page.extract_text()) f.close() layer = preprocessing.TextVectorization() text_ds = tf.data.TextLineDataset('test.txt').filter(lambda x: tf.cast(tf.strings.length(x), bool)) layer.adapt(text_ds.batch(1024)) inverse_vocab = layer.get_vocabulary() You could do something like this: * *read pdf using pdfplumber. *Write the pages to a text file. *Then create dataset using that text file.
doc_23531117
I had try !feof(fp), EOF, but it loop infinitely. If i change to fscanf(fp, str, &str) == 1, it can't read anything. Here is the code: void readFile(){ FILE *fp; int i=0, j=1; int* arr; char str[45]; fp = fopen("c:\\Defuzzification.txt","r"); // read mode if (fp == NULL) { perror("Error while opening the file.\n"); exit(EXIT_FAILURE); } arr = (int*)calloc(SIZE, sizeof(int)); while( fscanf(fp, "The different between frame %d and %d :%d", &i, &j, arr) == 1 ){ fscanf(fp, "The different between frame %d and %d :%d", &i, &j, arr); printf("Display The different between frame %d and %d :%d\n", i, j, *arr); i++; j++; } fclose(fp); } while(fscanf(fp, "The different between frame %d and %d :%d", &i, &j, arr) != EOF) =>> loop infinite while( fscanf(fp, "The different between frame %d and %d :%d", &i, &j, arr) == 1 ) =>> read nothing input data: The different between frame 0 and 1 :80 The different between frame 1 and 2 :58.18 The different between frame 2 and 3 :77.59 The different between frame 3 and 4 :71.24 The different between frame 4 and 5 :68.46 The different between frame 5 and 6 :75.81 The different between frame 6 and 7 :41.35 A: In the following statement, fscanf will return 3 if all the input operations are successful. while( fscanf(fp, "The different between frame %d and %d :%d", &i, &j, arr) == 1 ){ Change it to: while( fscanf(fp, "The different between frame %d and %d :%d", &i, &j, arr) == 3 ){ Another thing... You have numbers 80, 58.18, etc. These are floating point numbers not integral number. Shouldn't you be using a floating point format and read it to a floating point variable? float number; while( fscanf(fp, "The different between frame %d and %d :%f", &i, &j, &number) == 3 ){ Update You need to make the following changes: * *In the format string to fscaf, put a space as the first character. This will skip zero or more white spaces, including newline characters. *Use a floating point number to read the last data. Otherwise, the fractional part of the number gets left behind in the input stream and the subsequent read operation fails. *You need to compare the return value of fscanf in the conditional of the while statement to 3. fscanf will return 3 if it is able to successfully read all the three pieces of data. Using the following block of code for reading the data works for me: float number; while( fscanf(fp, " The different between frame %d and %d :%f", &i, &j, &number) == 3 ){ fscanf(fp, " The different between frame %d and %d :%f", &i, &j, &number); printf("Display The different between frame %d and %d :%f\n", i, j, number); i++; j++; }
doc_23531118
But I came to a decision that I don’t need all these amazing features jQuery has, except its AJAX functions (like $.ajax(), $.get(), $.post, getJSON() and load();). Can you recommend a lightweight crossbrowser AJAX library/framework (up to ~10 kb)? A: You can make jQuery smaller by removing the modules you don't need / Just modify the Makefile file. A: If you need to use ONLY ajax features take a look at sajax or custom MooTools. Of course, if you are a "lightweight freak" you can write your own routine for this (should be less than 50 lines) A: MochiKit might fit your needs: http://mochikit.com/ Although lightweight and powerful it might not meet the 10kb requirement (you can trim it down to only the async module) The equivalent methods would be: * *doXHR *doSimpleXMLHttpRequest *evalJSONRequest *loadJSONDoc *sendXMLHttpRequest A: Really lightweight there is SACK (Simple AJAX Code Kit) I don't use myself but it looks really simple edit : I checked, the js file is about 5kB A: MooTools...!! Don't believe the jQuery guys ... ;)
doc_23531119
Before learning to program DPL I just want to verify that I am able to communicate with the printer. I am using the below code to send a "feed form" command but the printer does nothing. I have tried numerous other simple functions as well. Does anyone recall any custom configuration (besides static IP) that they may have had to do to print in this fashion? At this point I have to think this is a printer issue and not my code, as I use it to print to many other devises. I can find very little support/information online for DPL or this bagger so any help would be great. Dim IP As String = "XXX.XX.XXX.XXX" Dim clientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) clientSocket.Connect(New IPEndPoint(IPAddress.Parse(IP), 9100)) Dim Label As String = "<STX>F" clientSocket.Send(Encoding.UTF8.GetBytes(Label)) clientSocket.Close() A: I was able to solve this, not the way I wanted but it works. Instead of sending the raw DPL to the printer I am creating text file and sending that. Besides the creation of the text file I also changed. clientSocket.Send(Encoding.UTF8.GetBytes(Label)) To clientSocket.SendFile("Insert Filepath Here")
doc_23531120
screen where I post to user_resources: import React from 'react'; import { ScrollView,SafeAreaView,StyleSheet, Text, View, FlatList, TouchableOpacity,Button, NativeEventEmitter} from 'react-native'; import {connect} from 'react-redux'; import {fetchResources,searchChanged} from '../actions'; import { addUserResource } from '../actions' import {SearchBar} from 'react-native-elements'; import { MaterialIcons } from '@expo/vector-icons'; import { MaterialCommunityIcons } from '@expo/vector-icons'; class ResourcesScreen extends React.Component { state = { search: '' } componentDidMount = () =>{ this.props.fetchResources(); } FlatListItemSeparator = () => { return ( <View style={{ height: 0.5, width: "100%", backgroundColor: "lightblue", }} /> ); } handlePress(item) { debugger fetch('http://localhost:3000/user_resources', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ resource_id: item.id, user_id: this.props.users.id, name: item.name, description:item.description, link:item.link, }) }) .then(res => res.json()) .then(data2 => { console.log(data2) this.props.addUserResource(data2) console.log(this.props) }) } header = () => { return <View> <Text style={styles.header}>Resources</Text> </View> } onSearchChange = text => { this.setState({search:text}) } render(){ return( <SafeAreaView> <SearchBar placeholderTextColor="white" placeholder="Enter resource name here" onChangeText={this.onSearchChange} value={this.state.search}/> <TouchableOpacity onPress={() => this.props.navigation.navigate('Add A New Resource',{topicId:this.props.route.params.topicId})} style={styles.buttonitem}> <Text style={styles.text}> <MaterialIcons name="add-circle-outline" size={24} color="white"/>Add A New Resource </Text> </TouchableOpacity> <FlatList keyExtractor={(item)=> item.id.toString()} data={this.props.resourceName} ItemSeparatorComponent = { this.FlatListItemSeparator } renderItem={({item}) => { return <TouchableOpacity style={styles.material2}> <Text onPress={() => this.props.navigation.navigate('Add A New Resource',{topicId:item.id})} style={styles.listitem}>{item.name}</Text> <MaterialCommunityIcons name="bookmark-plus" size={50} color="#16a085" backgroundColor='black' onPress={()=>this.handlePress(item)}/> </TouchableOpacity> }} ListHeaderComponent = {this.header}/> </SafeAreaView> ) } } const mapStateToProps = (state) => { return { resourceName: state.resourceReducer.resources, users: state.userReducer, search:state.resourceReducer.searchTerm } } const mapDispatchToProps = (dispatch) => { return { fetchResources: () => dispatch(fetchResources()), addUserResource, searchChanged } } export default connect(mapStateToProps,mapDispatchToProps)(ResourcesScreen) After this I head to the profile page where the user_resources SHOULD be displayed, but aren't import React from 'react'; import { ScrollView,StyleSheet, Text, View, FlatList, TouchableOpacity} from 'react-native'; import {connect} from 'react-redux'; import {SearchBar} from 'react-native-elements'; import { AntDesign } from '@expo/vector-icons'; class Profile extends React.Component{ handleDelete = (id) => { debugger fetch(`http://localhost:3000/user_resources/${id}`, { method: "DELETE", headers: { "Authorization": this.props.users.token } }) .then(r => r.json()) .then((delResource) => { console.log(delResource) this.props.deleteOneFood(delResource) console.log('deleted') this.forceUpdate() }) } render(){ return( <View> {this.props.users.user_resources.map(singleResource=> { return <Text key={singleResource.id}>{singleResource.name}</Text> })} </View> )} } let deleteOneResource = (id) => { return { type: "DELETE_ONE_USER_RESOURCE", payload: id } } const mapDispatchToProps = { deleteOneResource } const mapStateToProps = (state) => { return { users: state.userReducer, } } export default connect(mapStateToProps,mapDispatchToProps)(Profile) I had a flatlist before but thought that may be causing the issues so rendered it another way, still no luck. I tried forceUpdates as well, still no luck. I'm not sure if the issue is coming from my reducer: let userInitialState = { id: 0, username: "", name: '', category: '', token: "", user_resources:[], } let userReducer = (state = userInitialState, action) => { switch(action.type){ case "ADD_USERS": let singleNestedObject = { ...action.users.user, token: action.users.token } return { ...state, username: action.users.user.username, token: action.users.token, id: action.users.user.id, name: action.users.user.name, category: action.users.user.category, user_resources: action.users.user.user_resources } case "ADD_ONE_USER_RESOURCE": let copyOfResources = [...state.user_resources, action.userResources] return { ...state, user_resources: copyOfResources } default: return state } } and it's action export const addUserResource = (resourceInfo) => { return { type: "ADD_ONE_USER_RESOURCE", userResources: resourceInfo } } Please help me find the issue here, I'm losing it.
doc_23531121
and I was wondering what the best way would be to represent an object. The following relations are possible: Class::StaticObject Class::StaticMethod() object.attribute object.method() I was thinking about representing it this way (Pseudocode): interface Primitive Object : Primitive { Lexeme Lefthandside; boolean Staticreference; // true = ::, false is . operator Primitive Righthandside; // Can either be a method or an object, null if no operator is present } Method : Primitive { Lexeme Lefthandside; List of Parameters; // Parameters of the method } Or would you guys go with another approach, I mean you could also use the operators . and :: as Node names and then attach two children to it, but wouldn't that make parsing and recursing the tree harder? Thanks for helping! A: I don't think it is usual to have a lexeme in the AST. They are used in the parse tree, but since the AST is created as part of the semantic analysis, you in fact have much richer information at that point. So instead the nodes in your AST should point to your symbol table. For instance, the symbol table would contain an entry for the object (presumably inserted when you saw the declaration or the first use of the object), as well as an entry for the method (and the entry for the method contains a pointer to the entry for the class of the object. At that point, you can decide whether the object is passed as an explicit parameter to the method (as in python or Ada for instance), or implicitly (C++). So for object.method(), for instance, the AST would contain a node 'methodcall', with one child node 'self' pointing to the object entry, one child node 'method' pointing to the method entry, plus n children node for each of the parameters (pointing to the corresponding entries or to expression nodes).
doc_23531122
I'm talking about the navigation at the side as seen when editing a product. Google fails me when searching for "Magento admin sidebar", "Magento admin left navigation", "Magento admin left column", etc...
doc_23531123
Is there a way to implement edit and delete. I have done it in PHP before. The method I would like to use is create two more columns in the table with edit and delete buttons on each row. Then when the buttons are click it passes the 'id' through the URL and able to edit or delete. Not really sure how to do this in asp.net webforms. Below is my code for the table. Thank you. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField HeaderText="Surgery" DataField="surgery" /> <asp:BoundField HeaderText="PatientID" DataField="patientID" /> <asp:BoundField HeaderText="Location" DataField="location" /> </Columns> SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); conn.Close(); GridView1.DataSource = dt; GridView1.DataBind(); A: The GridView supports those operations. You can add a CommandField which will contain the command buttons or LinkButtons (you can choose the type of button and assign the text of each button). The patientID field should be included in the DataKeyNames property of the GridView, in order to retrieve it when the time comes to update or delete the record in the database. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="patientID" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" > <Columns> <asp:CommandField ShowEditButton="true" ShowCancelButton="true" ShowDeleteButton="true" /> <asp:BoundField HeaderText="Surgery" DataField="surgery" /> ... </Columns> You will then need to handle a few events in code-behind: // The RowEditing event is called when data editing has been requested by the user // The EditIndex property should be set to the row index to enter edit mode protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; BindData(); } // The RowCancelingEdit event is called when editing is canceled by the user // The EditIndex property should be set to -1 to exit edit mode protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; BindData(); } // The RowUpdating event is called when the Update command is selected by the user // The EditIndex property should be set to -1 to exit edit mode protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { int patientID = (int)e.Keys["patientID"] string surgery = (string)e.NewValues["surgery"]; string location = (string)e.NewValues["location"]; // Update here the database record for the selected patientID GridView1.EditIndex = -1; BindData(); } // The RowDeleting event is called when the Delete command is selected by the user protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int patientID = (int)e.Keys["patientID"] // Delete here the database record for the selected patientID BindData(); } Since the data must be bound to the GridView at the end of each of those event handlers, you can do it in a BindData utility function, which should also be called when the page loads initially: private void BindData() { SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); conn.Close(); GridView1.DataSource = dt; GridView1.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindData(); } } A: And Store Procedure is: USE [DemoProjet] GO /****** Object: StoredProcedure [dbo].[Customers_CRUD] Script Date: 11-Jan-17 2:57:38 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[Customers_CRUD] @Action VARCHAR(10) ,@BId INT = NULL ,@Username VARCHAR(50) = NULL ,@Provincename VARCHAR(50) = NULL ,@Cityname VARCHAR(50) = NULL ,@Number VARCHAR(50) = NULL ,@Name VARCHAR(50) = NULL ,@ContentType VARCHAR(50) = NULL ,@Data VARBINARY(MAX) = NULL AS BEGIN SET NOCOUNT ON; --SELECT IF @Action = 'SELECT' BEGIN SELECT BId , Username,Provincename,Cityname,Number,Name,ContentType, Data FROM tblbooking END --INSERT IF @Action = 'INSERT' BEGIN INSERT INTO tblbooking(Username,Provincename,Cityname,Number,Name,ContentType, Data) VALUES (@Username ,@Provincename ,@Cityname ,@Number ,@Name ,@ContentType ,@Data) END --UPDATE IF @Action = 'UPDATE' BEGIN UPDATE tblbooking SET Username = @Username,Provincename = @Provincename,Cityname = @Cityname,Number = @Number,Name = @Name,ContentType = @ContentType,Data = @Data WHERE BId = @BId END --DELETE IF @Action = 'DELETE' BEGIN DELETE FROM tblbooking WHERE BId = @BId END END GO A: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Configuration; using System.Data.SqlClient; namespace FinalYearProject { public partial class MBooking : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { this.BindGrid(); } } private void BindGrid() { string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Customers_CRUD")) { cmd.Parameters.AddWithValue("@Action", "SELECT"); using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = con; sda.SelectCommand = cmd; using (DataTable dt = new DataTable()) { sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); } } } } } protected void Insert(object sender, EventArgs e) { string Username = txtUsername.Text; string Provincename = txtProvinceName.Text; string Cityname = txtCityname.Text; string Number = txtNumber.Text; string Name = txtName.Text; string ContentType = txtContentType.Text; string Data = txtData.Text; string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Customers_CRUD")) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Action", "INSERT"); cmd.Parameters.AddWithValue("@Username", Username); cmd.Parameters.AddWithValue("@Provincename ", Provincename); cmd.Parameters.AddWithValue("@Cityname", Cityname); cmd.Parameters.AddWithValue("@Number", Number); cmd.Parameters.AddWithValue("@Name", Name); cmd.Parameters.AddWithValue("@ContentType", ContentType); //cmd.Parameters.AddWithValue("@Data", Data); cmd.Parameters.AddWithValue("@Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF }; cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } this.BindGrid(); } protected void OnRowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; this.BindGrid(); } protected void OnRowCancelingEdit(object sender, EventArgs e) { GridView1.EditIndex = -1; this.BindGrid(); } protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GridView1.Rows[e.RowIndex]; int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); string Username = (row.FindControl("txtUserName") as TextBox).Text; string Provincename = (row.FindControl("txtProvincename") as TextBox).Text; string Cityname = (row.FindControl("txtCityname") as TextBox).Text; string Number = (row.FindControl("txtNumber") as TextBox).Text; string Name = (row.FindControl("txtName") as TextBox).Text; string ContentType = (row.FindControl("txtContentType") as TextBox).Text; string Data = (row.FindControl("txtData") as TextBox).Text; string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Customers_CRUD")) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Action", "UPDATE"); cmd.Parameters.AddWithValue("@BId", BId); cmd.Parameters.AddWithValue("@Username", Username); cmd.Parameters.AddWithValue("@Provincename ", Provincename); cmd.Parameters.AddWithValue("@Cityname", Cityname); cmd.Parameters.AddWithValue("@Number", Number); cmd.Parameters.AddWithValue("@Name", Name); cmd.Parameters.AddWithValue("@ContentType",ContentType) ; cmd.Parameters.AddWithValue("@Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF }; //cmd.Parameters.AddWithValue("@ContentType", SqlDbType.VarBinary, -1); //cmd.Parameters.AddWithValue("@Data", SqlDbType.VarBinary, -1); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } GridView1.EditIndex = -1; this.BindGrid(); } protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; this.BindGrid(); } protected void OnRowDataBound(object sender, GridViewRowEventArgs e) { //if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex) //{ // (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');"; //} } protected void DownloadFile(object sender, EventArgs e) { int id = int.Parse((sender as LinkButton).CommandArgument); byte[] bytes; string fileName, contentType; string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "select Name, Data, ContentType from tblbooking where BId=@BId"; cmd.Parameters.AddWithValue("@BId",id); cmd.Connection = con; con.Open(); using (SqlDataReader sdr = cmd.ExecuteReader()) { sdr.Read(); bytes = (byte[])sdr["Data"]; contentType = sdr["ContentType"].ToString(); fileName = sdr["Name"].ToString(); } con.Close(); } } Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = contentType; Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); } protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e) { int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Customers_CRUD")) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Action", "DELETE"); cmd.Parameters.AddWithValue("@BId", BId); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } this.BindGrid(); } } } A: And Aspx page is: <%@ Page Title="" Language="C#" MasterPageFile="~/admin.Master" AutoEventWireup="true" CodeBehind="MBooking.aspx.cs" Inherits="FinalYearProject.MBooking" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <style type="text/css"> <%-- body { font-family: Arial; font-size: 10pt; } table { border: 1px solid #ccc; border-collapse: collapse; background-color: #fff; } table th { background-color: #B8DBFD; color: #333; font-weight: bold; } table th, table td { background-color: #B8DBFD; padding: 5px; border: 1px solid #ccc; } table, table table td { border: 3px solid #ccc; } --%> .style1 { width: 184px; } </style> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True" OnPageIndexChanging="OnPageIndexChanging" PageSize="6" DataKeyNames="BId" OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit" OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added." Style="margin:20px 0px 0px 25px;" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" Height="250px" Width="1035px" > <Columns> <asp:TemplateField HeaderText="Username" ItemStyle-Width="120"> <ItemTemplate> <asp:Label ID="lblUsername" runat="server" Text='<%# Eval("Username") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtUsername" style = "Width:100px;" runat="server" Text='<%# Eval("Username") %>'></asp:TextBox> </EditItemTemplate> <ItemStyle Width="120px"></ItemStyle> </asp:TemplateField> <asp:TemplateField HeaderText="ProvinceName" ItemStyle-Width="120"> <ItemTemplate> <asp:Label ID="lblProvinceName" runat="server" Text='<%# Eval("Provincename") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtProvinceName" style = "Width:100px;" runat="server" Text='<%# Eval("Provincename") %>'></asp:TextBox> </EditItemTemplate> <ItemStyle Width="120px"></ItemStyle> </asp:TemplateField> <asp:TemplateField HeaderText="CityName" ItemStyle-Width="120"> <ItemTemplate> <asp:Label ID="lblCityname" runat="server" Text='<%# Eval("Cityname") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtCityname" style = "Width:100px;" runat="server" Text='<%# Eval("Cityname") %>'></asp:TextBox> </EditItemTemplate> <ItemStyle Width="120px"></ItemStyle> </asp:TemplateField><asp:TemplateField HeaderText="Number" ItemStyle-Width="120"> <ItemTemplate> <asp:Label ID="lblNumber" runat="server" Text='<%# Eval("Number") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtNumber" style = "Width:100px;" runat="server" Text='<%# Eval("Number") %>'></asp:TextBox> </EditItemTemplate> <ItemStyle Width="120px"></ItemStyle> </asp:TemplateField><asp:TemplateField HeaderText="Name" ItemStyle-Width="120"> <ItemTemplate> <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtName" style = "Width:100px;" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox> </EditItemTemplate> <ItemStyle Width="120px"></ItemStyle> </asp:TemplateField><asp:TemplateField HeaderText="ContentType" ItemStyle-Width="120"> <ItemTemplate> <asp:Label ID="lblContentType" runat="server" Text='<%# Eval("ContentType") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtContentType" style = "Width:100px;" runat="server" Text='<%# Eval("ContentType") %>'></asp:TextBox> </EditItemTemplate> <ItemStyle Width="120px"></ItemStyle> </asp:TemplateField><asp:TemplateField HeaderText="Data" ItemStyle-Width="120"> <ItemTemplate> <asp:Label ID="lblData" runat="server" Text='<%# Eval("Data") %>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtData" style = "Width:100px;" runat="server" Text='<%# Eval("Data") %>'></asp:TextBox> </EditItemTemplate> <ItemStyle Width="120px"></ItemStyle> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile" CommandArgument='<%# Eval("BId") %>'></asp:LinkButton> </ItemTemplate></asp:TemplateField> <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="100" > <ItemStyle Width="100px"></ItemStyle> </asp:CommandField> </Columns> <FooterStyle BackColor="#99CCCC" ForeColor="#003399" /> <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" /> <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Center" Font-Bold="True" Font-Italic="True" Font-Underline="True" Width="20px" /> <RowStyle BackColor="White" ForeColor="#003399" /> <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" /> <SortedAscendingCellStyle BackColor="#EDF6F6" /> <SortedAscendingHeaderStyle BackColor="#0D4AC4" /> <SortedDescendingCellStyle BackColor="#D6DFDF" /> <SortedDescendingHeaderStyle BackColor="#002876" /> </asp:GridView> <br /> <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse; margin:10px 0px 0px 25px;"> <tr> <td style="width: 100px; background-color:#003399; color:#CCCCFF;"> <b> Username:</b><br /> <asp:TextBox ID="txtUsername" runat="server" Width="120" /> </td> <td style="width: 100px;background-color:#003399; color:#CCCCFF;"> <b> Provincename:</b><br /> <asp:TextBox ID="txtProvinceName" runat="server" Width="120" /> </td> <td style="width: 100px;background-color:#003399; color:#CCCCFF;"> <b>Cityname:</b><br /> <asp:TextBox ID="txtCityname" runat="server" Width="120" /> </td> <td style="width: 100px;background-color:#003399; color:#CCCCFF;"> <b> Number:</b><br /> <asp:TextBox ID="txtNumber" runat="server" Width="120" /> </td> <td style="width: 100px;background-color:#003399; color:#CCCCFF;"> <b> Name:</b><br /> <asp:TextBox ID="txtName" runat="server" Width="120" /> </td> <td style="width: 100px;background-color:#003399; color:#CCCCFF;"> <b> ContentType:</b><br /> <asp:TextBox ID="txtContentType" runat="server" Width="120" /> </td> <td style="width: 100px;background-color:#003399; color:#CCCCFF;"> <b>Data:</b><br /> <asp:TextBox ID="txtData" runat="server" Width="120" /> </td> <td style="background-color:#003399; color:#CCCCFF;" class="style1"> <asp:Button ID="btnAdd" runat="server" CssClass="btn btn-info" Text="Add" OnClick="Insert" Width="187px" /> </td> </tr> </table> </asp:Content>
doc_23531124
This is error that i get when i run it. Traceback (most recent call last): File "pandas/index.pyx", line 157, in pandas.index.IndexEngine.get_loc (pandas/index.c:3843) File "pandas/hashtable.pyx", line 303, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6501) TypeError: an integer is required During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/jacob/Projects/CIS2302/CW2/ddd_cw2/temporal_analysis /test.py", line 33, in <module> plot = seaborn.stripplot(data=data, x='day', y='category') File "/home/jacob/.virtualenvs/cis2303/lib/python3.4/site-packages/seaborn/categorical.py", line 2501, in stripplot jitter, split, orient, color, palette) File "/home/jacob/.virtualenvs/cis2303/lib/python3.4/site-packages/seaborn/categorical.py", line 1108, in __init__ self.establish_variables(x, y, hue, data, orient, order, hue_order) File "/home/jacob/.virtualenvs/cis2303/lib/python3.4/site-packages/seaborn/categorical.py", line 199, in establish_variables group_names) File "/home/jacob/.virtualenvs/cis2303/lib/python3.4/site-packages/seaborn/categorical.py", line 241, in _group_longform grouped_vals = vals.groupby(grouper) File "/home/jacob/.virtualenvs/cis2303/lib/python3.4/site-packages/pandas/core/generic.py", line 3436, in groupby sort=sort, group_keys=group_keys, squeeze=squeeze) File "/home/jacob/.virtualenvs/cis2303/lib/python3.4/site-packages/pandas/core/groupby.py", line 1311, in groupby return klass(obj, by, **kwds) File "/home/jacob/.virtualenvs/cis2303/lib/python3.4/site-packages/pandas/core/groupby.py", line 418, in __init__ level=level, sort=sort) File "/home/jacob/.virtualenvs/cis2303/lib/python3.4/site-packages/pandas/core/groupby.py", line 2264, in _get_grouper in_axis, name, gpr = True, gpr, obj[gpr] File "/home/jacob/.virtualenvs/cis2303/lib/python3.4/site-packages/pandas/core/series.py", line 557, in __getitem__ result = self.index.get_value(self, key) File "/home/jacob/.virtualenvs/cis2303/lib/python3.4/site-packages/pandas/core/index.py", line 1790, in get_value return self._engine.get_value(s, k) File "pandas/index.pyx", line 103, in pandas.index.IndexEngine.get_value (pandas/index.c:3204) File "pandas/index.pyx", line 111, in pandas.index.IndexEngine.get_value (pandas/index.c:2903) File "pandas/index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas/index.c:3908) KeyError: 'item' This is my code that i am using to try and make this work. code: import seaborn from matplotlib import pyplot from csv import DictReader from pandas import DataFrame from datetime import datetime data = {'category': [], 'day': [], 'time': []} with open('/home/jacob/Projects/CIS2302/CW2/ddd_cw2/cleaned_logs/u_ex150601.log.csv') as in_f: reader = DictReader(in_f) for line in reader: timestamp = datetime.strptime(line['time_received_isoformat'], '%Y-%m-%dT%H:%M:%S') data['day'].append(timestamp.day) data['time'].append(timestamp.hour * 60 + timestamp.minute) if 'search' in line['request_url_path']: data['category'].append('search') elif 'browse' in line['request_url_path']: data['category'].append('browse') elif 'add-to-cart' in line['request_url_path'] or 'remove-from-cart' in line['request_url_path']: data['category'].append('cart') elif 'book' in line['request_url_path']: data['category'].append('item') elif line['request_url_path'] == '/baseline/': data['category'].append('baseline') elif line['request_url_path'] == '/explore/' or line['request_url_path'] == '/review/': data['category'].append('modern') else: print(line['request_url_path']) plot = seaborn.stripplot(data=data, x='day', y='category') plot.get_figure().savefig('/home/jacob/Projects/CIS2302/CW2/ddd_cw2 /temporal_graphs/' + 'category_day_stripplot' + '.png') pyplot.close()
doc_23531125
const compress = require('compression'); export const handleCompression = compress({ filter: function (req: express.Request, res: express.Response) { return (/json|text|javascript|css|font|svg/).test(res.getHeader('Content-Type')); }, level: 9 }); I get this warning from TypeScript: Would it be correct to change the call to: res.get('Content-Type') ? A: Yes or better: req.header('Content-Type'). See footer here.
doc_23531126
import pymongo import sys def main(): connection = pymongo.Connection("mongodb://localhost", safe=True) db = connection.m101 people = db.people person ={'name': 'Barack Obama', 'role':'President', 'address':{'address1': 'The White House', 'street': '1600 Pensylvania Avenue', 'state':'DC', 'city':'Washington'}, 'interests':['government', 'basketball', 'the middle east'] } people.insert(person) And when I try to use writing mongo command it says Could not connect to server 127.0.0.1:27017 src/mongo shell mongo.js:91 exception: connection failed What can be done? I am following their tutorial! A: You need to run mongo daemon server. $ mongod You can look more information here: Is mongodb running?
doc_23531127
Code 'Clears all run specifications Sub clearRunSpecs_click() Dim resp As String resp = MsgBox("This will clear all run specifications. Are you sure you want to continue?", vbYesNo) If (resp = vbYes) Then Worksheets("AdjustmentsAmount").Unprotect "pass" Range("D3").Clear Range("D3").Interior.Color = RGB(235, 241, 222) Range("D3").BorderAround LineStyle:=XlLineStyle.xlContinuous, Weight:=xlMedium, ColorIndex:=xlColorIndexAutomatic, Color:=RGB(0, 0, 0) Range("D3").Locked = False Range("D4").Clear Range("D4").Interior.Color = RGB(235, 241, 222) Range("D4").BorderAround LineStyle:=XlLineStyle.xlContinuous, Weight:=xlMedium, ColorIndex:=xlColorIndexAutomatic, Color:=RGB(0, 0, 0) Range("D4").Locked = False Range("B4").Clear Range("B4").Interior.Color = RGB(235, 241, 222) Range("B4").BorderAround LineStyle:=XlLineStyle.xlContinuous, Weight:=xlMedium, ColorIndex:=xlColorIndexAutomatic, Color:=RGB(0, 0, 0) Range("B4").Locked = False Range("A17:D22").Clear Range("A17:D22").Merge Range("A17:D22").Interior.Color = RGB(235, 241, 222) Range("A17:D22").BorderAround LineStyle:=XlLineStyle.xlContinuous, Weight:=xlMedium, ColorIndex:=xlColorIndexAutomatic, Color:=RGB(0, 0, 0) Range("A17:D22").VerticalAlignment = xlTop Range("A17:D22").Locked = False ActiveSheet.Shapes("Facility").ListIndex = -1 ActiveSheet.CheckBoxes("ZeroBalance").Value = xlOff ActiveSheet.CheckBoxes("Balance<Adj").Value = xlOff ActiveSheet.CheckBoxes("Balance=Adj").Value = xlOff Worksheets("AdjustmentsAmount").Protect "pass" End If End Sub Methods tried ActiveSheet.Shapes("Facility") ActiveSheet.Facility ActiveSheet.ListBoxes("Facility") Application.Facility I have accessed checkboxes in the same method using ActiveSheet.CheckBoxes("NAME") and that worked fine. However, I can't seem to get ahold of the combo box. A: It is a bit hidden - you can access the listbox or combobox like this: Debug.Print ActiveSheet.Shapes("Facility").OLEFormat.Object.Value A: I have set a blank line to be ListIndex1 and used: ActiveSheet.Shapes("Facility").ControlFormat.ListIndex = 1 to access it. I am presuming that's what you need?
doc_23531128
I have abstract class A. Class A1 extends A. If I write ArrayList<A> a = ArrayList<A1> a1 I get error Type mismatch: cannot convert from ArrayList<A1> to ArrayList<A> A: You cannot Cast from ArrayList<A1> to other type ArrayList<A> using TypeErasure,So I suggest you to try with using WildCard in java for this case ArrayList<? extends A1>a1=new ArrayList<A1>(); ArrayList<? extends A1> a = a1; A: In the following a list declaration, ArrayList<A> a the type rules say that a list can only contain object of exactly A type: it cannot, for instance, contain any other type of type object which extends super type A. To solve this problem you can use Bounded Wildcards as follows... ArrayList<? extends A> a = a1 Now a list will accept lists of any subclass of A. Here, The ? stands for an unknown type, but this unknown type is in fact a subtype of Shape. (Note: It could be A itself, or some subclass; it need not literally extend A).
doc_23531129
const fetchUsersFromApi = () => fetch('https://jsonplaceholder.typicode.com/users?_limit=10') function* fetchUserWorker() { const data = yield call(fetchUsersFromApi) const json = yield call(() => new Promise(res => res(data.json()))) yield put(setUsers(json)) } A: No you can't do it . Considering you are firing the API call after the component is mounted inside your useEffect for function component or componentDidMount in case of class component . You need a state to hold the initial users value . Initially users will be an [] and once you make the API call your users might be list of users [{}, {}]. Now if you see here we are changing the value from [] to [{}, {}] over a period of time. State provided by react is for this purpose . Whenever a value changes over a period of time either by API calls or by user Interactions then it has to be held in State .
doc_23531130
I need to send characters, '1' or '2', to control a servo and I am using these commands: mode com10:9600,n,8,1 ... and I see that my Arduino received some data. After that, I try to use that: echo 1>com10 OR echo "1">com10 and nothing nothing happens. With PuTTY it works corrent and turning, when I press 1 or 2. With the Arduino serial monitor it works great too. A: What worked for me was, something like: echo ON > \\.\COM4 echo OFF > \\.\COM4 This link provides some good info. So, in general, the format to send simple ASCII chars to serial port: echo [ASCII chars / string you want to send] > \\.\ [Com Port #] A: At the end, I used PowerShell to do this task: powershell "$port= new-Object System.IO.Ports.SerialPort COM10,9600,None,8,one; $port.open(); $port.WriteLine("1"); $port.Close()" A: PowerShell is very useful when working with Arduinos, here is a link to a post where I did the same. I've added a COM port lookup and some error handling to ease the process. Hope this helps someone. A: mode com3 BAUD=9600 PARITY=n DATA=8 STOP=1 && echo blahblah > com3 about the same: powershell "$port= new-Object System.IO.Ports.SerialPort COM10,9600,None,8,one; $port.open(); $port.WriteLine("1"); $port.Close()" A: This will send the contents of a file to COM10 under Windows 7, not sure about other versions: copy myfile \\.\COM10 If you just use "copy myfile COM10" then it creates a file called COM10 instead. So you might like to try: echo 1>\\.\com10 A: Three points: * *COM10 isn't a reserved file name like COM1–4, so it could be that you're just creating a file. *echo 1>foo is the same as echo >foo which will print ECHO is on. (you're redirecting stream 1, aka stdout). *echo "1">foo will print "1" including the quotes. To actually echo a 1 somewhere you'd have to use >foo echo 1 or (echo 1)>foo
doc_23531131
function ycs_list() { $query = new EntityFieldQuery; $query->entityCondition('entity_type', 'node') ->entityCondition('bundle', YCS_NODE_TYPE) ->propertyCondition('status', 1) ->fieldCondition('field_active_image', 'value', 1, '='); $result = $query->execute(); return $result; } How can I expand this to use two fileds? If I were to use a taxonomy list, would I use something other than a EntityFieldQuery or is it just an additional condition of this? A: You can add as many conditions to an EntityFieldQuery as you like and as vocabularies are linked to nodes via fields in Drupal 7 you can include them quite easily. The only small thing to note is that the column name for a term ID in a term reference field is tid instead of value which is used in a lot of cases. The following assumes your term reference field is named field_my_term_field: $query = new EntityFieldQuery; $query->entityCondition('entity_type', 'node') ->entityCondition('bundle', YCS_NODE_TYPE) ->propertyCondition('status', 1) ->fieldCondition('field_active_image', 'value', 1, '=') ->fieldCondition('field_my_term_field', 'tid', $the_term_id); $result = $query->execute(); return $result;
doc_23531132
public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddJsonFile("hosting.json", optional: true) .AddCommandLine(args) .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .Configure(app => { app.Run(async (context) => await context.Response.WriteAsync("Hi!")); }) .Build(); host.Run(); } I don't want to use hosting.json. Why would I want that? I have this appsettings.{environment}.json file for exactly this situation. Sweet, I'll just paste that bad boy in public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddCommandLine(args) .Build(); What the compiler error? env does not exist in the current context. It only exists in the Startup.cs file--which is not called on startup, but called from the startup file, Program.cs, with sorcery. So, how do I solve this problem? How can I store my environment-specific hosting settings in my environment-specific appsettings.json, and subsequently use it in while building my environment-specific web host via the WebHostBuilder in Program.cs? A: This is possible. Expanding on the answer given here, by creating the WebHostBuilder and ConfigurationBuilder in the Program.cs, it is possible to have access to the host environment and then configure the host URL and port in environment-specific appsettings files. Assuming an appsettings.json and an apppsettings.Development.json file each with the following: "hostUrl": "http://*:<port number here>" Modify the Main with the following: public static void Main(string[] args) { var host = new WebHostBuilder(); var env = host.GetSetting("environment"); var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env}.json", optional: true) .AddEnvironmentVariables(); var configuration = builder.Build(); host.UseKestrel() .UseUrls(configuration["hostUrl"]) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build() .Run(); } Using this code, the Startup.cs will still need to declare its own ConfigurationBuilder in order to publicly expose its Configuration property. A: Or, starting from .NET Core 2.0, when creating the default IWebHostBuilder that will build the IWebHost implementation, you can use return WebHost.CreateDefaultBuilder(args) .UseConfiguration(configuration) .ConfigureAppConfiguration((builderContext, config) => { // nb: here you may clear configuration(s) loaded so far var env = builderContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true); }) .UseStartup<Startup>();
doc_23531133
I have two similar set of Entities which must save data to different tables in DB. But since the business logic is perfectly same, so I want to use base classes for these entities, so these base classes can be used in common JPA repository (@NoRepositoryBean). @MappedSuperClass class Classroom { String std; } @MappedSuperClass class School { String name; @OneToMany //ERROR Set<Classroom> rooms; } @entity @table("A_SCHOOL") class ASchool extends School { Set<AClassroom> rooms; } @entity @table("A_CLASSROOM") class AClassroom extends Classroom { } @entity @table("B_SCHOOL") class BSchool extends School { Set<BClassroom> rooms; } @entity @table("B_CLASSROOM") class BClassroom extends Classroom { } The issue is the @OneToMany mapping in School is not allowed since Classroom is not an entity. Considering the common JPA repository (and all other business logic) is designed to work with only School/Classroom, how should I update the association of Classrooms in School? A: the idea of using @MappedSuperClass is to make common attributes between different classes in one place . in your case each School has dependency on certain ClassRoom so you need to declare that relationship in each subclass of school, so you need to remove the relationship from the parent class and declare it in all School subclasses . have a look at this tutorial :How to inherit properties from a base class entity using @MappedSuperclass with JPA and Hibernate
doc_23531134
Also in Pages I have 5 active and only 4 published. The 5th one is marked as Private but I can't see it (I suppose this one is my previous now hidden page)
doc_23531135
I don't want to show to the user that notification. I tried to implement BroadcastReceiver inside the Application class. But this is not working proprely. Somethimes the BroadcastReceiver doesn't work and somethimes works well. Even when it works well, if the app is removed from the recent tasks, the BroadcastReceiver stops to work. Is there a way to use a BroadcastReceiver that works indefinitely without the use of a service? A: Is there a way to use a BroadcastReceiver that works indefinitely without the use of a service? In the case of ACTION_TIME_TICK: No, since you cannot use a manifest-declared BroadcastReceiver. Since you're not willing to use a foreground service, you may want to look into START_STICKY. In this situation, that's the only way to maximize your Service's run-time: Allow the system to re-start it, capriciously, after it's been stopped for lack of resources. Of course, this means your clock could stop updating for arbitrarily long periods of time. Note that your problem is not limited to Oreo (Oreo does not require you to be a foreground service, but it does impose certain limits on what you're allowed to do if you're NOT in the foreground). Even on earlier OSs, if you're not foreground, the system considers you a prime candidate for elimination.
doc_23531136
I tryed with opera, firefox, IE, safary and chrome. I tryed to change z-index of my link whithout any result. You can see this issue by downloading images and code there : https://www.mediafire.com/folder/kn6wdothgbsms/html_problem I also copy/past you the code directly on this page : <!doctype html> <html> <head> <meta charset="utf-8"> <title>Document sans nom</title> <style> section>img:first-child { position:absolute; left:0px; top:0; } section>img:nth-child(2) { position:absolute; right:0px; top:0; } article { padding:50px; } a { z-index:10; } </style> </head> <body> <section> <img alt="article_end" src="main_top_left.png"/> <img alt="article_end" src="main_top_right.png"/> <article> <a href="www.google.fr">LINK</a> </article> </section> </body> </html> A: Z-index will only apply to elements that have been set position: absolute or position: relative; so in order to get your link "on top of" your images, you should give it a position: relative. Working example: http://www.codeply.com/go/7Gog6kcwiC See also z-index not working with position absolute
doc_23531137
namespace APIMCheck { class Program { static void Main(string[] args) { string thumbprint = "***"; string url @"https://******-us-stats-webapi.azurewebsites.net/statistics/v1/masterData/carTypes"; X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, true); X509Certificate2 certificate = certificates[0]; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ClientCertificates.Add(certificate); req.Method = WebRequestMethods.Http.Get; Console.WriteLine(Program.CallAPI(req).ToString()); Console.Read(); } public static string CallAPI(HttpWebRequest req) { var httpResponse = (HttpWebResponse)req.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { return streamReader.ReadToEnd(); } } public static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; } } } I get response with data. All good. Now, I have created Azure APIM, which will act as front end for above web API This is policy configured in Azure API Management portal <policies> <inbound> <base /> <choose> <when condition="@(context.Request.Certificate.Verify() != true || context.Request.Certificate == null || context.Request.Certificate.Issuer != "CN=MySubCA, DC=MYEXT, DC=NET" || context.Request.Certificate.NotAfter < DateTime.Now)"> <return-response> <set-status code="403" reason="Invalid client certificate" /> <set-body template="none">@(context.Request.Certificate.Issuer.ToString())</set-body> </return-response> </when> </choose> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </on-error> </policies> Now, changed the url as follow to point apim string url = @"https://******-us-stats-apim.azure-api.net/statistics/v1/masterData/carTypes"; I get below error The request was aborted: Could not create SSL/TLS secure channel for HttpWebRequest How SSL/TLS making difference in web api and APIM? Anything to do with firewall? A: By default, TLS 1.2 is enabled for Azure API Management gateway. You could go to your azure api management(on portal) > Protocol settings> turn on tls 1.2 and ssl 3.0. A: There are a few things you do in your test app and APIM cannot do on it's own: * *Enable SSL3 *Add client certificate *Ignore any SSL validation errors. Of the things above only #2 is fine to have in production. SSL3 is deprecated and should not be used in production. Ignoring any SSL errors is also unwise, since that way you cannot be sure that you're talking to your server. Now assuming that you're fine with all of the above: * *For SSL3 follow @Joey Cai answer. *To allow APIM to use your certificate to authenticate to backend follow this guidance: https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-mutual-certificates *To control SSL validation at APIM level use this REST API: https://learn.microsoft.com/en-us/rest/api/apimanagement/2019-01-01/backend/createorupdate and set-backend-service policy. The main reason for #2 and #3 is that client-to-APIM and APIM-to-backend are two separate connections. So when APIM needs to make a call to backend it must have client certificate available (if it's required by backend). That also means that by default APIM will not require client to provide certificate.
doc_23531138
names(object_1) <- namesvector names(object_2) <- namesvector names(object_3) <- namesvector Is it possible to do that in only one step? Thanks! A: A slightly more compact solution lapply(list(obj_1, obj_2, obj_3), setNames, name_vector) A: You could try putting all your numeric vectors into a list, then lapply over them with an assignment. Something like: # makes some vectors obj_1 <- 1:10 obj_2 <- 1:10 obj_3 <- 1:10 name_vector <- LETTERS[1:10] # now apply the names lapply(list(obj_1,obj_2,obj_3), function(x) {names(x) <- name_vector; x}) A: Another way just for fun: lapply(list(object_1, object_2, object_3), structure, .Names = namesvector) All these answers are condemning your objects to a list. If you still want your objects freely accessible (i.e. in the global environment) here's another solution: Sample objects: object_1 <- runif(3) object_2 <- runif(3) object_3 <- runif(3) Names you want to apply: namesvector <- letters[1:3] Some hackery to apply names: # Objects you want to combine. items_n <- c("object_1", "object_2", "object_3") # Make into a list with names of objects needed for promoting to global environment. items <- structure(lapply(items_n, get), .Names = items_n) # Add names to object elements. named <- lapply(items, structure, .Names = namesvector) # Promote to global environment. list2env(named, .GlobalEnv) Now you can still reference e.g.: object_1 and get its contents back. You could create items_n (the list of objects to combine) dynamically as well if you have lots of objects (assuming they have a similar name): items_n <- sapply(1:3, function(x) paste0("object_", x))
doc_23531139
onclick="this.style.border='solid 1px red';" How to insert multiple onclick events which would trigger changes of border colors - for example 1st click - red, 2nd click - blue, 3rd click - reset? This is exactly what I need - changes of the one particular div with multiple onclick events, not improvisations with multiple divs. edit: I also have other actions called with onclick + I have onmouseenter and onmouseleave events inside of the same div. Everything work as it should, I only can't get multiple onclick events to work. I can't get any of these functions to work and I can't tell why. Maybe because I have more actions and events, or maybe it's up to Wordpress? (I put a function in the header area inside of <script></script>) I thought this will be easier than playing a sound, but surprisingly sounds were a piece of cake and this seems to be a real challenge... can somebody help? edit2: It was up to Wordpres. Now I know how to make proper functions to work. edit3: I've edited a little solution posted by user1875968, and I finally got exactly what I want (with proper reset): var linkClick = 1; function update_link(obj){ if (linkClick == 1){obj.style.border = 'solid 1px red'}; if (linkClick == 2){obj.style.border = 'solid 1px blue'}; if (linkClick == 3){obj.style.border = 'solid 1px green'}; if (linkClick >3 ) {obj.style.border = 'solid 1px #555555'; linkClick=0}; linkClick++; } thanks everybody for your help ;) A: you can make use of functions and css classes. Identify the styles you want to switch between as different classes. Let's take them as: .redBorder { border: 1px solid red; } .blueBorder { border: 1px solid blue; } .resetBorder { border: none; } declare a function on the click event of the div: onclick="switchBorder(this);" Inside the function, use a switch case on the div class: function switchBorder(divObj) { prevClass = divObj.className; switch( prevClass ) { case 'redBorder': divObj.className = "blueBorder" break; case 'blueBorder': divObj.className = "resetBorder" break; case 'resetBorder': divObj.className = "redBorder" break; } } Hope that helps. :) Edit: syntax mistake. A: The only way i could think of is changing the on-click event every time it's fired like: x.onclick = method1; function method1() { x.onclick = method2; } funbction method2() { x.onclick = method3; } function method3() { x.onclick = method1; } A: You can make use of integers onclick="my_function()" and then: function my_function(){ i++; if(i == 1){ //red } if(i == 2){ //blue } if(i == 3){ i = 0; // reset } } A: it's best to use javascript for this. var clicks = 0; function changeBorder() { if(++clicks > 2) clicks = 1; switch (clicks) { case 1 : { this.style.border='solid 1px red';}; break; case 2 : { this.style.border='solid 1px blue';}; break; } } But you have to adapt on the "this" element. (i don't know which one it is, use getElementById) and use in HTML, onclick="changeBorder()" A: Something like this. Presuming the default border is "1px solid black". This can be extended to contain as many changes and colors as you want. function changeBorder(ele){ var colors = ["1px solid black", "1px solid red", "1px solid blue"]; var curInd = colors.indexOf(ele.style.border); if(curInd != colors.length-1){ //If the current color isn't the last one //Next color ele.style.border = colors[curInd++]; } else { //Reset to first color ele.style.border = colors[0]; } } NOTE: array.indexOf is an ECMAscript 5 implementation for older browsers please include the shim found here A: <script> var linkClick = 0; function update_link(obj){ if (linkClick == 0){obj.style.border = 'solid 1px red'}; if (linkClick == 1){obj.style.border = 'solid 1px blue'}; if (linkClick >1 ) {obj.style.border = 'solid 1px red'; linkClick=0}; linkClick++; } </script> HTML <a href='#' onclick='update_link(this)'> my link </a> A: Try using a global variable like colorCode and initialize it to zero—colorCode=0 And call a function onClick="ChangeBGColor()" function ChangeBGColor() { colorcode++; var color=''; if (colorcode==1) { color='red'; } else if (colorcode==2) { color='blue'; } else { colorCode=0; /*Reset to zero if colorCode =3 or more*/ color='gray'; } this.style.border="'solid 1px "+color+ "';" /* Need to correctly apply style for the specific contol*/ } A: <div id="x" onclick="Clicked"></div> <script type="text/javascript"> var clickno=1; function Clicked() { if(clickno==1) { document.getElementById('x').style.border="solid 1px red"; } if(clickno==2) { document.getElementById('x').style.border="solid 1px blue"; } if(clickno==3) { document.getElementById('x').style.border="solid 1px red"; clickno=1; } clickno++; } </script>
doc_23531140
angular.module('optionsExample', []) .controller('ExampleController', ['$scope', function($scope) { debugger; if(true){ $scope.name = 'Foo'; } if(false){ $scope.name = 'lol'; } }]); Firefox version: 35.0.1 Chrome version: 41.0.2272.101 m Why does it happen? Update: Also tested in Firefox 36.0.4, Same problem. A: This maybe a bug or it may just be how they designed it. But this seems to do with how the debugger deals with if statement conditions it can readily evaluate, and the code styling used (K&R, Allman, 1TBS, etc) Lines of code that can have breakpoints set to them are shaded green, and ones that cannot are shaded gray by the debugger. Simply put the debugger does not highlight if statement lines (and maybe even other control statement lines) that it can readily tell have a true/false condition. When setting a breakpoint the breakpoint will be put on the next breakable line of code instead. In the case of blocks that use 1TBS/OTBS or K&R style formatting the debugger will highlight the first breakable line within the if block instead of the actual if statement line. This gives the false impression that the code inside false condition if statements are going to be executed next. In the case of blocks that use Allman style formatting the debugger will not highlight any part of the if statement or code block when stepping through. And if you try to put a code break on the if statement it will skip the entire block and put the breakpoint on the next breakable line. When the if statements do not use conditions that the debugger can readily read as true/false the debugger acts as expected. Demo to test debugger; var one = true; var two = false; //Allman Style if(one) { console.log("Truth"); } if(two) { console.log("false"); } if(true) { console.log("Truth"); } if(false) { console.log("false"); } //1TBS/OTBS Style if(one){ console.log("Truth"); } if(two){ console.log("false"); } if(true){ console.log("Truth"); } if(false){ console.log("false"); }
doc_23531141
DEFINE('INTERESTS_1','a'); DEFINE('INTERESTS_2','d'); DEFINE('INTERESTS_3','g'); DEFINE('INTERESTS_4','c'); Is it possible to open it, put it into an array and then ordering it ASC beforing echoing it all out using a loop? A: // capture constant before loading the new ones $before = get_defined_constants(); // require_file // require_once 'somefile'; DEFINE('INTERESTS_1','a'); // this is for testing DEFINE('INTERESTS_2','d'); // " DEFINE('INTERESTS_3','g'); // " DEFINE('INTERESTS_4','c'); // " $new = array_diff(get_defined_constants(), $before); // sort, or do whatever you want with those values asort($new); // debug output foreach ($new as $constantName => $constantValue) { echo $constantName, ' ', $constantValue, "\n"; } A: What you can do is, use get_defined_constants() and then use sort() to sort the array of constants and of course, use a foreach loop to echo out what you want. A: Yeap... Use $GLOBALS to print them, and natsort them http://php.net/manual/en/function.natsort.php
doc_23531142
$con = mysqli_connect('localhost','root','','demo') or die('Unable To connect'); $query = mysqli_query($con,"SELECT * FROM images"); while($row=mysqli_fetch_assoc($query)) { echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />'; } Problem with those coding : It only display images with .png extension because I am using echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />'; to display it. What I am trying to do : I wanted to display images with extension .jpeg .png and .gif as well. Is there anybody that can help me with other simple way of displaying images? Thank you. A: Store the format in the database as well: $con = mysqli_connect('localhost','root','','demo') or die('Unable To connect'); $query = mysqli_query($con,"SELECT * FROM images"); while($row=mysqli_fetch_assoc($query)) { echo '<img src="data:image/' . $row['format'] . ';base64,' . base64_encode($row['image']) . '" />'; } A: Hi Just get the image extension and use it $ext = pathinfo($row['image'], PATHINFO_EXTENSION); echo '<img src="data:image/' . $ext . ';base64,' . base64_encode($row['image']) . '" />'; A: @FrankerZ already gave correct solution but if you have already stored base64 images on your database it will be problematic to add format column. You can discover the mime type of image from base64 like that; $img = $row['image']; // base64 of your image $fileInfo = finfo_open(); // file info resource $mimeType = finfo_buffer($fileInfo, $img, FILEINFO_MIME_TYPE); If you have already existing records, do not apply this methodology on your each iteration. Simply add new column to your database, and fill/update these new colums using this methodology. After that, use @FrankerZ 's solution.
doc_23531143
Here are my R and RStudio configurations: Sys.info() sysname release version nodename machine login user effective_user "Windows" "10 x64" "build 19044" "MP01027922" "x86-64" "U468091" "U468091" "U468091" .libPaths() [1] "C:/profili/u468091/Documents/Enterprise Analytics/R-4.2.2/library" dir.exists(Sys.getenv("R_LIBS_USER")) [1] FALSE # why? the env variable 'R_LIBS_USER' is properly set up (see later) Sys.getenv() ... PATH c:/rtools42/x86_64-w64-mingw32.static.posix/bin; c:/rtools42/usr/bin; ... PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC ... R_ARCH /x64 R_CLI_HAS_HYPERLINK_IDE_HELP true R_CLI_HAS_HYPERLINK_IDE_RUN true R_CLI_HAS_HYPERLINK_IDE_VIGNETTE true R_COMPILED_BY gcc 10.4.0 R_DOC_DIR c:/profili/u468091/DOCUME~1/ENTERP~1/R-42~1.2/doc R_HOME c:/profili/u468091/DOCUME~1/ENTERP~1/R-42~1.2 R_LIBS_SITE c:/profili/u468091/DOCUME~1/ENTERP~1/R-42~1.2/site-library R_LIBS_USER C:\Users\u468091\AppData\Local/R/win-library/4.2 R_RTOOLS42_PATH c:/rtools42/x86_64-w64-mingw32.static.posix/bin;c:/rtools42/usr/bin R_USER C:/profili/u468091/Documents RMARKDOWN_MATHJAX_PATH c:/profili/u468091/Documents/Enterprise Analytics/rSTUDIO/resources/mathjax-27 RS_LOCAL_PEER \\.\pipe\55470-rsession RS_RPOSTBACK_PATH c:/profili/u468091/Documents/Enterprise Analytics/rSTUDIO/bin/rpostback RS_SHARED_SECRET 1cc90387-55bd-426a-ab7d-3ef4b8b6eba3 RSTUDIO 1 RSTUDIO_CLI_HYPERLINKS true RSTUDIO_CONSOLE_COLOR 256 RSTUDIO_CONSOLE_WIDTH 80 RSTUDIO_MSYS_SSH c:/profili/u468091/Documents/Enterprise Analytics/rSTUDIO/bin/msys-ssh-1000-18 RSTUDIO_PANDOC c:/profili/u468091/Documents/Enterprise Analytics/rSTUDIO/bin/quarto/bin/tools RSTUDIO_PROGRAM_MODE desktop RSTUDIO_SESSION_PID 9444 RSTUDIO_SESSION_PORT 55470 RSTUDIO_USER_IDENTITY U468091 RSTUDIO_WINUTILS c:/profili/u468091/Documents/Enterprise Analytics/rSTUDIO/bin/winutils ... Any suggestions? There are a lot of posts out there related to R user library disappeared. None related to system library disappeared. Many thanks in advance.
doc_23531144
Edit: I understand this can be fixed by using just a single assembly. We have more than one for the following reason: * *our "system" consists of several components. A customer can have just one component, or more - so what we did is we created different assemblies for different components. It kind of makes sense - why would you deploy things that you do not need - is it not a wasting of memory? *things that were common to more components, mostly helper classes, went to another assembly - again not all components need all helper classes, so there are more assemblies *however, these two applications can talk to each other - the system for doctors sends requests to the system for nurses, requests are going back, etc. - and here's where the actual problem is Having the two components talking to each other is really just one of the situations we've had a cyclic dependency conflicts before. It happens now and then and when it happens we need to figure out how to solve it - move some classes around - and sometimes we need to add a new assembly. Now we have like 8-10 assemblies, and it looks like the more you have the faster they get added :) - for example, we added a general purpose feature that uses custom attributes - so we added another assembly just for the attribute - just in case we do not get in conflict in future Is this the way to go? I am really feeling we are doing something fundamentally wrong :) I really appreciate your input. A: Can you put the common stuff in its own assembly? I agree with one commenter that we probably need more information. Why do you have 2 assemblies? Is there a reason everything's not in one assembly? How are these assemblies connected? Just via reference or are there WCF, etc components involved? We've given you the simplest answers, but maybe there's more to it than we can tell by your brief description. A: I would try to pull the offending types out into a third 'common' assembly that the two 'parent' assemblies reference. I would question why you need multiple assemblies in the first place, however, when they both depend on each other. Assemblies are units of deployment, and can be versioned separately from each other. If you don't need this functionality, I would just package everything into a single assembly and be done with it. This has the added bonuses of speeding up the build and simplifying deployment. Please do try to add more context to your question - maybe there are some details we can help with if we know exactly what it is you're trying to do. Edit re your additions: To specifically answer your question regarding whether or not multiple assemblies is the way to go, consider this: I once worked on a codebase like this with Visual Studio 2008, where there were about 20 separate project files open in the solution at once. These 20 projects were all supporting DLLs for a single main EXE. These projects were not shared with other products, nor were there strange versioning requirements. Working with this solution was a nightmare. It took literally 5 minutes for Visual Studio to compile the solution. Compiling in the command line with MSBuild took 2 minutes. This made making incremental changes an exercise in frustration and pain. Since all of the projects were used in the making of the main executable, none of them could be unloaded to speed up the compile, and there was an executive mandate against breaking projects out into separate solutions. If you end up with a single solution like this, trust me when I say that you and your teammates will revolt one day... My recommendation would be to break out assemblies into their own solutions, grouping together any assemblies that are likely to be changed together; then create a custom build task that copies the final assembly into a common folder from which all the other assemblies can take references. A: One way to avoid it would be using a proxy / business structure. AssemblyA.Proxy - contains two classes: one interface (let's call it IServices), and another class responsible for calling AssemblyA.Business methods. AssemblyA.Business - contains one class, which implements the methods declared on IServices. AssemblyB.Proxy - analogue to AssemblyA.Proxy AssemblyB.Business - analogue to AssemblyA.Business This way, each Proxy component would reference only the business logic they're supposed to. AssemblyA.Proxy would have a reference to AssemblyA.Business; AssemblyB.Proxy would have a reference to AssemblyB.Business. AssemblyA.Business would reference AssemblyB.Proxy, and so on. Don't know if it it's clear but hope it helps.
doc_23531145
Code compile fine but when debug the code "Unhandled exception at 0x00416d14 in deletedemo.exe: 0xC0000005: Access violation writing location 0x0041ff01." exception occur at the line // Check for an ending slash and add one if it is missing. lpEnd = lpSubKey + lstrlen(lpSubKey); if (*(lpEnd - 1) != TEXT('\\')) { *lpEnd = TEXT('\\'); //Here exception occur. lpEnd++; *lpEnd = TEXT('\0'); } A: I have written a code to delete the Registry Key and its Subkeys recursively some time ago. The code goes like this:: static BOOL RcrsvRegDel( HKEY hKey, LPTSTR lpszSub, DWORD dwOpenFlags ) { BOOL bRet = TRUE ; LONG lRet ; DWORD dwSize = MAX_PATH ; TCHAR szName[MAX_PATH] ; HKEY hKeySub = NULL ; HRESULT hr = NULL ; HANDLE hProcess = NULL ; HANDLE hToken = NULL ; do{ lRet = RegOpenKeyEx( hKey, lpszSub, 0, dwOpenFlags, &hKeySub ) ; if( lRet != ERROR_SUCCESS ) { bRet = FALSE ; break ; } while( ERROR_NO_MORE_ITEMS != (lRet = RegEnumKeyEx(hKeySub, 0, szName, &dwSize, NULL, NULL, NULL, NULL)) ) if( !RcrsvRegDel(hKeySub, szName, dwOpenFlags) ) { bRet = FALSE ; break ; } lRet = RegDeleteKey( hKey, lpszSub ) ; printf("RegDelKey:: %S :: lRet = %ld\n", lpszSub, lRet) ; if( lRet != ERROR_SUCCESS ) { bRet = FALSE ; break ; } if( hKeySub != NULL ) { RegCloseKey(hKeySub) ; hKeySub = NULL ; } }while(0) ; return bRet ; } dwOpenFlags = Flags to be passed to RegOpenKeyEx or RegDeleteKey. EDIT:: If you do not want to delete the whole tree yourself recursively, MSDN have two functions to do this. You can always use them, namely, RegDeleteTree and SHDeleteKey.
doc_23531146
I need to do LDAP authentication for the users. The application should support multiple users at a time. I checked on few references but nothing helped. I prefer not to use any 3rd party opensource products like keycloak, ngninx. Some help on this would be really appreciated. A: Get Basic Auth running. Then fork https://github.com/plotly/dash-auth and change the is_authorized function in the file dash_auth/basic_auth.py to your needs, i.e. make it only return true if the given username and password can login to your LDAP server, for which you probably have to use a LDAP library. After that build your altered dash-auth package and install it over the one that ships with Dash. You can also serve your app via gunicorn and make it use TLS, so your user's credentials are protected.
doc_23531147
A: This was the first solution I came up with: DocumentBuilder builder = DocumentBuilderFactory .newInstance() .newDocumentBuilder(); StringReader reader = new StringReader( xml ); Document document = builder.parse( new InputSource(reader) ); XPathExpression expr = XPathFactory .newInstance() .newXPath() .compile( ... ); Object result = expr.evaluate(document, XPathConstants.NODESET); Element el = document.getDocumentElement(); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { el.removeChild( nodes.item(i) ); } As you can see it's kinda long. Being a coder who strives for simplicity, I decided to take Ahmed's advice hoping I'll find a better solution and I came up with this: List<?> elements = page.getByXPath( ... ); DomNode node = null; for( Object o : elements ) { node = (DomNode)o; node.getParentNode().removeChild( node ); } Please note these are just snippets, I omitted the imports and the XPath expressions but you get the idea. A: Have a look at the DOM methods, you can remove nodes. http://htmlunit.sourceforge.net/apidocs/com/gargoylesoftware/htmlunit/html/DomNode.html
doc_23531148
#import "MapViewController.h" #import <MapKit/MapKit.h> #import <CoreLocation/CoreLocation.h> #import "Vehicles+Company.h" #import "Vehicles+MKAnnotation.h" -(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ if ([segue.identifier isEqualToString:@"reserveCar"]) { if ([sender isKindOfClass:[MKAnnotationView class]]) { MKAnnotationView *aView = sender; if ([aView.annotation isKindOfClass:[Vehicles class]]) { Vehicles *vehicle = aView.annotation; if ([segue.destinationViewController respondsToSelector:@selector(setVehicle:)]) { [segue.destinationViewController performSelector:@selector(setVehicle:) withObject:vehicle]; } } } } } This is the viewcontroller it is segueing to. .h file #import <UIKit/UIKit.h> #import "Vehicles+MKAnnotation.h" #import "Vehicles.h" #import "Vehicles+Company.h" @interface CompanyVehicleViewController : UIViewController @property (nonatomic,strong) Vehicles *vehicle; @end .m file #import "CompanyVehicleViewController.h" @interface CompanyVehicleViewController () @end @implementation CompanyVehicleViewController -(void) setVehicle:(Vehicles *)vehicle{ _vehicle = vehicle; self.title = vehicle.name; NSLog(@"Vehicle is %@", vehicle); } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. } @end A: Most likely segue.destinationViewController isn't an instance of CompanyVehicleViewController. Verify in your storyboard that the view controller's type is set to the proper class.
doc_23531149
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> <style type="text/css"> .CaptionRight { float: right; vertical-align: top; margin-left: 1em; margin-bottom: 1em; display:block; border: 1px red solid; } .CaptionRight p { } body { width: 500px; } </style> </head> <body> <p><span class="CaptionRight" style="width:300px;"><img src="http://www.dn.se/ImageHandler.axd/?id=1034780&imageFormat=original" alt="" /> <p> -This should be the image caption right under the image. </p></span> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc lobortis at lacus in auctor. Phasellus urna ligula, accumsan ut nisl pharetra, porta egestas ligula. Integer ultrices dolor neque, dapibus cursus lorem volutpat sit amet. Aliquam volutpat tempus dapibus. Vestibulum blandit, quam sit amet lacinia laoreet, dui massa dictum turpis, sed mattis purus lorem non diam. Pellentesque imperdiet massa libero, et ultrices tellus tincidunt eu. Vivamus urna magna, congue nec imperdiet nec, eleifend vitae elit. Donec iaculis lorem elementum orci tempus rutrum. Donec vel tortor iaculis lacus lacinia tempus sed vel est. Suspendisse iaculis vestibulum tincidunt. Quisque varius sapien porttitor malesuada volutpat. Sed a sapien nisl. </p> </body> </html> A: You cannot have <p></p> tags inside another <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> <style type="text/css"> .CaptionRight{ float: right; vertical-align: top; margin-left: 1em; margin-bottom: 1em; display:block; border: 1px red solid; } Body{ width: 500px; } </style> </head> <body> <span class="CaptionRight" style="width:300px;"><img src="http://www.dn.se/ImageHandler.axd/?id=1034780&imageFormat=original" alt="" /><p>-This should be the image caption right under the image.</p></span> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc lobortis at lacus in auctor. Phasellus urna ligula, accumsan ut nisl pharetra, porta egestas ligula. Integer ultrices dolor neque, dapibus cursus lorem volutpat sit amet. Aliquam volutpat tempus dapibus. Vestibulum blandit, quam sit amet lacinia laoreet, dui massa dictum turpis, sed mattis purus lorem non diam. Pellentesque imperdiet massa libero, et ultrices tellus tincidunt eu. Vivamus urna magna, congue nec imperdiet nec, eleifend vitae elit. Donec iaculis lorem elementum orci tempus rutrum. Donec vel tortor iaculis lacus lacinia tempus sed vel est. Suspendisse iaculis vestibulum tincidunt. Quisque varius sapien porttitor malesuada volutpat. Sed a sapien nisl. Etiam ultricies tincidunt sagittis. Cras tortor turpis, blandit eu tincidunt eu, malesuada sit amet nisl. In ullamcorper tellus est, et volutpat dui pretium id. Nullam a dolor orci. Vivamus volutpat nisl vel eros feugiat, sit amet elementum est eleifend. Phasellus lorem sem, adipiscing eu lacus consequat, hendrerit feugiat risus. Donec non adipiscing felis. Suspendisse potenti. Mauris tempus id magna at euismod. Quisque non justo eu nulla consequat feugiat sed vel diam. Nulla nec tortor rhoncus, tincidunt elit et, sagittis libero. Phasellus sed nibh et arcu elementum lacinia sit amet nec dolor. Phasellus dictum pulvinar erat vel auctor. Fusce nibh massa, molestie et elit fermentum, fringilla aliquam tellus. Donec pulvinar auctor risus, id auctor nisi pellentesque pellentesque. Ut ut auctor metus. Curabitur sit amet dictum nunc. Aliquam dignissim erat ac nisl pellentesque, at pellentesque nisi auctor. Ut dapibus iaculis volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Maecenas hendrerit ipsum ut dolor commodo feugiat. Praesent eu purus eu ipsum pharetra commodo at at odio. Maecenas elementum urna vitae congue scelerisque. Donec vel laoreet lectus, ut laoreet odio. Nam ut accumsan quam, adipiscing tincidunt libero. Aenean quis felis libero.<br /></p> </body> </html> A: HTML5: <!DOCTYPE html> ... <figure> <img src="#" alt="image"> <figcaption>My caption</figcaption> </figure> Fiddle In this way? A: Just remove the P from the HTML. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> <style type="text/css"> .CaptionRight { float: right; vertical-align: top; margin-left: 1em; margin-bottom: 1em; display:block; border: 1px red solid; } body { width: 500px; } </style> </head> <body> <p><span class="CaptionRight" style="width:300px;"><img src="http://www.dn.se/ImageHandler.axd/?id=1034780&imageFormat=original" alt="" />This should be the image caption right under the image.</span> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc lobortis at lacus in auctor. Phasellus urna ligula, accumsan ut nisl pharetra, porta egestas ligula. Integer ultrices dolor neque, dapibus cursus lorem volutpat sit amet. Aliquam volutpat tempus dapibus. Vestibulum blandit, quam sit amet lacinia laoreet, dui massa dictum turpis, sed mattis purus lorem non diam. Pellentesque imperdiet massa libero, et ultrices tellus tincidunt eu. Vivamus urna magna, congue nec imperdiet nec, eleifend vitae elit. Donec iaculis lorem elementum orci tempus rutrum. Donec vel tortor iaculis lacus lacinia tempus sed vel est. Suspendisse iaculis vestibulum tincidunt. Quisque varius sapien porttitor malesuada volutpat. Sed a sapien nisl. </p> </body> </html>
doc_23531150
I am thinking about fetching the data "state" via hook, and altering the discount depending on the fetched data. I can't figure out where I can set the value of the price. I don't think the rules will be much of a help, since all be adding a lot of conditions to it. A: I still believe Pricing Rules is the way to go. Obviously you can't set a condition for each state, as that would result in chaos. What I would suggest is setting up a new table with two columns: State and Discount. Fill the table with the data you need for your project. Set up a new Pricing Rule (Store -> Configuration -> Product pricing Rules -> List -> Add). Skip the Conditions part. In the Actions part, fetch the user's State data and make it available as a variable. Then add a PHP action to query the table for the relevant discount. Use a third action to set the price to the retrieved discount, or if no results were returned, to the original value. It might be good practice to wrap up this logic in a tidy module with the following: * *A UI for managing the discounts table. *A Rules action for querying the table for a given State. *A Rules condition for checking if there is a discount for a given State. (You can then use item #3 above in the conditions of the Pricing Rule, to change the price only if a discount is found.) Hope that helps. Good luck!
doc_23531151
With the following query I can retrieve a list of all the macros in a database: SELECT Name, Type, DateCreate, DateUpdate FROM MsysObjects WHERE (Name Not Like '~*') And (Name Not Like 'MSys*') And Type=-32766 ORDER BY Name; Is there anything like a 'MacroDef' object, similar to TableDef or QueryDef, that could provide further details of a macro? Might there be any profane hidden system table which stored the list of actions in a macro? Thanks a lot for any tip or guidance to move forward on this. A: You may have some luck using the undocumented .SaveAsText method to output the information to a text file, and then read these text files back in using VBA. Try something like: Sub sExportObjects() On Error GoTo E_Handle Dim db As DAO.Database Dim cnt As Container Dim doc As Document Dim strFolder As String strFolder = "J:\downloads\test\" Set db = DBEngine(0)(0) Set cnt = db.Containers("Scripts") For Each doc In cnt.Documents Application.SaveAsText acMacro, doc.name, strFolder & "macro_" & doc.name & ".txt" Next doc sExit: On Error Resume Next Set cnt = Nothing Set db = Nothing Exit Sub E_Handle: MsgBox Err.Description & vbCrLf & vbCrLf & "sExportObjects", vbOKOnly + vbCritical, "Error: " & Err.Number Resume sExit End Sub Regards,
doc_23531152
This is CheckOut Page New items are added from sale page, and then new items are reach in checkout page. But, scrollable is not working in checkout page, if I add new items from sale page. Please help me. THis is checkout page. import 'package:flutter/material.dart'; class CheckOutScreen extends StatefulWidget { // ignore: prefer_typing_uninitialized_variables final cart; // ignore: prefer_typing_uninitialized_variables final sum; const CheckOutScreen({Key? key, this.cart, this.sum}) : super(key: key); @override State<CheckOutScreen> createState() => _CheckOutScreenState(); } class _CheckOutScreenState extends State<CheckOutScreen> { late ScrollController controller; List<String> items = []; @override void initState() { super.initState(); controller = ScrollController()..addListener(_scrollListener); } @override void dispose() { controller.removeListener(_scrollListener); super.dispose(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ ListView.builder( controller: controller, itemCount: widget.cart.length, shrinkWrap: true, itemBuilder: (context, index) { return ListTile( title: Text(widget.cart[index].title), trailing: Text( "${widget.cart[index].price}", style: const TextStyle( color: Colors.redAccent, fontSize: 20, fontWeight: FontWeight.w500), ), onTap: () {}, ); }, // separatorBuilder: (BuildContext context, int index) { // return const Divider(); // }, ), const Divider(), Text("Total : \$${widget.sum}"), ], ); } void _scrollListener() { // ignore: avoid_print print(controller.position.extentAfter); if (controller.position.extentAfter < 500) { setState(() { items.addAll(widget.cart); }); } } } This is sale page. import 'package:akin/model/product.dart'; import 'package:akin/model/table_data.dart'; import 'package:flutter/material.dart'; class AkinItem extends StatelessWidget { final ValueSetter<Product> valueSetter; final TableData data; final List<Product> products; const AkinItem( {Key? key, required this.data, required this.products, required this.valueSetter}) : super(key: key); @override Widget build(BuildContext context) { return ListView.separated( shrinkWrap: true, itemBuilder: ((context, index) { return Card( color: Colors.blueGrey.shade100, elevation: 3.0, child: Padding( padding: const EdgeInsets.all(10.0), child: ListTile( title: RichText( overflow: TextOverflow.ellipsis, text: TextSpan( text: products[index].title, style: TextStyle( color: Colors.blueGrey.shade800, fontWeight: FontWeight.bold, fontSize: 18.0)), ), trailing: Text("${products[index].price} Ks", style: const TextStyle( color: Colors.redAccent, fontSize: 20.0, fontWeight: FontWeight.bold)), onTap: () { valueSetter(products[index]); }, ), ), ); }), separatorBuilder: (context, index) { return const Divider(); }, itemCount: products.length); } } Many items are added in the sale page, this items are showing in checkout page. If above 50 items, show error in ui page. How can I solve this. Please help me. Edited: All Scroll Functions are deleted. And I added new widget in ListView.builder, give new widget as Expanded. All Fine Ok. Thanks for all. A: A ListView widget will always take all the space available. If there are more list items than space available on your device, an error like the one in your screenshot occurs. Try wrapping your ListView in a SizedBox to pass on a specific height. SizedBox( height: 400, ListView( // your ListView code here ), ) If you want to use a height that is dependent on your device size, you can also access the MediaQuery object provided by Flutter.
doc_23531153
I try to run ffmpeg -i input.mp4 -vf frei0r=pixeliz0r output.mp4 I have this error: [Parsed_frei0r_0 @ 0x5585b8093280] Duplicated pixel format Error reinitializing filters! Failed to inject frame into filter network: Invalid argument Error while processing the decoded data for stream #0:0 Conversion failed! I chose --enable-frei0r when I compiled. ffmpeg output: ffmpeg version N-99920-g46e362b765 Copyright (c) 2000-2020 the FFmpeg developers built with gcc 10.2.0 (GCC) configuration: --prefix=/usr --disable-debug --disable-static --disable-stripping --enable-avisynth --enable-fontconfig --enable-gmp --enable-gnutls --enable-gpl --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libdav1d --enable-libdrm --enable-libfreetype --enable-libfribidi --enable-libgsm --enable-libiec61883 --enable-libjack --enable-libmfx --enable-libmodplug --enable-libmp3lame --enable-libopencore_amrnb --enable-libopencore_amrwb --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librav1e --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libssh --enable-libtheora --enable-libv4l2 --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxcb --enable-libxml2 --enable-libxvid --enable-nvdec --enable-nvenc --enable-omx --enable-shared --enable-version3 --enable-frei0r end of the log when the debug is enabled [Parsed_frei0r_0 @ 0x55e92c387280] name:pixeliz0r author:'Gephex crew' explanation:'Pixelize input image.' color_model:packed32 frei0r_version:1 version:1.0 num_params:2 [graph 0 input from stream 0:0 @ 0x55e92c3806c0] Setting 'video_size' to value '640x480' [graph 0 input from stream 0:0 @ 0x55e92c3806c0] Setting 'pix_fmt' to value '13' [graph 0 input from stream 0:0 @ 0x55e92c3806c0] Setting 'time_base' to value '1/15360' [graph 0 input from stream 0:0 @ 0x55e92c3806c0] Setting 'pixel_aspect' to value '0/1' [graph 0 input from stream 0:0 @ 0x55e92c3806c0] Setting 'frame_rate' to value '30/1' [graph 0 input from stream 0:0 @ 0x55e92c3806c0] w:640 h:480 pixfmt:yuvj422p tb:1/15360 fr:30/1 sar:0/1 [format @ 0x55e92c381300] Setting 'pix_fmts' to value 'yuv420p|yuvj420p|yuv422p|yuvj422p|yuv444p|yuvj444p|nv12|nv16|nv21|yuv420p10le|yuv422p10le|yuv444p10le|nv20le|gray|gray10le' [Parsed_frei0r_0 @ 0x55e92c387280] Duplicated pixel format Error reinitializing filters! Failed to inject frame into filter network: Invalid argument Error while processing the decoded data for stream #0:0 [AVIOContext @ 0x55e92c1edf00] Statistics: 0 seeks, 0 writeouts [AVIOContext @ 0x55e92c1e3a40] Statistics: 70706 bytes read, 2 seeks Any ideas how to make it work? A: Looks like vf_frei0r was broken by 69f5f6ea (or rather, it was always a little bit broken, but now there's a check that makes it fail). You can * *File a bug. *Not run git HEAD of ffmpeg — the troublesome commit isn't present in n4.3.1, the latest release.
doc_23531154
class ShoppingListsController < ApplicationController before_action :authenticate_user! def share shopping_list = current_user.shopping_lists.find(params[:id]) user = User.find_by(email: params[:email]) user_list = UserShoppingList.new(user: user, shopping_list: shopping_list) if user_list.save flash[:notice] = "Shopping list has been shared" else flash[:alert] = "Shopping list has not been shared" end redirect_to shopping_lists_path end end How the share spec should look like? I am stuck on this stage, not sure how can I pass here shopping_list_id and what 'expect' should look like require "rails_helper" RSpec.describe ShoppingListsController, type: :request do login_user let (:user) { controller.current_user } let (:shopping_list) { create :shopping_list, user: user } describe 'share shopping list' do it 'let current user share shopping list' do post share_shopping_list_path, params: {email: 'user2@gmail.com'} end Any help would be appreciated :) A: What I like to do is look at the action and pick out what I want to ensure happens, so taking your snippet I'd end up with: - valid shopping list - shopping list is created for the target user - shows a success message - redirects to shopping list index path - invalid shopping list - shows a warning message - redirects to shopping list index path Then we can work this into RSpec by making each top level point a context and each point beneath an expectation: describe 'share shopping list' do let(:params) { { email: 'user2@gmail.com' } } # pass route params like id into path helper here subject { post share_shopping_list_path, params: params } context 'valid shopping list' do before do # set up a valid shopping list end it 'shopping list is created for the target user' do end it 'shows a success message' do end it 'redirects to shopping list index path' do end end context 'invalid shopping list' do before do # setup an invalid shopping list end it 'shows a warning message' do end it 'redirects to shopping list index path' end end end Once you've filled in your expectations, you could consider expanding your test coverage. Perhaps there are multiple cases where you'd expect a shopping list to be invalid (add more contexts) or perhaps you'd like to check the shopping list is created with the same items as the original (add more expectations).
doc_23531155
I've passing AJAX parameters in a maner, but this time my way didn't work. I've asked a friend for help, and he send me another way of sending AJAX data. To my untrained eyes they both work equal. So I don't know why mine does not work: Why? My friend's AJAX: <script> $("#id_shipping_province").change(function () { var val_d = $("#id_shipping_department").val() var val_p = $("#id_shipping_province").val() $.ajax({ url: "/district/?d_name=" + val_d + "&p_name=" + val_p }).done(function (result) { $("#id_shipping_district").html(result); }); }); </script> My AJAX: <script> $("#id_shipping_province").change(function () { var val_d = $("#id_shipping_department").val() var val_p = $("#id_shipping_province").val() $.ajax({ url: "/district/", d_name: val_d, p_name: val_p }).done(function (result) { $("#id_shipping_district").html(result); }); }); }); </script> View def get_district(request): d_name = request.GET.get("d_name") p_name = request.GET.get("p_name") data = Peru.objects.filter(departamento=d_name, provincia=p_name).values_list("distrito", flat=True) # data = Peru.objects.filter(provincia=p_name).values_list("provincia", flat=True) return render(request, "accounts/district_dropdown.html", { "districts": set(list(data)) }) A: You need to pass the the d_name and p_name properties in a separate object specified by data. Currently you're passing them as top level properties of the ajax settings object, which won't have any effect. var val_d = $("#id_shipping_department").val() var val_p = $("#id_shipping_province").val() $.ajax({ url: "/district/", data: { // Pass parameters in separate object d_name: val_d, p_name: val_p }, }).done(function (result) { $("#id_shipping_district").html(result); }); The data object is converted into a query string and appended to the URL. In your friend's case, they are building up the query string manually when they create the URL - hence their version works.
doc_23531156
I cant figure out what is going wrong. I'm using this: <?php session_start(); $_SESSION['isb-vraag1'] = $_POST['isb-vraag1']; $_SESSION['isb-vraag3'] = $_POST['isb-vraag3']; ?> <?php if(isset($_POST['Submitform']) && $_SERVER['REQUEST_METHOD'] == "POST") { $strerror = ""; if(empty($_POST['isb-vraag1'])) { $strerror = $strerror."U dient deze vraag in te vullen<br />"; } if(empty($_POST['isb-vraag2'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag4'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag5'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag6'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag7'])) { $strerror = $strerror."UU dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag8'])) { $strerror = $strerror."UU dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag9'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag10'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag11'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag12'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag13'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag14'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag15'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag16'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag18'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(empty($_POST['isb-vraag19'])) { $strerror = $strerror."U dient deze vraag in te vullen<br/>"; } if(strip_tags($_POST['isb-vraag1']) != $_POST['isb-vraag1'] || strip_tags($_POST['isb-vraag3']) != $_POST['isb-vraag3'] || strip_tags($_POST['isb-vraag4']) != $_POST['isb-vraag4'] || strip_tags($_POST['isb-vraag5']) != $_POST['isb-vraag5'] || strip_tags($_POST['isb-vraag6']) != $_POST['isb-vraag6'] || strip_tags($_POST['isb-vraag7']) != $_POST['isb-vraag7'] || strip_tags($_POST['isb-vraag8']) != $_POST['isb-vraag8'] || strip_tags($_POST['isb-vraag9']) != $_POST['isb-vraag9'] || strip_tags($_POST['isb-vraag10']) != $_POST['isb-vraag10'] || strip_tags($_POST['isb-vraag11']) != $_POST['isb-vraag11'] || strip_tags($_POST['isb-vraag12']) != $_POST['isb-vraag12'] || strip_tags($_POST['isb-vraag13']) != $_POST['isb-vraag13'] || strip_tags($_POST['isb-vraag14']) != $_POST['isb-vraag14'] || strip_tags($_POST['isb-vraag15']) != $_POST['isb-vraag15'] || strip_tags($_POST['isb-vraag16']) != $_POST['isb-vraag16'] || strip_tags($_POST['isb-vraag17']) != $_POST['isb-vraag17'] || strip_tags($_POST['isb-vraag18']) != $_POST['isb-vraag18'] || strip_tags($_POST['isb-vraag19']) != $_POST['isb-vraag19'] || strip_tags($_POST['isb-vraag20']) != $_POST['isb-vraag20'] || strip_tags($_POST['fm-lastname']) != $_POST['fm-lastname'] || strip_tags($_POST['fm-email']) != $_POST['fm-email']) { $$strerror = $strerror."Script is niet toegestaan<br/>"; } if(empty($strerror)) { $to = "test@company.nl"; $subject = "Enquete Comany B.V."; $header = "MIME-Version: 1.0\r\n"; $header .= "Content-type: text/html; charset=iso-8859-1\r\n"; $header .= "From: ".$_POST['fm-email']."\r\n"; $header .= "Reply-To: ".$_POST['fm-email']; $bericht = ' <html> <head> </head> <body style="font-family: Arial;"> <div class="fm-req"> <b><label for="fm-lastname">De volgende enquete is ingevuld door:</label></b><br/> <br/> '.$_POST['fm-lastname'].' </div> <br/> <div class="fm-req"> <b><label for="isb-vraag20">Afzender / Bedrijf:</label></b><br/> <br/> '.$_POST['isb-vraag20'].' </div><br/> <fieldset> <b><legend>De Antwoorden:</legend></b> <br/> <br/> <b><legend>Vraag 1:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag1">Waarom heeft u gekozen voor Company als leverancier?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag1'].'</font> </div> <br/> <b><legend>Vraag 2:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag2">Koopt u ook bij andere leveranciers in de markt?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag2'].'</font> </div> <br/> <b><legend>Vraag 3:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag3">Zo ja? Wat zijn de redenen en wat kunnen wij doen om u beter van dienst te zijn?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag3'].'</font> </div> <br/> <b><legend>Vraag 4:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag4">Wat vindt u van onze telefonische bereikbaarheid?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag4'].'</font> </div> <br/> <b><legend>Vraag 5:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag5">Wat is uw algemene indruk van onze verkoopafdeling?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag5'].'</font> </div> <br/> <b><legend>Vraag 6:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag6">Wat is uw mening over de klantgerichtheid van onze verkoopafdeling?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag6'].'</font> </div> <br/> <b><legend>Vraag 7:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag7">Wat vindt u van onze voorraad A-merken?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag7'].'</font> </div> <br/> <b><legend>Vraag 8:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag8">Wat vindt u van onze voorraad B-merken?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag8'].'</font> </div> <br/> <b><legend>Vraag 9:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag9">Wat vindt u van onze administratieve afhandeling / creditnota afhandeling?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag9'].'</font> </div> <br/> <b><legend>Vraag 10:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag10">Wat vindt u van onze E-commerce website?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag10'].'</font> </div> <br/> <b><legend>Vraag 11:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag11">Wat vindt u van onze bonusshop?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag11'].'</font> </div> <br/> <b><legend>Vraag 12:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag12">Wat vindt u van onze bezoekfrequentie buitendienst medewerkers?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag12'].'</font> </div> <br/> <b><legend>Vraag 13:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag13">Wat vindt u van de kwaliteit van deze bezoeken?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag13'].'</font> </div> <br/> <b><legend>Vraag 14:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag14">Wat vindt u van de productondersteuning?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag14'].'</font> </div> <br/> <b><legend>Vraag 15:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag15">Wat vindt u van onze uitleverprestatie / kwaliteit?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag15'].'</font> </div> <br/> <b><legend>Vraag 16:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag16">Wat vindt u van de Company leveringen</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag16'].'</font> </div> <br/> <b><legend>Vraag 17:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag17">Wat vindt u van de leveringen via Plaats? ( indien van toepassing )</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag17'].'</font> </div> <br/> <b><legend>Vraag 18:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag18">Wat is uw algemene indruk / mening over ons bedrijf?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag18'].'</font> </div> <br/> <b><legend>Vraag 19:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag19">Wat zou u graag veranderd willen zien, in onze organisatie?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag19'].'</font> </div> <br/> </fieldset> <fieldset> <div class="fm-req"> <b><label for="isb-vraag20">Afzender / Bedrijf:</label></b><br/> <br/> '.$_POST['isb-vraag20'].' </div> <br/> <div class="fm-req"> <b><label for="fm-lastname">Ingevuld door:</label></b><br/> <br/> '.$_POST['fm-lastname'].' </div> <br/> <div class="fm-req"> <b><label for="fm-email">E-mail</label></b><br/><br/> '.$_POST['fm-email'].' </div> </fieldset> </body> </html>'; if(mail($to, $subject, $bericht, $header)) { $to2 = $_POST['fm-email']; $subject2 = "Enquete succesvol ingevuld"; $header2 = "MIME-Version: 1.0\r\n"; $header2 .= "Content-type: text/html; charset=iso-8859-1\r\n"; $header2 .= "From: test@company.nl\r\n"; $header2 .= "Reply-To: test@company.nl"; $bericht2 = ' <html> <head> </head> <body style="font-family: Arial;"> Hartelijk dank voor het invullen van deze enquete<br/> <br/> <br/> Met vriendelijke groet,<br/> <br/> <font style="font-weight: Bold">Company B.V.</font><br/> <br/> <br/> Antwoorden:<br/> <br/> <fieldset> <b><legend>De Antwoorden:</legend></b> <br/> <br/> <b><legend>Vraag 1:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag1">Waarom heeft u gekozen voor Company als leverancier?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag1'].'</font> </div> <br/> <b><legend>Vraag 2:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag2">Koopt u ook bij andere leveranciers in de markt?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag2'].'</font> </div> <br/> <b><legend>Vraag 3:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag3">Zo ja? Wat zijn de redenen en wat kunnen wij doen om u beter van dienst te zijn?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag3'].'</font> </div> <br/> <b><legend>Vraag 4:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag4">Wat vindt u van onze telefonische bereikbaarheid?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag4'].'</font> </div> <br/> <b><legend>Vraag 5:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag5">Wat is uw algemene indruk van onze verkoopafdeling?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag5'].'</font> </div> <br/> <b><legend>Vraag 6:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag6">Wat is uw mening over de klantgerichtheid van onze verkoopafdeling?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag6'].'</font> </div> <br/> <b><legend>Vraag 7:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag7">Wat vindt u van onze voorraad A-merken?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag7'].'</font> </div> <br/> <b><legend>Vraag 8:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag8">Wat vindt u van onze voorraad B-merken?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag8'].'</font> </div> <br/> <b><legend>Vraag 9:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag9">Wat vindt u van onze administratieve afhandeling / creditnota afhandeling?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag9'].'</font> </div> <br/> <b><legend>Vraag 10:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag10">Wat vindt u van onze E-commerce website?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag10'].'</font> </div> <br/> <b><legend>Vraag 11:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag11">Wat vindt u van onze bonusshop?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag11'].'</font> </div> <br/> <b><legend>Vraag 12:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag12">Wat vindt u van onze bezoekfrequentie buitendienst medewerkers?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag12'].'</font> </div> <br/> <b><legend>Vraag 13:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag13">Wat vindt u van de kwaliteit van deze bezoeken?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag13'].'</font> </div> <br/> <b><legend>Vraag 14:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag14">Wat vindt u van de productondersteuning?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag14'].'</font> </div> <br/> <b><legend>Vraag 15:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag15">Wat vindt u van onze uitleverprestatie / kwaliteit?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag15'].'</font> </div> <br/> <b><legend>Vraag 16:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag16">Wat vindt u van de company leveringen</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag16'].'</font> </div> <br/> <b><legend>Vraag 17:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag17">Wat vindt u van de leveringen via Plaats? ( indien van toepassing )</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag17'].'</font> </div> <br/> <b><legend>Vraag 18:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag18">Wat is uw algemene indruk / mening over ons bedrijf?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag18'].'</font> </div> <br/> <b><legend>Vraag 19:</legend></b> <br/> <div class="fm-req"> <label for="isb-vraag19">Wat zou u graag veranderd willen zien, in onze organisatie?</label> <br/> <br/> <font color="red">'.$_POST['isb-vraag19'].'</font> </div> <br/> </fieldset> <fieldset> <div class="fm-req"> <b><label for="isb-vraag20">Afzender / Bedrijf:</label></b><br/> <br/> '.$_POST['isb-vraag20'].' </div> <br/> <div class="fm-req"> <b><label for="fm-lastname">Ingevuld door:</label></b><br/> <br/> '.$_POST['fm-lastname'].' </div> <br/> <div class="fm-req"> <b><label for="fm-email">E-mail</label></b><br/><br/> '.$_POST['fm-email'].' </div> </fieldset> </body> </html>'; if(mail($subject2, $bericht2, $header2)) { echo "\t\t\t\t\t<blockquote class=\"goed\">Hartelijk dank voor het invullen van de enquete.<br/></blockquote>\n"; } } else { echo "\t\t\t\t\t<blockquote>Uw enquete is niet correct verzonden, probeer het later opnieuw</blockquote>\n"; } } else { echo "\t\t\t\t\t<blockquote>" . $strerror . "</blockquote>\n"; GetForm(); } } else { GetForm(); } function GetForm() { ?> <form name="aanvraag" method="post" action="index.php?action=checkform"> <fieldset> <div> <img width="300" height="108" alt="Company B.V." src="logogroot.png" style="float:right;"> <p>Geachte relatie, <br/><br/> Company streeft er naar om de service aan haar klanten continu te verbeteren. <br/><br/> Uw mening, als gewaardeerde klant, vinden wij hierin heel belangrijk. <br/> Wat verwacht u van uw bandenleverancier, bent u tevreden of heeft u opbouwende kritiek. Wij vernemen het graag van u. <br/><br/> Wij willen u dan ook vriendelijk verzoeken onderstaande vragen te beantwoorden en het ingevulde formulier </div> </fieldset><br/> <fieldset> <legend>Enquete Company B.V.</legend> <div> <label for="isb-vraag1">Waarom heeft u gekozen voor Company als leverancier?</label><br/> <textarea name="isb-vraag1" value="<?php echo $_SESSION['isb-vraag1'];?>" cols="60" rows="7" id="isb-vraag1"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag1']) == $_POST['isb-vraag1']){ echo $_POST['isb-vraag1']; } ?></textarea> </div><br/> <div> <label for="isb-vraag2">Koopt u ook bij andere leveranciers in de markt?</label> <br/><br/> <input id="isb-vraag2" name="isb-vraag2" type="radio" value="Ja" <?php if(isset($_POST['Submitformk']) && $_POST['isb-vraag2'] == "Ja"){ echo "checked=\"checked\" "; } ?>style="width: 20px;"/> Ja <input name="isb-vraag2" type="radio" value="Nee" <?php if(isset($_POST['Submitformk']) && $_POST['isb-vraag2'] == "Nee"){ echo "checked=\"checked\" "; } ?>style="width: 20px;" /> Nee <br/> <label>&nbsp;</label> </div><br/> <div> <label for="isb-vraag3">Zo ja? Wat zijn de redenen en wat kunnen wij doen om u beter van dienst te zijn?</label><br/><br/> <textarea name="isb-vraag3" value="<?php echo $_SESSION['isb-vraag3'];?>" cols="60" rows="7" id="isb-vraag3"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag3']) == $_POST['isb-vraag3']){ echo $_POST['isb-vraag3']; } ?></textarea> </div><br/> <div> <label for="isb-vraag4">Wat vindt u van onze telefonische bereikbaarheid?</label><br/><br/> <textarea name="isb-vraag4" cols="60" rows="7" id="isb-vraag4"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag4']) == $_POST['isb-vraag4']){ echo $_POST['isb-vraag4']; } ?></textarea> </div><br/> <div> <label for="isb-vraag5">Wat is uw algemene indruk van onze verkoopafdeling?</label><br/><br/> <textarea name="isb-vraag5" cols="60" rows="7" id="isb-vraag5"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag5']) == $_POST['isb-vraag5']){ echo $_POST['isb-vraag5']; } ?></textarea> </div><br/> <div> <label for="isb-vraag6">Wat is uw mening over de klantgerichtheid van onze verkoopafdeling?</label><br/><br/> <textarea name="isb-vraag6" cols="60" rows="7" id="isb-vraag6"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag6']) == $_POST['isb-vraag6']){ echo $_POST['isb-vraag6']; } ?></textarea> </div><br/> <div> <label for="isb-vraag7">Wat vindt u van onze voorraad A-merken?</label><br/><br/> <textarea name="isb-vraag7" cols="60" rows="7" id="isb-vraag7"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag7']) == $_POST['isb-vraag7']){ echo $_POST['isb-vraag7']; } ?></textarea> </div><br/> <div> <label for="isb-vraag8">Wat vindt u van onze voorraad B-merken?</label><br/><br/> <textarea name="isb-vraag8" cols="60" rows="7" id="isb-vraag8"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag8']) == $_POST['isb-vraag8']){ echo $_POST['isb-vraag8']; } ?></textarea> </div><br/> <div> <label for="isb-vraag9">Wat vindt u van onze administratieve afhandeling / creditnota afhandeling?</label><br/><br/> <textarea name="isb-vraag9" cols="60" rows="7" id="isb-vraag9"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag9']) == $_POST['isb-vraag9']){ echo $_POST['isb-vraag9']; } ?></textarea> </div><br/> <div> <label for="isb-vraag10">Wat vindt u van onze E-commerce website?</label><br/><br/> <textarea name="isb-vraag10" cols="60" rows="7" id="isb-vraag10"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag10']) == $_POST['isb-vraag10']){ echo $_POST['isb-vraag10']; } ?></textarea> </div><br/> <div> <label for="isb-vraag11">Wat vindt u van onze bonusshop?</label><br/><br/> <textarea name="isb-vraag11" cols="60" rows="7" id="isb-vraag11"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag11']) == $_POST['isb-vraag11']){ echo $_POST['isb-vraag11']; } ?></textarea> </div><br/> <div> <label for="isb-vraag12">Wat vindt u van onze bezoekfrequentie buitendienst medewerkers?</label><br/><br/> <textarea name="isb-vraag12" cols="60" rows="7" id="isb-vraag12"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag12']) == $_POST['isb-vraag12']){ echo $_POST['isb-vraag12']; } ?></textarea> </div><br/> <div> <label for="isb-vraag13">Wat vindt u van de kwaliteit van deze bezoeken?</label><br/><br/> <textarea name="isb-vraag13" cols="60" rows="7" id="isb-vraag13"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag13']) == $_POST['isb-vraag13']){ echo $_POST['isb-vraag13']; } ?></textarea> </div><br/> <div> <label for="isb-vraag14">Wat vindt u van de productondersteuning?(Zoals folders etc)</label><br/><br/> <textarea name="isb-vraag14" cols="60" rows="7" id="isb-vraag14"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag14']) == $_POST['isb-vraag14']){ echo $_POST['isb-vraag14']; } ?></textarea> </div><br/> <div> <label for="isb-vraag15">Wat vindt u van onze uitleverprestatie / kwaliteit?</label><br/><br/> <textarea name="isb-vraag15" cols="60" rows="7" id="isb-vraag15"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag15']) == $_POST['isb-vraag15']){ echo $_POST['isb-vraag15']; } ?></textarea> </div><br/> <div> <label for="isb-vraag16">Wat vindt u van de "Company" leveringen?</label><br/><br/> <textarea name="isb-vraag16" cols="60" rows="7" id="isb-vraag16"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag16']) == $_POST['isb-vraag16']){ echo $_POST['isb-vraag16']; } ?></textarea> </div><br/> <div> <label for="isb-vraag17">Wat vindt u van de leveringen via Plaats? (indien van toepassing)</label><br/><br/> <textarea name="isb-vraag17" cols="60" rows="7" id="isb-vraag17"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag17']) == $_POST['isb-vraag17']){ echo $_POST['isb-vraag17']; } ?></textarea> </div><br/> <div> <label for="isb-vraag18">Wat is uw algemene indruk / mening over ons bedrijf?</label><br/><br/> <textarea name="isb-vraag18" cols="60" rows="7" id="isb-vraag18"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag18']) == $_POST['isb-vraag18']){ echo $_POST['isb-vraag18']; } ?></textarea> </div><br/> <div> <label for="isb-vraag19">Wat zou u graag veranderd willen zien, in onze organisatie?</label><br/><br/> <textarea name="isb-vraag19" cols="60" rows="7" id="isb-vraag19"><?php if(isset($_POST['Submitformk']) && strip_tags($_POST['isb-vraag19']) == $_POST['isb-vraag19']){ echo $_POST['isb-vraag19']; } ?></textarea> </div><br/> </fieldset> <fieldset> <div> <p>U bent niet verplicht onderstaande bedrijfsgegevens in te vullen. Anoniem deelnemen mag ook. <br/><br/> Wij stellen uw eerlijke antwoorden zeer op prijs en willen u vriendelijk danken voor uw tijd. <br/><br/> Met vriendelijke groet, <br/> Company B.V. <br/><br/><br/> Door u als klant in te vullen. </div><br/> <div> <label for="isb-vraag20">Afzender / Bedrijf:</label><br/><br/> <input name="isb-vraag20" id="isb-vraag19" type="text" value="<?php if(isset($_POST['Submitform']) && strip_tags($_POST['isb-vraag20']) == $_POST['isb-vraag20']){ echo $_POST['isb-vraag20']; } ?>" /> </div><br/> <div> <label for="fm-lastname">Ingevuld door:</label><br/><br/> <input name="fm-lastname" id="fm-lastname" type="text" value="<?php if(isset($_POST['Submitform']) && strip_tags($_POST['fm-lastname']) == $_POST['fm-lastname']){ echo $_POST['fm-lastname']; } ?>" /> </div><br/> <div> <label for="fm-email">E-mail:</label><br/><br/> <input name="fm-email" id="fm-email" type="text" value="<?php if(isset($_POST['Submitformk']) && strip_tags($_POST['fm-email']) == $_POST['fm-email']){ echo $_POST['fm-email']; } ?>" /> </div> </fieldset> <div id="fm-submit"> <input name="Submitform" value="Verstuur" type="submit" /> </div> </form> <?php } ?> And getting this error without submitting: Notice: Undefined index: isb-vraag1 in /company.nl/enquete/index.php on line 4 Can somebody help my out? A: Your error means what it says. :-) $_SESSION['isb-vraag1'] = $_POST['isb-vraag1']; That simply mneans $_POST['isb-vraag1'] is not set. This typically happens the first time you use your script. Try this instead: if (isset($_POST['isb-vraag1'])){ $_SESSION['isb-vraag1'] = $_POST['isb-vraag1']; } else { // do whatever you deem usefull. eg: $_SESSION['isb-vraag1'] = ""; } A: You're trying to assign $_POST variables to $_SESSION variables without checking if they have been set. Use isset() if (isset($_POST['isb_vraag1'])) { $_SESSION['isb-vraag1'] = $_POST['isb-vraag1']; }
doc_23531157
MY HTML <form id="form"> <input class="form-control topSpaceFromRoof" type="text"id="getReminder"/> <p class="text-center"> <input type="submit" value="submit" class="btn btn-default"> </p> </form> <!-- here is the div in which i want to append check boxes --> <div class="checkbox"> </div> MY JAVASCRIPT (function(){ var input = $('#getReminder'); $this = $(this); $( "form" ).submit(function() { if(input.val() == ""){ input.addClass('warning').attr('placeholder','Please set the reminder').addClass('warning-red'); return false; } else { input.removeClass('warning'); $('<label> <input type="checkbox" id="checkboxSuccess" value="option1"> '+ input.val() +' </label>').appendTo('.checkbox'); return true; } }); })(); A: In JavaScript, a new line within a string denotes the start of a new statement. If you want your string to cover multiple lines, you need to escape the carriage return: $('<label>\ <input type="checkbox" id="checkboxSuccess" value="option1">\ '+ input.val() +'\ </label>').appendTo('.checkbox'); Or, concatenate each line: $('<label>' + '<input type="checkbox" id="checkboxSuccess" value="option1">' + input.val() + '</label>').appendTo('.checkbox'); A: else { input.removeClass('warning'); $('.checkbox').append('<label><input type="checkbox" id="checkboxSuccess" value="option1"> ' + input.val() + '</label>'); return true; } I'm not sure .appendTo() is what you want to use here, I would select the element with $(selector) and then use the .append() method to add the next item.
doc_23531158
class ConnectivityMgr @Inject constructor(val context: Context) { fun isConnectedOrConnecting(): Boolean { val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { connMgr.getNetworkCapabilities(connMgr.activeNetwork)?.run { return hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || hasTransport( NetworkCapabilities.TRANSPORT_CELLULAR ) } } else { @Suppress("DEPRECATION") connMgr.activeNetworkInfo?.let { return when (it.type) { ConnectivityManager.TYPE_WIFI -> true ConnectivityManager.TYPE_MOBILE -> true else -> false } } } return false } } A: You can use Roboelectric to test your ConnectivityMgr class. A sample test when the device is connected to WiFi would be like this: fun `should be connected when connected to WiFi`() { val connectivityManager = getApplicationContext<Context>().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkCapabilities = ShadowNetworkCapabilities.newInstance() shadowOf(networkCapabilities).addTransportType(NetworkCapabilities.TRANSPORT_WIFI) shadowOf(connectivityManager).setNetworkCapabilities(connectivityManager.activeNetwork, networkCapabilities) assertTrue(connectivityMgr.isConnectedOrConnecting()) } Roboelectric provides ShadowNetworkCapabilities for fetching and updating transport.
doc_23531159
A: I'm pretty sure the cyber glove you're using comes with an SDK as well as examples on how to get the data from the device. From there, I'm afraid we can't tell you much. I see you tagged your question with "recognition" but what are you trying to recognize exactly? Recognizing gestures would typically mean analyzing a trajectory in 3d space. I've never worked with such a glove but I can imagine it streams a sequence of data the same way a Wacom tablet would stream a sequence of (x,y, pressure) and eventually proximity and pen tilt data. So, you will need to extract pertinent features out of this raw data in order to form what's commonly called a "feature vector". For instance you could resample the data using an interpolation scheme to end up with n tuples, each tuple containing information such as: * *position *orientation *velocity *acceleration *curvature *etc You will have to experiment in order to decide which features are best for the problem you're trying to solve. Once you are able to convert a raw 3d trajectory into a normalized feature vector you will need to make a decision about the method you want to use, for instance: * *example based analysis with a DTW (Dynamic Time Warping) approach *neural network training *support vector machines *there are many!!! Unfortunately, pattern recognition is a vast subject and I can't tell everything about it in such a short answer. It's now up to you to study the literature. Good luck.
doc_23531160
My two questions are: * *Is it correct the state of CPU 2 is I (Invalid) in step 4. *What are the pros and cons of this protocol? Where my current answer for question 2 is: "Pros are you can split the task up in two CPU's and cons is if the data is very dependent on each other this protocol is not useful."
doc_23531161
@facebook_authentication_required The app asks me for permission, and after that the URL is somewhat like: mydomain.com/fblogin?code=somecode But the view for which the decorator was executed did not execute. How do I make the app execute the same view for which it was called? Or how do I parse this URL and call another view if the former is not possible?
doc_23531162
I followed the answer, and tried the following: socket.off('listenerName') to remove all listeners from the listenerName event, but this code gives me an error: (node:27706) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type Function. Received type undefined I am using the latest version (2.3.0) of socket.io. So it looks like, that the socket.off() method needs at least 2 parameters to work, and I have to explicitly tell it which function I want to remove. I tried searching socket.io's documentation to find the definition of this function, but all I found is that the socket inherits every method from the Emiter, including the off() method as well. Does anyone know if there is a function in socket.io, with which I can remove all listeners from a specific event, without explicitly providing it a reference to the originally added function? A: I found the solution in another question. I've managed to remove all the event listeners from the specific event with: socket.removeAllListeners("news");
doc_23531163
A: I test my apps using IIS (localhost). I use to check if the url contained "localhost", later found out about checking window.cordova to determine if the app is running as Cordova App. Example: function isRunningLocalhost() { if (window.cordova) { console.log('runningLocalhost() - False In Cordova'); return false; } else { console.log('runningLocalhost() - True Running Localhost'); return true; } } if (isRunningLocalhost() === true) { //Not running as an APK }
doc_23531164
#!./expect -f set timeout -1 spawn /path/to/command --foo param1 --bar param2 --password expect "Password for baz which is prompted on the console.: " send "pass\r" expect "> " send "print\r" expect "> " send -- "\r" When I run it the output is: spawn /path/to/command --foo param1 --bar param2 --password Password for baz which is prompted on the console.: > print {"stuff"} > > I have some code in a here doc in bash: variable=$(/usr/bin/expect <<HEREKALpxT5KZu set timeout -1 spawn /path/to/command --foo param1 --bar param2 --password expect "Password for baz which is prompted on the console.: " send "pass\r" expect "> " send "print\r" expect "> " send -- "\r" HEREKALpxT5KZu ) I expect this code to produce the exact same output as running the expect file, but the output when I print the variable is: spawn /path/to/command --foo param1 --bar param2 --password Password for baz which is prompted on the console.: > There is no second ">" and no {"stuff"}. It's like the print command is never sent. Also, when I add "interact" at the end, it only works for the expect file, not the here doc.
doc_23531165
WITH A as (select stuff from X), B as (select stuff from Y join X), C as (select stuff from Z join X) Subquery1 Union Subquery2 Union ... Subquery100 I call this package function directly from SSRS using Table(). Everything works fine for a while. However if I run it later in the day I get an error message: ORA-32036: unsupported case for inlining of query name in WITH clauseORA-6512: at "[function name]" However if I open Oracle SQLDeveloper, and run the function then come back to SSRS, everthing runs fine (for a while). I realize it is probably getting angry at my nested WITH clauses, but what would cause it to work for a while, then fail soon after? Note it always works in SQLDeveloper. Thanks in advance for your assistance! A: Your issue is that the version of the client (or possibly the driver within your client) you are connecting to Oracle with (inside SSRS) probably doesn't support function calls within a WITH clause. In the 9i client, the WITH clause was not fully functional and I suspectwhichever client is connecting to Oracle (even if it's not the 9i client) is still not fully functional. You'll have to either: 1) Upgrade the Oracle client (or driver) within SSRS (if that's even possible) 2) Upgrade your version of SSRS (if it's not the latest, but check it is worthwhile doing the upgrade first) 3) Re-write your query without the WITH clauses and use inline views instead. Another option would be to create DB views of the data needed and reference them in your select statement, not ideal but possibly an option. Hope it helps... A: I had the same problem and solve it by adding pragma autonomous_transaction; to the function..e.g: create or replace function myfunction() return varchar2 is pragma autonomous_transaction; begin --Your code here commit;---> don't forget the commit or else won't work return 'result' end; Just use it if your function doesn't manipulate with data. A: Perhaps Jeff implied this earlier, however I did get this to work by containing the oracle query by using OPENQUERY().Curiously though I still have to run the query once after all changes for it to work, but I no longer have to run it before I need to run the report. Thanks all again for your help! A: I was using another BI tool but got the same error. Found a good solution that worked for me by adding DistribTx=0 to a connection string. Credit goes to Sean commented on this post https://orastory.wordpress.com/2007/09/20/one-of-those-weird-ones-ora-32036/#comment-9164 The issue is still not fixed by Oracle as of 11g r2 A: In SSRS, I am connected directly to my Oracle 10g database using the Oracle driver. I have found that this driver has the following limitations: * *A single WITH subquery cannot be referenced more than once in a query, even though SQL Developer let you "cheat" and get away with this. *I will get error ORA-32036 if I try to execute a query in SSRS with more than two WITH subqueries, i.e. WITH A AS (...), B AS (...) SELECT ... FROM A, B ..., even though in SQL Developer I can use as many WITHs as I like. So another suggestion is to try to rewrite your query to use no more than two WITH subqueries.
doc_23531166
** (gvim:13790): CRITICAL **: murrine_style_draw_box: assertion 'height >= -1' failed Why do I get this warning and how do I get rid of it? The installation (via software center) is pretty much unmodified, except the addition of ~/.vimrc: source $VIMRUNTIME/mswin.vim behave mswin set hls A: It's a bug in the theme package(s). Resolution here: https://bugs.launchpad.net/ubuntu/+source/light-themes/+bug/538499/comments/24 Modify the entry in /usr/share/themes/YOUR THEME IN USE/gtk-2.0/gtkrc from GtkRange::trough-under-steppers = 0 to GtkRange::trough-under-steppers = 1 HTH
doc_23531167
I am trying to "Upload a file" in the first instance using the POST operation and passing the json with the source url to the endpoint as specified. I can use other methods just fine but since there is little in the way or error feedback I am stuck I keep getting error 404 I have used - https://developers.podio.com/doc/files/upload-file-1004361 (have tried both GET & POST) image of method with error i get A: Upload file method that you are trying to use (https://developers.podio.com/doc/files/upload-file-1004361) is expecting file path which is supposed to be local file but not url. Here is example of how it should be used: http://podio.github.io/podio-php/api-requests/ $file = PodioFile::upload($path_to_file, $filename_to_display); print 'File uploaded. The file id is: '.$file->id; Here is another example on how to work with files: https://developers.podio.com/examples/files
doc_23531168
<html> <head> <body> <span style="z-index:50;font-size:0.9em;"> <img src="https://theysaidso.com/branding/theysaidso.png" height="20" width="20" alt="theysaidso.com"/> <a href="https://theysaidso.com" title="Powered by quotes from theysaidso.com" style="color: #9fcc25; margin-left: 4px; vertical-align: middle;"> theysaidso.com</a></span> <?php $service_url = 'http://quotes.rest/qod.json'; $curl = curl_init($service_url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $curl_response = curl_exec($curl); curl_close($curl); $json_objekat=json_decode($curl_response); echo $json_objekat->contents->quotes->quote.'<br>'; echo $json_objekat->contents->quotes->author.'<br>'; ?> </body> </head> This code is saved as php file in my root directory on WAMP server. I use WAMP server. And it is written on this website http://quotes.rest/qod.json that you must insert this html too. When I open this php page on WAMP it shows alert: Notice: Undefined property: stdClass::$contents in C:\wamp\www\IzdavackaKuca\javniServis.php on line 18 Notice: Trying to get property of non-object in C:\wamp\www\IzdavackaKuca\javniServis.php on line 18 Notice: Trying to get property of non-object in C:\wamp\www\IzdavackaKuca\javniServis.php on line 18 Notice: Undefined property: stdClass::$contents in C:\wamp\www\IzdavackaKuca\javniServis.php on line 19 Notice: Trying to get property of non-object in C:\wamp\www\IzdavackaKuca\javniServis.php on line 19 Notice: Trying to get property of non-object in C:\wamp\www\IzdavackaKuca\javniServis.php on line 19 JSON on this link http://quotes.rest/qod.json looks like this: { "success": { "total": 1 }, "contents": { "quotes": [ { "quote": "A loser doesn't know what he'll do if he loses, but talks about what he'll do if he wins, and a winner doesn't talk about what he'll do if he wins, but knows what he'll do if he loses.", "length": "184", "author": null, "tags": [ "failure", "inspire", "knowledge", "winning" ], "category": "inspire", "date": "2016-05-11", "title": "Inspiring Quote of the day", "background": "https://theysaidso.com/img/bgs/man_on_the_mountain.jpg", "id": "KhjRMynny89MKxcGkEKF_QeF" } ] } } When I change last two lines in php to this: echo $json_objekat['contents']['quotes']['quote'].'<br>'; echo $json_objekat['contents']['quotes']['author'].'<br>'; it alerts: Fatal error: Cannot use object of type stdClass as array in C:\wamp\www\IzdavackaKuca\javniServis.php on line 18 I realy don`t know how to call this server, when I code: <?php $defaults = array( CURLOPT_URL => 'http://quotes.rest/qod.json', CURLOPT_POST => false, CURLOPT_HEADER => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYHOST => false, ); $curl = curl_init(); curl_setopt_array($curl, $defaults); $curl_response = curl_exec($curl); $json_objekat = json_decode($curl_response); // DUMP THE CURL-ERROR INFORMATION: var_dump(curl_error($curl)); curl_close($curl); ?> it alerts: string '' (length=0) Please help! A: The issue is because you are accesing quote and author incorrectly. Output of print_r($json_objekat) says that: contents is stdClass Object quotes is array again quotes is having 0 as index which is again stdClass Object So, try accessing quote and author as follows: $json_objekat->contents->quotes[0]->quote $json_objekat->contents->quotes[0]->author A: I am assuming this is what you intend to do: <?php $service_url = 'http://quotes.rest/qod.json'; $curl = curl_init($service_url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $curl_response = curl_exec($curl); curl_close($curl); $json_objekat = json_decode($curl_response); $quotes = $json_objekat->contents->quotes; foreach($quotes as $intKey=>$objQuote){ echo $objQuote->title . '<br>'; echo $objQuote->author . '<br>'; echo $objQuote->quote . '<br>'; echo $objQuote->background . '<br>'; } ?> But be aware that you cannot make more than 10 Request per Hour using the same IP Address. So once you make up to 10 Requests, you'd be blocked and you have to wait for another 1 Hour to continue with your Requests. Hope this helps...... A: <?php $conn = mysqli_connect("localhost","root","","mydatabase"); if(!$conn){ die("Connection failed: " . mysqli_connect_error()); } if(!function_exists("curl_init")) die("cURL extension is not installed"); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "http://localhost/ketan/all_user.php"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); echo $result; //print_r(json_decode($result));//To Decode Result ?> Output all_user.php <?php $conn = mysqli_connect("localhost","root","","mydatabase"); if(!$conn){ die("Connection failed: " . mysqli_connect_error()); } $result = mysqli_query($conn,"SELECT * FROM tblUser"); $data = array(); while ($row = mysqli_fetch_array($result)) { /*$result = array(); $result['userId'] = $row['userId']; $result['firstName'] = $row['firstName']; $result['lastName'] = $row['lastName'];*/ array_push($data, array('userId'=> $row['userId'],'firstName'=> $row['firstName'], 'lastName'=>$row['lastName'], 'email'=>$row['email'], 'phoneNumber'=>$row['phoneNumber'], 'userImage'=>"user_images/".$row['userImage'])); } $return['status'] = true; $return['message'] = 'Success'; $return['data'] = $data; header('Content-Type: application/json'); echo json_encode($return, JSON_PRETTY_PRINT); $conn->close(); ?>
doc_23531169
peak = max(cell[750:791]) Now I want to have the index of this specific peak value but only in the same time window. I tried: idx_peak = np.where(cell[750:791] == peak) But this seems to give me all the indices from the entire array. How can I apply np.where in my specific time window? I hope my question is clear. A: Just use idx_peak = cell[750:791].argmax()
doc_23531170
A: Using DataTable.ColumnChanged Event, make a change, press TAB or ENTER to get original and proposed value. In the following example we first subscribe to the DataTable ColumnChanged event someDataTable.ColumnChanged += ColumnChanged; Then, in this case show values to Visual Studio output window public void ColumnChanged(object sender, DataColumnChangeEventArgs e) { Console.WriteLine($" Column name {e.Column.ColumnName}"); Console.WriteLine($" Original value [{e.Row[e.Column.ColumnName, DataRowVersion.Original]}]"); Console.WriteLine($" Propose value [{e.ProposedValue}]"); } Or be selective public void ColumnChanged(object sender, DataColumnChangeEventArgs e) { if ( e.Row.RowState == DataRowState.Deleted || e.Row.RowState == DataRowState.Detached || e.Row.RowState == DataRowState.Added) return; Console.WriteLine($" Column name {e.Column.ColumnName}"); Console.WriteLine($" Original value [{e.Row[e.Column.ColumnName, DataRowVersion.Original]}]"); Console.WriteLine($" Propose value [{e.ProposedValue}]"); }
doc_23531171
var getPage = function () { var $a = $(this); GetTabData(a); return false; } and finally I'm sending pagenumber to the next function which sends pagenumber together with activeTab variable to the controller function GetTabData(xdata, pageNumber) { $.ajax({ url: ('/Home/GetTabData'), type: 'POST', contentType: 'application/json', dataType: 'html', data: JSON.stringify({ activeTab: xdata, page: pageNumber }), success: function (result) { $("[id^='tab-'] div").remove(); var currentTab = $("#tab-" + xdata).html(result); }, error: function () { alert("error"); } }); } Something is definit. wrong here cause on controller side I'm using Request.IsAjaxRequest() to allow only ajax request to paginate data and I'm getting Not ajax request. Once more, If I remove pagination option completly and send just activeTab everything works. Any thoughts? A: Your GetTabData function takes 2 arguments: xdata and pageNumber but when calling it you are passing only one: var $a = $(this); GetTabData(a); So you probably are getting a javascript error and the return false statement is never reached.
doc_23531172
I have read and completed the tutorials at the following sites:Whatsmyipadress, w3schools, tutorialspoint, and how stuff works. From what I understand, cookies work like: * *client visits site, *site requests cookie, *if cookie does not exist, site creates cookie, I found this example and tried to use but everyone has the same name and value: When I ran tests with different users, everyone returned the same combo name:bob Am I supposed to randomly assign a value? The first link says that users would need to complete a registration-type page and then server would use the info to create an id. This is similar to the tutorial on schools (except their example uses a popup). Is this what I need to do as well? How are cookies made unique ? From my experience, I wouldn’t be able to personalize any experience because everyone would have the same name/value pair. A: Cookies are specific to a particular domain, and can also be made specific to subdomains and/or subdirectories within a domain. So there's no conflict between cookies with the same name from different web sites, and you don't have to worry about making your cookies unique (except among all the cookies used by your own site). Each domain can only see and modify its own cookies. Cookies are also specific to a particular client browser. When you send or get a cookie from one user, it has no effect on cookies from a different user.
doc_23531173
./gradlew :app:dependencies > output_file.txt and it is a very long file. and Is there any command that will only show me with compose as the library?
doc_23531174
Here are the codes that I used: public class ExisActivity extends AppCompatActivity { private DatabaseReference mdatabase; private ListView mListView; private ArrayList<String> marralist = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exis); mdatabase = FirebaseDatabase.getInstance().getReference(); mListView = (ListView)findViewById(R.id.lvexist); final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,marralist); mListView.setAdapter(arrayAdapter); } } and this is the other code that i used to get the data: public class SaveData { public String getEtOwnername() { return etOwnername; } public void setEtOwnername(String etOwnername) { this.etOwnername = etOwnername; } public String getEtAnimalname() { return etAnimalname; } public void setEtAnimalname(String etAnimalname) { this.etAnimalname = etAnimalname; } public String getEtAddress() { return etAddress; } public void setEtAddress(String etAddress) { this.etAddress = etAddress; } public String getEtContactNo() { return etContactNo; } public void setEtContactNo(String etContactNo) { this.etContactNo = etContactNo; } public String getEtDobAge() { return etDobAge; } public void setEtDobAge(String etDobAge) { this.etDobAge = etDobAge; } public String getEtEmail() { return etEmail; } public void setEtEmail(String etEmail) { this.etEmail = etEmail; } public String getEtClinicalNotes() { return etClinicalNotes; } public void setEtClinicalNotes(String etClinicalNotes) { this.etClinicalNotes = etClinicalNotes; } public String getEtMedication() { return etMedication; } public void setEtMedication(String etMedication) { this.etMedication = etMedication; } public String getEtPayMent() { return etPayMent; } public void setEtPayMent(String etPayMent) { this.etPayMent = etPayMent; } public SaveData(String etOwnername, String etAnimalname, String etAddress, String etContactNo, String etDobAge, String etEmail, String etClinicalNotes, String etMedication, String etPayMent) { this.etOwnername = etOwnername; this.etAnimalname = etAnimalname; this.etAddress = etAddress; this.etContactNo = etContactNo; this.etDobAge = etDobAge; this.etEmail = etEmail; this.etClinicalNotes = etClinicalNotes; this.etMedication = etMedication; this.etPayMent = etPayMent; } this is my DB structure of my fire base i'm also new to fire base { "rules":{ ".read": true, ".write": true, } } Can any help me? please provide some link PLEASE RESPECT MY POST
doc_23531175
I have not found a way to make VSCode clear the terminal -- it is possible to clear the panel in tasks.json with the clear: true property, this however only works for tasks such as the build task but has no effect on the debug panel. Help is greatly appreciated. Thanks in advance -Simon A: There is a new setting due in v1.55: debug.terminal.clearBeforeReusing Some debug extension allow to launch debuggees in VS Code's integrated terminal. In order keep the number of integrated terminals small, VS Code tries to reuse a terminal if it is not blocked by a still running command. A consequence of this approach is that previous commands and program output will remain visible in the terminal which is sometimes confusing. In this release we've introduced a new feature to automatically clear the integrated terminal before starting a new debug session. The feature is controlled by the new setting debug.terminal.clearBeforeReusing. from https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_55.md#new-setting-for-clearing-a-terminal-before-launching-a-debuggee A: this however only works for tasks such as the build task but has no effect on the debug panel. The 'Debug Console' should be new text every session. If you would like to redirect the terminal output to the Debug Console you can use the following properties for your launch.json file: internalConsoleOptions Controls when the internal debug console should open. redirectOutput "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "internalConsoleOptions": "openOnSessionStart", "redirectOutput": true } ] Both of these used in tandem will open the 'Debug Console' instead of terminal and just provide the necessary output; though it still sends to terminal should you still want it: Another option is to not use the terminal at all: "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "internalConsole", } ] Meaning, it does not send to (or use) your integrated terminal at all and only opens the Debug Console, which doesn't show any cd like statements or executable overhead and no previous history Shorcuts (definitely not as user friendly): Terminal: Relaunch Active Terminal CommandId: workbench.action.terminal.relaunch Terminal: Clear CommandId: workbench.action.terminal.clear These options don't answer the question "how to clear the terminal when debug starts", but options for those new to vscode to consider as alternatives. I'm not so sure they feel the terminal is appropriate for debugging, because we have a debug console and debug/run panel. The reason this can be complicated is because extensions use their own output channels for debugging. For example, the python uses a completely different terminal than say Code Runner. Same for javascript and then there is native support. A: You can clear the terminal using a preLaunchTask: launch.json: { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch via NPM", "preLaunchTask": "Clear terminal", "runtimeVersion": "15.14.0", "runtimeExecutable": "npm", "runtimeArgs": ["run", "start"], "skipFiles": ["<node_internals>/**"], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", } ] } tasks.json: { "version": "2.0.0", "tasks": [ { "label": "Clear terminal", "command": "echo ${command:workbench.action.terminal.clear}" } ] } There is one caveat though: it will clear the active terminal. So if you switched to a different terminal after completing the task, this will clear that terminal instead... I have not found a way to target a specific terminal window, and I don't think it's possible.
doc_23531176
ERROR: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. ALTER PROCEDURE [dbo].[insertData] @Value insertTbl READONLY, @Result INT OUTPUT AS BEGIN BEGIN TRY IF (SELECT COUNT(Id) FROM @Values WHERE Id IN (SELECT Id FROM [dbo].[username])) = 0 BEGIN INSERT INTO dbo.username ( Id, NAME ) SELECT Id, NAME FROM @Values WHERE Id NOT IN (SELECT Id FROM [dbo].[username]) SELECT @Result = 101 END ELSE SELECT @Result = ( SELECT Id FROM @Values WHERE Id IN (SELECT Id FROM [dbo].[username]) ) END TRY BEGIN CATCH SELECT ERROR_MESSAGE() END CATCH END A: Please try this. I have changed the return type to VARCHAR. That would return a CSV (e.g. 1,3,9...) The other option is to return a result set. For this replace SELECT @Result = to INSERT INTO @Result... Hope this helps. ALTER PROCEDURE [dbo].[insertData] @Value insertTbl READONLY, @Result VARCHAR(500) OUTPUT AS BEGIN BEGIN TRY IF (SELECT COUNT(Id) FROM @Values WHERE Id IN (SELECT Id FROM [dbo].[username]) ) = 0 BEGIN INSERT INTO dbo.username (Id,NAME) SELECT Id, NAME FROM @Values WHERE Id NOT IN (SELECT Id FROM [dbo].[username]) SELECT @Result = 101 END ELSE BEGIN SELECT @Result = (SELECT STUFF((SELECT ', ' + CAST(ID AS VARCHAR(5)) FROM @Values WHERE Id IN (SELECT Id FROM [dbo].[username]) ORDER BY Id FOR XML PATH('')),1,2,'')) END END TRY BEGIN CATCH SELECT ERROR_MESSAGE() END CATCH END A: Probably this line SELECT @Result=(SELECT Id FROM @Values WHERE Id IN (SELECT Id FROM [dbo].[username])) return more than one row. You should change the query to return only one value as below SELECT @Result=(SELECT top 1 Id FROM @Values WHERE Id IN (SELECT Id FROM [dbo].[username])) or you should change your logic. Alternative way is to use temprary table to return listo of ID. Try below solution -- create temporary table before (!) creating procedure create table #Resulttab ( Result int ) go ALTER PROCEDURE [dbo].[insertData] @Value insertTbl READONLY, @Result INT OUTPUT -- in this solution I think you don't need this parameter AS BEGIN BEGIN TRY IF (SELECT COUNT(Id) FROM @Values WHERE Id IN (SELECT Id FROM [dbo].[username])) = 0 BEGIN INSERT INTO dbo.username ( Id, NAME ) SELECT Id, NAME FROM @Values WHERE Id NOT IN (SELECT Id FROM [dbo].[username]) SELECT @Result = 101 END ELSE insert into #Resulttab SELECT Id FROM @Values WHERE Id IN (SELECT Id FROM [dbo].[username]) END TRY BEGIN CATCH SELECT ERROR_MESSAGE() END CATCH END go You can use it that way: -- create temporary table before run procedure create table #Resulttab ( Result int ) -- run procedure with parameters exec insertData ... --after run procedure you can check list of your IDs select Result from #Resulttab
doc_23531177
Here is my code: public interface GenericDAO <E, K> { public void save(E entity); public List<E> findAll(); public void update(E entity); public void delete(E entity); public E find(K key); } @Transactional @Repository public abstract class GenericDAOImpl<E, K extends Serializable> implements GenericDAO<E, K>{ @Autowired private SessionFactory sessionFactory; protected Class<? extends E> daoType; public GenericDAOImpl() { Type type = getClass().getGenericSuperclass(); ParameterizedType parameterizedType = (ParameterizedType) type; } protected Session currentSession(){ return sessionFactory.getCurrentSession(); } @Override public void save(E entity) { currentSession().save(entity); } @SuppressWarnings("deprecation") @Override public List<E> findAll() { return currentSession().createCriteria(daoType).list(); } @Override public void update(E entity) { currentSession().saveOrUpdate(entity); } @Override public void delete(E entity) { currentSession().delete(entity); } @Override public E find(K key) { return (E)currentSession().get(daoType, key); } } public interface GenericService <E, K>{ public void save(E entity); public List<E> findAll(); public void update(E entity); public void delete(E entity); public E find(K key); } @Service public abstract class GenericServiceImpl<E, K> implements GenericService<E, K> { private GenericDAO<E, K> genericDAO; public GenericServiceImpl() { } public GenericServiceImpl(GenericDAO<E, K> genericDAO){ this.genericDAO = genericDAO; } @Override @Transactional(propagation = Propagation.REQUIRED) public void save(E entity) { genericDAO.save(entity); } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = true) public List<E> findAll() { return genericDAO.findAll(); } @Override @Transactional public void update(E entity) { genericDAO.update(entity); } @Override @Transactional public void delete(E entity) { genericDAO.delete(entity); } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = true) public E find(K key){ return genericDAO.find(key); } } public interface MoviesDAO extends GenericDAO<Movies, Integer> { } @Transactional @Repository public class MoviesDAOImpl extends GenericDAOImpl<Movies, Integer> implements MoviesDAO{ } public interface MoviesService extends GenericService<Movies, Integer>{ } @Service public class MoviesServiceImpl extends GenericServiceImpl<Movies, Integer> implements MoviesService{ } @Controller public class MoviesController { @Autowired(required = true) MoviesService moviesService; @RequestMapping("/movies") public String returnMovies(Model model){ model.addAttribute("movies", new Movies()); model.addAttribute("listMovies", moviesService.find(1)); return "movies"; } } The error that appears is: java.lang.NullPointerException com.project.movies.service.impl.GenericServiceImpl.find(GenericServiceImpl.java:51) com.project.movies.controller.MoviesController.returnMovies(MoviesController.java:21) context.xml <tx:annotation-driven transaction-manager="transactionManager"/> <mvc:annotation-driven/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/DataBaseBD" /> <property name="username" value="user"/> <property name="password" value="password"/> </bean> <bean id="hibernate5AnnotatedSessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="annotatedClasses"> <list> <value>com.project.movies.model.Movies</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" /> </bean> A: You service is null, add the bean definition for your service with your full qualified name of the MoviesServiceImpl. .... <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/DataBaseBD" /> <property name="username" value="user"/> <property name="password" value="password"/> </bean> <bean id="moviesService" class="your.class.package.MoviesServiceImpl" parent="GenericService" /> ....
doc_23531178
A: You could try this array formula that returns unique text or numbers from a rectangular range. * *Select a range to output the results to eg: H1:H245 *Copy and paste the formula below into the formula bar. *Press Ctrl+Shift+Enter to enter into the range. =IFERROR(CELL("Contents",INDIRECT(T(IF(1,TEXT(MODE.MULT(IF(FREQUENCY(COUNTIF(B1:F49,"<="&B1:F49)+ISTEXT(B1:F49)*COUNT(B1:F49),COUNTIF(B1:F49,"<="&B1:F49)+ISTEXT(B1:F49)*COUNT(B1:F49))>={1,1},MODE.MULT(10^5*ROW(B1:F49)+COLUMN(B1:F49),10^5*ROW(B1:F49)+COLUMN(B1:F49)))),"r0c00000"))),0)),"") A: I'd probably put this formula in column C: (or another empty column you have): (so starting in cell C1: ) =COUNTIF(B:B,B1)=1 (and copy/paste the formula down) It will return TRUE if it is unique. So you can then filter things out via Filter, or with other formulas down the road. A: It may be easiest to just combine your information into one long column and run a remove duplicates. If this is not an option you may want to look at writing a macro to crawl through the records. You could have a macro go through each column for the rows specified and determine if the CountIf function =COUNTIF(B2:F49,B2) returns a value >1 if it does there are at least 2 instances of this number. I'm not sure how you want to identify your unique cells but you could potentially set a text color or return the values of the cell to another location. A: Simplest for identification of values unique within the entire array may be to highlight the entire range with ‘standard’ formatting of choice for uniques, then select the entire range, Conditional Formatting, Highlight Cell Rules, Duplicate Values…, and choose a custom format of no fill and font of whatever you started with.
doc_23531179
import com.atlanticpkg.controller.ejb.ContactsFacade; import com.atlanticpkg.model.entities.Contacts; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.enterprise.context.SessionScoped; import javax.inject.Named; @Named(value = "contactsBean") @SessionScoped public class ContactsBean implements Serializable { @EJB ContactsFacade contactsEJB; private List<Contacts> contacts = new ArrayList<Contacts>(); private int page = 0; private int contactsRecords; private boolean previousDisabled = false; private int firstItem = 0; private int batchSize = 5; public ContactsBean() { } @PostConstruct public void onLoad() { contactsRecords = contactsEJB.count(); updateContactsList(); } public void updateContactsList() { if (firstItem <= 0) { previousDisabled = true; } if (firstItem > 0) { previousDisabled = false; } contacts = contactsEJB.findRange(firstItem, batchSize); } public void next() { if (firstItem + batchSize < contactsRecords) { firstItem += batchSize; } updateContactsList(); } public void previous() { if (firstItem > 0) { firstItem -= batchSize; } updateContactsList(); } /** * @return the contacts */ public List<Contacts> getContacts() { return contacts; } /** * @param contacts the contacts to set */ public void setContacts(List<Contacts> contacts) { this.contacts = contacts; } /** * @return the contactsRecords */ public int getContactsRecords() { return contactsRecords; } /** * @param contactsRecords the contactsRecords to set */ public void setContactsRecords(int contactsRecords) { this.contactsRecords = contactsRecords; } /** * @return the page */ public int getPage() { return page; } /** * @return the previousDisabled */ public boolean isPreviousDisabled() { return previousDisabled; } /** * @param previousDisabled the previousDisabled to set */ public void setPreviousDisabled(boolean previousDisabled) { this.previousDisabled = previousDisabled; } /** * @return the firstItem */ public int getFirstItem() { return firstItem; } /** * @param firstItem the firstItem to set */ public void setFirstItem(int firstItem) { this.firstItem = firstItem; } /** * @return the batchSize */ public int getBatchSize() { return batchSize; } /** * @param batchSize the batchSize to set */ public void setBatchSize(int batchSize) { this.batchSize = batchSize; } } index.xhtml <h:form> <h:panelGroup id="contactsPanel"> <h:dataTable id="contactsTable" value="#{contactsBean.contacts}" var="contacts"> <h:column> <f:facet name="header"> <h:outputText value="Name"/> </f:facet> <h:outputText value="#{contacts.name}"/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Street"/> </f:facet> <h:outputText value="#{contacts.street}"/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="City"/> </f:facet> <h:outputText value="#{contacts.city}"/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="State"/> </f:facet> <h:outputText value="#{contacts.state}"/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Zip"/> </f:facet> <h:outputText value="#{contacts.zip}"/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Country"/> </f:facet> <h:outputText value="#{contacts.country}"/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Sent?"/> </f:facet> <h:selectBooleanCheckbox value="#{contacts.sent}" /> </h:column> </h:dataTable> <h:outputText value="#{contactsBean.contactsRecords}" /> <h:commandLink disabled="#{contactsBean.previousDisabled}" value="&lt; previous" action="#{contactsBean.previous}"> <f:ajax execute="@form" render="contactsPanel"/> </h:commandLink> <h:commandLink value="next &gt;" action="#{contactsBean.next}"> <f:ajax execute="@form" render="contactsPanel"/> </h:commandLink> </h:panelGroup> </h:form> I'm not sure why this doesn't work. Technically the page is not refreshing so I should be able to use request scope right? Thanks. A: What may be a little more appropriate is ViewScoped, see an article by Balusc: http://balusc.blogspot.com/2010/06/benefits-and-pitfalls-of-viewscoped.html A: RequestScope means the bean is instantiated each time a request is sent to it. That includes an ajax request.
doc_23531180
class Student { public $id; public $name; public function setById($id) { ... // PDO $stmt // Manual casting works fine but not easy to maintain // $student = $stmt->fetchObject(); // $this->id = $student->id; // $this->name = $student->name; // So, I'm trying to do auto cast, but $this cannot be re-assign. $stmt->setFetchMode(PDO::FETCH_CLASS, 'Student'); $this = $stmt->fetch(); // Error: Cannot re-assign $this } } Is there any native syntax to do this or it should be done by custom function?
doc_23531181
My configuration of Google Authentication is OK and I can successfully login into my application with it. I store the context.AccessToken as a Claim in the authentication callback (OnAuthenticated "event" of GoogleOAuth2AuthenticationProvider). My Startup.Auth.cs configuration (app.UseGoogleAuthentication(ConfigureGooglePlus())) private GoogleOAuth2AuthenticationOptions ConfigureGooglePlus() { var goolePlusOptions = new GoogleOAuth2AuthenticationOptions() { ClientId = "Xxxxxxx.apps.googleusercontent.com", ClientSecret = "YYYYYYzzzzzz", Provider = new GoogleOAuth2AuthenticationProvider() { OnAuthenticated = context => { context.Identity.AddClaim(new System.Security.Claims.Claim("Google_AccessToken", context.AccessToken)); return Task.FromResult(0); } }, SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie }; goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/plus.login"); goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.email"); return goolePlusOptions; } The code in which the exception is throwed (Execute() method) var externalIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie); var accessTokenClaim = externalIdentity.FindAll(loginProvider + "_AccessToken").First(); var secrets = new ClientSecrets() { ClientId = "Xxxxxxx.apps.googleusercontent.com", ClientSecret = "YYYYYYzzzzzz" }; IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = new[] { PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail } }); UserCredential credential = new UserCredential(flow, "me", new TokenResponse() { AccessToken = accessTokenClaim.Value }); var ps = new PlusService( new BaseClientService.Initializer() { ApplicationName = "My App Name", HttpClientInitializer = credential }); var k = ps.People.List("me", PeopleResource.ListRequest.CollectionEnum.Visible).Execute(); Is there another way to get the original AccessToken or refresh it without pass thru the entire authentication process (the user is already authenticated)? I need to query some GooglePlus profile data such as GivenName, familyName, gender, profile picture and profile url. A: Linda helped me with an URL pointing to a new asp.net mvc sample (https://codereview.appspot.com/194980043/). I just had to add AccessType = "offline" to GoogleOAuth2AuthenticationOptions and save some extra info to create a new instance of TokenResponse when I need. Google Authentication Options private GoogleOAuth2AuthenticationOptions ConfigureGooglePlus() { var goolePlusOptions = new GoogleOAuth2AuthenticationOptions() { AccessType = "offline", ClientId = "Xxxxxxx.apps.googleusercontent.com", ClientSecret = "Yyyyyyyyyy", Provider = new GoogleOAuth2AuthenticationProvider() { OnAuthenticated = context => { context.Identity.AddClaim(new System.Security.Claims.Claim("Google_AccessToken", context.AccessToken)); if (context.RefreshToken != null) { context.Identity.AddClaim(new Claim("GoogleRefreshToken", context.RefreshToken)); } context.Identity.AddClaim(new Claim("GoogleUserId", context.Id)); context.Identity.AddClaim(new Claim("GoogleTokenIssuedAt", DateTime.Now.ToBinary().ToString())); var expiresInSec = (long)(context.ExpiresIn.Value.TotalSeconds); context.Identity.AddClaim(new Claim("GoogleTokenExpiresIn", expiresInSec.ToString())); return Task.FromResult(0); } }, SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie }; goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/plus.login"); goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/plus.me"); goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.email"); return goolePlusOptions; } How to retrieve the credentials (using token info "stored" as claim) private async Task<UserCredential> GetCredentialForApiAsync() { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = "Xxxxxxxxx.apps.googleusercontent.com", ClientSecret = "YYyyyyyyyyy", }, Scopes = new[] { "https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email" } }; var flow = new GoogleAuthorizationCodeFlow(initializer); var identity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ApplicationCookie); var userId = identity.FindFirstValue("GoogleUserId"); var token = new TokenResponse() { AccessToken = identity.FindFirstValue("Google_AccessToken"), RefreshToken = identity.FindFirstValue("GoogleRefreshToken"), Issued = DateTime.FromBinary(long.Parse(identity.FindFirstValue("GoogleTokenIssuedAt"))), ExpiresInSeconds = long.Parse(identity.FindFirstValue("GoogleTokenExpiresIn")), }; return new UserCredential(flow, userId, token); }
doc_23531182
This is a cut down version of script for simplicity. $WebApp_Root = 'C:\Documents and Settings\user\Desktop\Dummy.Website' $Preview_WebApp_Root = 'c:\applications\Preview\' $Choice = read-host("enter 'preview' to deploy to preview, enter Dummy to deploy to Dummy, or enter test to deploy to the test environment") if (($Choice -eq 'Preview') -or ($Choice -eq 'preview')) { $Choice = 'Preview' $Final_WebApp_Root = $Preview_WebApp_Root } write-host("Releasing Build to " + $Choice +'...') write-host("Emptying web folders or creating them if they don't exist... ") New-Item $Final_WebApp_Root -type directory -force write-host("Copying Files... ") Copy-Item $WebApp_Root $Final_WebApp_Root -recurse write-host("Copy the correct config file over the top of the dev web config...") Copy-Item $Final_WebApp_Root\Config\$Choice\Web.configX $Final_WebApp_Root\web.config write-host("Copying correct nhibernate config over") Copy-Item $Final_WebApp_Root\Config\$Choice\NHibernate.config $Final_WebApp_Root\NHibernate.config write-host("Deployed full application to environment") A: Try to use -Force parameter to replace read-only files. From documentation: PS> help Copy-Item -Par force -Force [<SwitchParameter>] Allows the cmdlet to copy items that cannot otherwise be changed, such as copying over a read-only file or alias.
doc_23531183
https://www.awesomescreenshot.com/image/2830211/0e5b3019610b6e334939ef50675a0723 Headers.js import React from 'react'; import {BrowserRouter, Route, Switch, Link} from 'react-router-dom'; import About from './pages/About'; import Contact from './pages/Contact'; import Home from './pages/Home'; export default () => { return( <BrowserRouter> <div> <div className="navbar navbar-default"> <div className="container"> <div className="navbar-header pull-left"> <ul className="nav navbar-nav"> <li className="active"><Link to="/">Home<span class Name="sr-only">(current)</span></Link></li> <li><Link to="/contact">Contact</Link></li> <li><Link to="/about">About</Link></li> </ul> </div> </div> </div> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/contact" component={Contact} /> <Route exact path="/about" component={About} /> </Switch> </div> </BrowserRouter> ) } Footers.js import React from 'react'; import {BrowserRouter, Route, Switch, Link} from 'react-router-dom'; import About from '../pages/About'; import Contact from '../pages/Contact'; import Home from '../pages/Home'; import './index.css' export default class Footers extends React.Component { render() { return ( <div> <div className="footer-section"> <div className="container"> <div className="row"> <div className="col-sm-4"> <BrowserRouter> <div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/contact">Contact</Link></li> <li><Link to="/about">About</Link></li> </ul> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/contact" component={Contact} /> <Route exact path="/about" component={About} /> </Switch> </div> </BrowserRouter> </div> <div className="col-sm-4"> <h2>Text 2nd</h2> </div> <div className="col-sm-4"> <h2>Text 3rd</h2> </div> </div> </div> </div> </div> ); } } src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import Headers from './Headers'; import Footers from './footers'; ReactDOM.render( <div> <Headers/> <Footers/> </div>, document.getElementById('root') ); Headers and footers has correct menu links and quick links but home component are displaying twice, also when i click on menu links components are rendered on top section, when footer links are clicked components are rendered on second section which is below of footer as per screenshot. How can i solve this? Any solution would be appreciated, thank you! A: Move browser router to index.js, this will make it more consistent : ReactDOM.render( <BrowserRouter> <div> <Headers/> <Route exact path="/" component={Home} /> <Route exact path="/contact" component={Contact} /> <Route exact path="/about" component={About} /> <Footers/> </div> </BrowserRouter> , document.getElementById('root') ); Remove router from header and footer. A: Why components are rendering twice? Because you are using the same routing part in two different components, so inside Header routing will work separately and in Footer it will work separately and both component will render one Child component on the basis of path, that's why two components. Solution: You need to re-structure the routing part, instead of defining the same routes in multiple components, define them in global space like inside index.js file and use their links in different component. Use BrowserRouter once and put the main routes inside index.js file. Index file: ReactDOM.render( <BrowserRouter> <div> <Headers/> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/contact" component={Contact} /> <Route exact path="/about" component={About} /> </Switch> <Footers/> </div> </BrowserRouter>, document.getElementById('root') ); Now all these routes will be accessible inside Footer and Header component. To render them use Links in Header and Footer. Header file: export default () => ( <div> <div className="navbar navbar-default"> <div className="container"> <div className="navbar-header pull-left"> <ul className="nav navbar-nav"> <li className="active"><Link to="/">Home<span class Name="sr-only">(current)</span></Link></li> <li><Link to="/contact">Contact</Link></li> <li><Link to="/about">About</Link></li> </ul> </div> </div> </div> </div> ) Footer file: export default class Footers extends React.Component { render() { return ( <div className="footer-section"> <div className="container"> <div className="row"> <div className="col-sm-4"> <div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/contact">Contact</Link></li> <li><Link to="/about">About</Link></li> </ul> </div> <div className="col-sm-4"> <h2>Text 2nd</h2> </div> <div className="col-sm-4"> <h2>Text 3rd</h2> </div> </div> </div> </div> </div> ); } }
doc_23531184
I getvalues starting at row 6115 thru 6154, and when I setvalues to the same range, it adds 6000+ rows to the document and throws an error because the google sheet now has too many cells. The simple script below is taken from a larger function, but even the simplest script below does not work. Error Msg: This action would increase the number of cells in the workbook above the limit of 2000000 cells. function test3() { var ss=SpreadsheetApp.getActiveSpreadsheet(); var sheet=ss.getActiveSheet(); data = sheet.getRange(6115,88,6154,89).getValues(); sheet.getRange(6115,88,6154,89).setValues(data); } I appreciate any help. thanks. A: getRange() is "getRange(row, column, numRows, numColumns)". The detail information is here. https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrangerow-column-numrows-numcolumns The number of all cells in a spreadsheet can be expressed as follows. From your script, getRange(6115,88,6154,89) can be written as follows. This value is larger than the limitation of spreadsheet which is displays as an error. In the case of getValues(), even if there are no data in the range, the size of data array is created for the range. But this is not reflected to the sheet. So no errors occur, even when this getValues() is executed. But in the case of setValues(), it imports data by expanding sheet, when number of data is larger than the size of sheet. At this time, the error occurs when the data range is over the limitation. In order to avoid this error, it is necessary to be careful for number of cells and range. In your case, if you want to avoid the error, please reduce the range or create new spreadsheet which is not sheets in this spreadsheet and import the data. If I misunderstand your question, I'm sorry.
doc_23531185
normA = Xtrain - min(Xtrain(:)); Xtrain = normA ./ max(normA(:)); normB = Xtest - min(Xtest(:)); Xtest = normB ./ max(normB(:)); to normalized my data before using classifier (design tree), but every time I got very poor accuracy, it is around 55.00. Meanwhile, I got accuracy 93.88 without using the normalization algorithm. can anyone tell me what the problem exactly and what I have to do? This is my code: load('train_and_test_data.mat') Xtrain= Xtrain(:, 2:42); Xtest= Xtest(:,2:42); normA = Xtrain - min(Xtrain(:)); Xtrain = normA ./ max(normA(:)); normB = Xtest - min(Xtest(:)); Xtest = normB ./ max(normB(:)); Mdl = fitctree(Xtrain ,Ytrain); y =Mdl.predict(Xtest); %test Conf_Mat = confusionmat(Ytest,y) This small sample of data I am using before normalization: 1 0 0 0 0 17 4 2 2 0 38 20 17 0 0 11 2 2 0 0 2 1 1 0 0 11 1 4 0 0 8 5 1 1 1 21 1 16 0 0 27 12 11 0 0 13 11 2 1 0 12 3 2 2 1 A: You are not normalizing the training and the test set using the same transformation. normA = Xtrain - min(Xtrain(:)); Xtrain = normA ./ max(normA(:)); normB = Xtest - min(Xtest(:)); Xtest = normB ./ max(normB(:)); Subtracting a different amount. Dividing by a different amount. Therefore the inputs from your test set are not comparable to the inputs from your training set. Instead, normalize your test data using the same transformation. normB = Xtest - min(Xtrain(:)); Xtest = normB ./ max(normA(:));
doc_23531186
I have a service method that disables a user by the ID, all it does is set a property to true and set the DisabledDate. Should I call to the repository, get that user, set the properties in the service, then call to the save function in the repository? If I do this, then thats 2 database calls, should I worry about this? What if the user is updating the profile at the same time the admin is calling the disable method, and calls the user calls the save method in the repository (which currently holds false for the IsDisabled property?) Wouldn't that set the user back to being enabled if called right after the disabled method? What is the best way to solve this problem? How do I update data in a high concurrent system? A: As long as you know the id of the entity you want to save you should be able to do it by attaching the entity to the context first like so: var c = new Customer(); c.Id = someId; context.AttachTo("Customer", c) c.PropertyToChange = "propertyValue"; context.SaveChanges(); Whether this approach is recommended or not, I'm not so sure as I'm not overly familiar with EF, but this will allow you to issue the update command without having to first load the entity. A: CustomerRepository: // Would be called from more specific method in Service Layer - e.g DisableUser public void Update(Customer c) { var stub = new Customer { Id = c.Id }; // create "stub" ctx.Customers.Attach(stub); // attach "stub" to graph ctx.ApplyCurrentValues("Customers", c); // override scalar values of "stub" ctx.SaveChanges(); // save changes - 1 call to DB. leave this out if you're using UoW } That should serve as a general-purpose "UPDATE" method in your repository. Should only be used when the entity exists. That is just an example - in reality you should/could be using generics, checking for the existence of the entity in the graph before attaching, etc. But that will get you on the right track.
doc_23531187
<button class="btn btn-primary" data-toggle="modal" data-target="#modal-preview" onclick="return functionPrev();">Prev</button> js file: function functionPrev() { alert("Alert!"); return false; } Alert opens and bootstrap modal opens too, but I only want the alert to show and block modal window. A: data-toggle="modal" causes Bootstrap to bind a click event listener to this button. Bootstrap's event handler opens the modal. Removing that data attribute should stop this behavior. data-target="#modal-preview" will then be unnecessary.
doc_23531188
I'm doing the Scrabble exercise from CS50 and the program runs fine. BUT... when you type "Question!" or "Question?" as the first word, it simple cannot identify the "Q" as a letter anymore and therefore pontuates it as zero. Am i doing something wrong? I tried to printf the output right after the assignment of letters from words to points, and it seems that there is something wrong there, but i cannot figure out what. #include <ctype.h> #include <cs50.h> #include <stdio.h> #include <string.h> // Points assigned to each letter of the alphabet int POINTS[] = {1, 1, 3, 3, 3, 3, 2, 2, 1, 1, 4, 4, 2, 2, 4, 4, 1, 1, 8, 8, 5, 5, 1, 1, 3, 3, 1, 1, 1, 1, 3, 3, 10, 10, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 4, 4, 8, 8, 4, 4, 10, 10, 0}; char LETTERS[] = {'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', 'W', 'w', 'X', 'x', 'Y', 'y', 'Z', 'z', '\0'}; int compute_score(string word); int main(void) { int lcounter = 0; int counter; int index1; int index2; // Get input words from both players string word1 = get_string("Player 1: "); string word2 = get_string("Player 2: "); // FIND LENGTH OF WORD STRINGS int length_word1 = strlen(word1); int length_word2 = strlen(word2); // FIND CHARS OF STRINGS IN ARRAY AND ASSIGN VALUE string cword1 = word1; string cword2 = word2; int word1_counter = length_word1 - 1; int word2_counter = length_word2 - 1; int w1index[word1_counter]; int w2index[word2_counter]; for (counter=0; counter < 53; counter ++) { if (cword1[word1_counter] == LETTERS[counter]) { w1index[word1_counter] = counter; word1_counter--; counter = -1; } else if (word1_counter < 0) { counter = 54; } else if (counter == 52) { w1index[word1_counter] = 52; word1_counter--; counter = -1; } } for (counter=0; counter < 53; counter ++) { if (cword2[word2_counter] == LETTERS[counter]) { w2index[word2_counter] = counter; word2_counter--; counter = -1; } else if (word2_counter < 0) { counter = 54; } else if (counter == 52) { w2index[word2_counter] = 52; word2_counter--; counter = -1; } } // Score both words int score1; int score2; for (counter = 0; counter < length_word1; counter ++) { score1 = score1 + POINTS[w1index[counter]]; } for (counter = 0; counter < length_word2; counter ++) { score2 = score2 + POINTS[w2index[counter]]; } // TODO: Print the winner if (score1 > score2) { printf("Player 1 wins!"); } else if (score1 < score2) { printf("Player 2 wins!"); } else if (score1 == score2) { printf("Tie!"); } } A: OK I think I understood your algorithm. There are two errors. The first is here: int word1_counter = length_word1 - 1; int word2_counter = length_word2 - 1; int w1index[word1_counter]; int w2index[word2_counter]; You're not reserving enough space for the size intended. So the second loop (the one that fills w2index) will actually overwrite the last member from w1index when it's filling the first member from w2index. Change these lines to: int word1_counter = length_word1 - 1; int word2_counter = length_word2 - 1; int w1index[word1_counter + 1]; int w2index[word2_counter + 1]; The other error is here: // Score both words int score1; int score2; The variables are not initialized. Change to: // Score both words int score1 = 0; int score2 = 0; Variables lcounter, index1 and index2 are not used. Remove them. The names word*_counter are not very good because you're actually using them as indexes... You could use break to exit the loops and break down/simplify the code much more. But I see you're still beginning so it's easy to overcomplicate... It's fine though. It takes time. The beauty is that with more experience we always tend to make these things simpler!
doc_23531189
I have tried playing around with the row sizes "div class="row-sm-4" but to no luck <div class="col" style="overflow:auto;height:60vh;"> <div class="col-sm-12" style="max-height:10%;" ng-repeat="FoundAlises in SearchResults" ng-class="GetClassForSearchResult(FoundAlises)"> <div class="row mb-1"> <div class="col-sm-1 mt-12"> <input class="cursorPointer" type="radio" ng-model="$parent.SelectedSearchResult" ng-value="FoundAlises" name="AliasSearchResults" ng-click="OnSearchClicked(FoundAlises)"> </div> <div class="row-sm-4"> <small class="cursorPointer" ng-click="OnSearchClicked(FoundAlises)">Alias : <small ng-bind="FoundAlises.Alias"></small></small> <small class="cursorPointer" ng-click="OnSearchClicked(FoundAlises)">Tag : <small ng-bind="FoundAlises.Tag"></small></small> </div> </div> </div> The following is the area where I am having the issue <div class="row-sm-4"> <small class="cursorPointer" ng-click="OnSearchClicked(FoundAlises)">Alias : <small ng-bind="FoundAlises.Alias"></small></small> <small class="cursorPointer" ng-click="OnSearchClicked(FoundAlises)">Tag : <small ng-bind="FoundAlises.Tag"></small></small> </div> I expect the output to be all on one line and have equal spacing between all 3 columns. One thing to note but not sure if this will have any impact is results that are displayed can be different lengths of text. I was hoping that in these cases all of the text in the same column would be inline eg all of the 'Alias :' labels would be in line in 1 column and all of the 'Tag :' labels would be inline in the next column Expected output |Radio Button| Alias: ********** Tag:******* |Radio Button| Alias: ************ Tag:******* |Radio Button| Alias: ******* Tag:********** Current Output |Radio Button| Alias: ********** Tag:******* |Radio Button| Alias: ************ Tag:******* |Radio Button| Alias: ******* Tag:********** A: <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> </head> <body> <div class="col" style="overflow:auto;height:60vh;"> <div class="col-sm-12" style="max-height:10%;" ng-repeat="FoundAlises in SearchResults" ng-class="GetClassForSearchResult(FoundAlises)"> <div class="row mb-1"> <div class="col-sm-1"> <input class="cursorPointer" type="radio" ng-model="$parent.SelectedSearchResult" ng-value="FoundAlises" name="AliasSearchResults" ng-click="OnSearchClicked(FoundAlises)"> </div> <div class="col-sm-1"> <small class="cursorPointer" ng-click="OnSearchClicked(FoundAlises)">Alias : <small ng-bind="FoundAlises.Alias"></small></small> </div> <div class="col-sm-1"> <small class="cursorPointer" ng-click="OnSearchClicked(FoundAlises)">Tag : <small ng-bind="FoundAlises.Tag"></small></small> </div> </div> </div> </body> </html> This might helps you ! A: I've made some changes to your code using bootstrap and inline styles by declaring element width as a percentage and using display: inline-block; to keep the rows on the same line, like so: <div class="col" style="overflow:auto;height:60vh;"> <div class="col-sm-12" style="max-height:10%;" ng-repeat="FoundAlises in SearchResults" ng-class="GetClassForSearchResult(FoundAlises)"> <div class="row mb-1"> <input style="width: 30%; display: inline-block;" class="cursorPointer align-text-top p-1 m-3" type="radio" ng-model="$parent.SelectedSearchResult" ng-value="FoundAlises" name="AliasSearchResults" ng-click="OnSearchClicked(FoundAlises)"> <small style="width: 30%; display: inline-block;" class="cursorPointer align-text-top p-1" ng-click="OnSearchClicked(FoundAlises)">Alias : <small ng-bind="FoundAlises.Alias"></small>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</small> <small style="width: 30%; float: right;" class="cursorPointer align-text-top p-1" ng-click="OnSearchClicked(FoundAlises)">Tag : <small ng-bind="FoundAlises.Tag"></small>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</small> </div> <div class="row mb-1"> <input style="width: 30%; display: inline-block;" class="cursorPointer align-text-top p-1 m-3" type="radio" ng-model="$parent.SelectedSearchResult" ng-value="FoundAlises" name="AliasSearchResults" ng-click="OnSearchClicked(FoundAlises)"> <small style="width: 30%; display: inline-block;" class="cursorPointer align-text-top p-1" ng-click="OnSearchClicked(FoundAlises)">Alias : <small ng-bind="FoundAlises.Alias"></small>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</small> <small style="width: 30%; float: right;" class="cursorPointer align-text-top p-1" ng-click="OnSearchClicked(FoundAlises)">Tag : <small ng-bind="FoundAlises.Tag"></small>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</small> </div> <div class="row mb-1"> <input style="width: 30%; display: inline-block;" class="cursorPointer align-text-top p-1 m-3" type="radio" ng-model="$parent.SelectedSearchResult" ng-value="FoundAlises" name="AliasSearchResults" ng-click="OnSearchClicked(FoundAlises)"> <small style="width: 30%; display: inline-block;" class="cursorPointer align-text-top p-1" ng-click="OnSearchClicked(FoundAlises)">Alias : <small ng-bind="FoundAlises.Alias"></small>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</small> <small style="width: 30%; float: right;" class="cursorPointer align-text-top p-1" ng-click="OnSearchClicked(FoundAlises)">Tag : <small ng-bind="FoundAlises.Tag"></small>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</small> </div> </div> Hopefully that helps. Let me know if that wasn't what you are looking for.
doc_23531190
My implementation is to specify a list of prohibited selectors from UIResponderStandardEditActions, store it in an AssociatedValue in a UIResponder category and quit category's canPerformAction:withSender: prematurely if action is found in the list. This is quite tempting approach, because it lets to control any Responder in the project. Problem is no paste: action reaches any canPerformAction:withSender: method for the whole responder chain when I tap inside my UITextField. I wrote a category on UIResponder and swizzled canPerformAction:withSender: there, so I can be sure: - (BOOL)my_canPerformAction:(SEL)action withSender:(id)sender { NSString *string = NSStringFromSelector(action); BOOL prohibited = [self.prohibitedActions containsObject:string]; if (prohibited) { return NO; } BOOL canPerform = [self my_canPerformAction:action withSender:sender]; return canPerform; } The whole catch for my hierarchy is: cut: copy: select: selectAll: delete: _promptForReplace: _transliterateChinese: _insertDrawing: _showTextStyleOptions: _lookup: _define: _define: _addShortcut: _accessibilitySpeak: _accessibilitySpeakLanguageSelection: _accessibilityPauseSpeaking: _share: makeTextWritingDirectionLeftToRight: Prohibiting _promptForReplace: does not help. Also, my TextField does not implement canPerformAction:withSender:. So, what should I do to track down and hide that nasty paste? A: So in swift I will do like this: UIMenuController.shared.menuItems?.removeAll(where: {$0.title == "paste"}) In objective-c you can try something like this: UIMenuController * controller = [UIMenuController sharedMenuController]; NSArray * items = [controller menuItems]; // These are all custom items you added NSMutableArray * finalItemsYouWant = [NSMutableArray array]; // Here you can check what items you don't want and then remove it [controller setMenuItems:finalItemsYouWant]; So try finding out all the menu items and forcefully remove the one you want A: Creating category on UITextField instead of UIResponder did the trick. Subclassing UITextField and implementing canPerformAction:withSender: works either. It turned out that category on UIResponder does not affect canPerformAction:withSender: on UITextField, even though UITextField IS-A UIResponder. I do not know whether it is a bug in iOS or some oddity in it's internal behavior. My fault was to rely too much on swizzling. I do not recommend you this "universal" approach like making a category with a list of "prohibited" action selectors to work with any responder.
doc_23531191
When testing begins, I would like to delete all the previous records in a table. What I have tried: db.User.destroy({ force: true }).then(() => { }).then(() => done()); db.User.destroy( {where: undefined}, {truncate: false} ).then(() => { return }).then(() => done()); db.User.destroy({}).then(() => { return db.User.bulkCreate(users) }).then(() => done()); I keep getting the following error: Error: Missing where or truncate attribute in the options parameter of model.destroy. How do I delete/destroy all the records in a table? A: I was able to solve this problem with the code: table.sync({ force: true }); This is a safer solution than the one proposed in maheshiv's answer. A: It works for me: db.User.truncate() A: You can try using db.User.destroy({ where: {}, truncate: true })
doc_23531192
Example: let rx = xs.iter().zip(ys.iter()); compared to Scala: val rx = xs.zip(ys) A: What is the design reason for Vec not implementing the Iterator trait? Which of the three iterators should it implement? There are three different kinds of iterator you can get from a Vec: * *vec.iter() gives Iterator<Item = &T>, *vec.iter_mut() gives Iterator<Item = &mut T> and modifies the vector and *vec.into_iter() gives Iterator<Item = T> and consumes the vector in the process. compared to Scala: In Scala it does not implement Iterator directly either, because Iterator needs the next item pointer that the vector itself does not have. However since Scala does not have move semantics, it only has one way to create an iterator from a vector, so it can do the conversion implicitly. Rust has three methods, so it must ask you which one you want. A: An iterator has an iteration state. It must know what will be the next element to give you. So a vector by itself isn't an iterator, and the distinction is important. You can have two iterators over the same vector, for example, each with its specific iteration state. But a vector can provide you an iterator, that's why it implements IntoIterator, which lets you write this: let v = vec![1, 4]; for a in v { dbg!(a); } Many functions take an IntoIterator when an iterator is needed, and that's the case for zip, which is why let rx = xs.iter().zip(ys.iter()); can be replaced with let rx = xs.iter().zip(ys);
doc_23531193
var self = this; var flag = true; UserSessionModel.setDB(req.db); UserSessionModel.checkIdandToken(req.headers, function(err, result) { if(result.length == 0){ console.log(flag); // prints TRUE in console flag = false; res.status(400).send(self.createResponse({}, { success : false, message : "User Id or Token is invalid" })); } }); console.log(flag); // prints TRUE in console At the last line, it should be FALSE. Please Guide Me A: Like I've mentioned in my comment, it's true because of "asynchronicity" – I'm pretty sure the second argument of your checkIdandToken is a callback function. You console.log is executed before that code is run. Essentially you variable is changed, but after you run the console.log. This answer explains how asynchronous code works.
doc_23531194
My data contains dates and so I create a field of type DateTime, but when the file is generated the date values come out in the format ddmmyyyy rather than dd/mm/yyyy e.g. 28042000 instead of 28/04/2000. I've set the DateFormat property of the CsvOptions class to "dd/MM/yyyy" but it doesn't help. Here is the code that generates the record type: private Type CreateRecordType() { int propertyIndex = 0; var csvOptions = new CsvOptions("Flat" + _report.RootType.Name, ',', Properties.Count) { DateFormat = "dd/MM/yyyy" }; var classBuilder = new CsvClassBuilder(csvOptions); foreach(var property in Properties) { var fieldBuilder = classBuilder.FieldByIndex(propertyIndex++); fieldBuilder.FieldName = property.Name; fieldBuilder.FieldType = property.Type.Name; } return classBuilder.CreateRecordClass(); } A: It turns out you need to use the Converter property of the FieldBuilder class. Adding the following block of code to my method allows me to customise the date format in the resulting CSV file. if (property.Type == typeof(DateTime)) { fieldBuilder.Converter.Kind = ConverterKind.Date; fieldBuilder.Converter.Arg1 = "dd/MM/yyyy"; }
doc_23531195
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { I want to initialize my variable as in the same way like OnCreateView in AsyncTask. I was able to initialize these variable : LayoutInflater inflater; ViewGroup container; inflater = (LayoutInflater) ctx .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rootView = inflater.inflate(R.layout.fragment_pager_list, container, false); However, i get the error that container isn't initialized! so how can i initialize it? Thanks A: It's complaining because you have not initialized the value of the variable container - you have only declared it. Initialization means you assign it a value, such as ViewGroup container = null;. For your purposes, you can omit that entirely and simply pass null to the call to inflate. LayoutInflater inflater = (LayoutInflater) ctx. getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rootView = inflater.inflate(R.layout.fragment_pager_list, null);
doc_23531196
Never had this issue before. The first time I launch GlassFish, everything works fine. Then I shut it down and that works. Then when I start again, it says the Admin Port: 4848 is busy. Apparently the shutdown is not releasing the admin port. (Although it does seem to be shutting down, because if I try to navigate to localhost:4848 from my browser it hangs) When I do a lsof -i :4848 it shows me "*:appserv-http (LISTEN)" is listening. When I kill -9 that process that releases the port. But why does it need to be so difficult (especially since none of this can be handled by my IDE!) Does anyone have a more automated idea how to stop the domain if asadmin stop-domain doesn't do the job? victors-mbp:~ vgrazi$ cd programs/glassfish4/glassfish/bin/ victors-mbp:bin vgrazi$ ./asadmin start-domain Waiting for domain1 to start ........ Successfully started the domain : domain1 domain Location: /Users/vgrazi/programs/glassfish4/glassfish/domains/domain1 Log File: /Users/vgrazi/programs/glassfish4/glassfish/domains/domain1/logs/server.log Admin Port: 4848 Command start-domain executed successfully. victors-mbp:bin vgrazi$ ./asadmin stop-domain CLI306: Warning - The server located at /Users/vgrazi/programs/glassfish4/glassfish/domains/domain1 is not running. Command stop-domain executed successfully. victors-mbp:bin vgrazi$ ./asadmin start-domain There is a process already using the admin port 4848 -- it probably is another instance of a GlassFish server. Command start-domain failed. victors-mbp:bin vgrazi$
doc_23531197
/* Looks for an addition symbol "+" surrounded by two numbers, e.g. "5+6" and, if found, adds the two numbers and replaces the addition subexpression with the result ("(5+6)*8" becomes "(11)*8")--remember, you don't have to worry about associativity! */ if (buffer[i] == '+') { for (startOffset = i; startOffset - 1 >= 0 && isNumeric(buffer[startOffset - 1]); --startOffset) ; // empty loop body if (startOffset == i) // For further processing continue; for (remainderOffset = i; remainderOffset + 1 < bufferlen && isNumeric(buffer[remainderOffset + 1]); ++remainderOffset) ; // empty loop body if (remainderOffset == i) continue; strncpy(operand, &buffer[startOffset], i - startOffset); operand[i - startOffset] = '\0'; string2int(value1, operand); strncpy(operand, &buffer[remainderOffset], remainderOffset - i); operand[remainderOffset - i] = '\0'; string2int(value2, operand); sum = value1 + value2; sprint(operand, "%d", sum); operlength = strlen(operand); strncpy(&buffer[startOffset], operand, operlength); strcpy(&buffer[operlength], &buffer[remainderOffset + 1]); bufferlen = bufferlen - (remainderOffset - startOffset + 1) + operlength; } A: Compile your program with the debugger flag in gdb like this cc -g "program name". If you have command line arguments, for the program execute gdb --args progname arg2 ... It will load your program into a CLI utility which has the lines numbered. Type in 'break 32' for example and this will monitor variables on that line. At any rate, once you've compiled it with the debugger symbols and loaded it, type 'run' to start the program. If no break points are set or anything else funky, it will trigger the SEGV and tell you exactly which line of code triggered it. Run the debugger at least 3 times to make sure the segv fault is being triggered by the same line of code. Then check your memory bounds(is your array index outside of the allocated address space? You were tresspassing... Try inserting a printf line which prints off the array addresses and offset you are using to be sure your bounds aren't getting skewed; a side note, int conjunction with the gdb debugger using the breakpoint and typing 'step' on the CLI each time to step through each step, you can also at each step in your execution type in 'info locals' which will tell you the variables values in the stack space, i.e. your index variable value at each step. As an alternative to manually inserting printf lines) I am not a professional expert. It looks like continue on the 9th line is moot. Good luck!
doc_23531198
int main() { char* x = new char[33]; int* sz = (int*)x; sz--; sz--; sz--; sz--; int szn = *sz; //szn is 33 :) } I do know it's not safe and would never use it, but it brings to mind a question: Is the following safe? Is it a memory leak? char* allocate() { return new char[20]; } int main() { char* x = allocate(); delete[] x; } If it's safe, doesn't that mean we can actually find the size of the array? Granted, not in a standard way, but is the compiler required to store information about the size of the array? I am not using or plan on using this code. I know it is undefined behavior. I know it isn't guaranteed by anything. It's just a theoretical question! A: Is the following safe? Yes, of course that's safe. First snippet has UB however. If it's safe, doesn't that mean we can actually find the size of the array? Granted, not in a standard way, but is the compiler required to store information about the size of the array? Yes, generally extra data is stored before the first element. This is used to call the correct number of destructors. It's UB to access this. required to store information about the size of the array? No. It only requires delete[] work as expected. new int[10] could simply be a plain malloc call, which would not necessarily store the requested size 10. A: This is safe, and is not a memory leak. The standards require that delete[] handle the freeing of memory by any array allocation. If it's safe, doesn't that mean we can actually find the size of the array? The standards don't put specific requirements on where and how the allocated size is stored. This could be discoverable as shown above, but different compilers/platforms could also use a completely different methodology. As such, it's not safe to rely on this technique to discover the size. A: I know that in c, the size of any malloc on the heap resides before the pointer. The code for free relies on this. This is documented in K&R. But you should not rely on this always being there or always being in the same position. If you want to know the array length then I would suggest you create a class or struct to record capcity along side the actual array, and pass that around your program where you would previously just pass a char*. A: int main() { char* x = new char[33]; int* sz = (int*)x; sz--; sz--; sz--; sz--; int szn = *sz; //szn is 33 :) } This is an undefined behavior, because you access the memory location that you didn't allocate. is the compiler required to store information about the size of the array? No. If it's safe, doesn't that mean we can actually find the size of the array? You do not do anything special in the 2nd code snipet, therefore it's safe. But there are no ways to get the size of the array. A: I am not sure it the delete must know the size of the array when the array is allocated with basic types (that doesn't demand a call to the destructor). In visual studio compilers, the value is stored only for user defined objects (in this case, delete[] must know the size of the array, as it must call their destructors). Where in the memory the size is allocated is undefined (in visual studio it is in the same place of the gcc). http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.14 A: There are two ways to destroy an array, depending on how it was created. In both cases the compiler is required to call a destructor for each element of the array, so the number of elements in the array must be known. If the array is an automatic variable on the stack, the number of elements is known at compile time. The compiler can hard-code the number of elements in the code it emits for destroying the array. If the array is dynamically allocated on the heap, there must be another mechanism for knowing the element count. That mechanism is not specified by the standard, nor is it exposed in any other fashion. I think that putting the count at an offset from the front of the array is a common implementation, but it's certainly not the only way, and the actual offset is just a private implementation detail. Since the compiler must know how many elements are in the array, you'd think it would be possible for the standard to mandate a way of making that count available to programs. Unfortunately this is not possible because the count is only known at destruction time. Imagine that the standard included a function count_of that could access that hidden information: MyClass array1[33]; MyClass * array2 = new MyClass[33]; cout << count_of(array1) << count_of(array2); // outputs 33 33 Foo(array1); Foo(array2); MyClass * not_array = new MyClass; Foo(not_array); void Foo(MyClass * ptr) { for (int i = 0; i < count_of(ptr); ++i) // how can count_of work here? ... } Since the pointer passed to Foo has lost all its context, there's no consistent way for the compiler to know how many elements are in the array, or even if it's an array at all.
doc_23531199
def Capture(self, incoming): capture = pyshark.LiveCapture() capture.sniff(timeout=int(incoming)) print('TIMEOUT: ' + str(int(incoming))) print(capture) print("Len" + str(len(capture))) pktList = [] count=0 for pkt in capture: count=count+1 pktList.append([int(pkt.layers[1].version), pkt.layers[2].layer_name, pkt.length]) print(f"Saved packet #{count}") print(pktList) print("Job is done.") Output shows that despite after the timeout of 2 seconds the capture consists of a single packet, the program somehow continues reading some data. Output: TIMEOUT: 2 <LiveCapture (0 packets)> Len 0 Saved packet #1 [[4, 'tcp', '108']] Saved packet #2 [[4, 'tcp', '108'], [4, 'tcp', '112']] Saved packet #3 [[4, 'tcp', '108'], [4, 'tcp', '112'], [4, 'tcp', '108']] Saved packet #4 [[4, 'tcp', '108'], [4, 'tcp', '112'], [4, 'tcp', '108'], [4, 'tcp', '112']] Saved packet #5 [[4, 'tcp', '108'], [4, 'tcp', '112'], [4, 'tcp', '108'], [4, 'tcp', '112'], [4, 'tcp', '54']] ............... How can I fix it? A: I tried to use your code, but I couldn't get it to work correctly. I know that there are some known issues with the way that capture.sniff(timeout=x) works, so I put together some other code that is using apply_on_packets with a timeout. import pyshark import asyncio packet_list = [] def process_packets(packet): global packet_list try: packet_version = packet.layers[1].version layer_name = packet.layers[2].layer_name packet_list.append(f'{packet_version}, {layer_name}, {packet.length}') except AttributeError: pass def capture_packets(timeout): capture = pyshark.LiveCapture(interface='en0') try: capture.apply_on_packets(process_packets, timeout=timeout) except asyncio.TimeoutError: pass finally: global packet_list for item in packet_list: print(item) capture_packets(2) I decided to rework your code. The code below works with capture.sniff(timeout=x). import pyshark packet_list = [] def capture_packets(timeout): global packet_list capture = pyshark.LiveCapture(interface='en0') capture.sniff(timeout=timeout) packets = [pkt for pkt in capture._packets] capture.close() try: for packet in packets: packet_version = packet.layers[1].version layer_name = packet.layers[2].layer_name packet_list.append(f'{packet_version}, {layer_name}, {packet.length}') except AttributeError: pass finally: return packet_list packets = capture_packets(2) print(packets) ['4, tcp, 54', '6, icmpv6, 86', '6, icmpv6, 78', '4, tcp, 66'] I will answer any questions you have about the code examples above. ---------------------------------------- My system information ---------------------------------------- Platform: macOS Python: 3.8.0 Pyshark: 0.4.3 ----------------------------------------