text
stringlengths
15
59.8k
meta
dict
Q: Pyspark: how to read CSV file with additional lines so I am having the following CSV file. It has some additional strings between the valid rows. Excel seems to do a good job when reading those(and just ignores the additional ones). However, the story with spark is a bit different. I have set it as spark.read.csv(path, header=True, multiLine=True, sep='|') Is there some simple way to handle it?
{ "language": "en", "url": "https://stackoverflow.com/questions/67752545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to test redirect to created instance in Flask Having following function in views.py: def ask_question(): form = QuestionForm() if form.validate_on_submit(): question = Question(title=form.title.data, text=form.text.data) db.session.add(question) db.session.commit() return redirect('/questions/%d/' % question.id) return render_template('ask_question.html', form=form) How can I get an id of created model to put it in assertion? def test_can_post_question(self): response = self.tester.get('/new-question') self.assert_200(response) form = self.get_context_variable('form') self.assertIsInstance(form, QuestionForm) response = self.tester.post('/new-question', data={'title': 'What about somestuff in Flask?', 'text': 'What is it?'}) self.assertRedirects(response, '/questions/%d' % created_question.id) #^ how can I get id of created model here? I'm using Flask, Flask-SQLAlchemy, Flask-Testing A: Query the created question object. As a side effect, you can test that the question was created. ... q = Question.query.filter_by(title='What about somestuff in Flask?').first() self.assertRedirects(response, '/questions/%d/' % q.id)
{ "language": "en", "url": "https://stackoverflow.com/questions/27998027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to generate dynamic menu and components in angular based on API response I want to (propably) dynamically generate some number of menu positions and components reffering to these menu positions based on API response. Response to c# backend would be made on application start in app.component.ts. Those menu positions would be statuses of proceesing items (for example "finished", "in progress" etc.) and html in every component should look almost identically (just table with positions from sql database, only difference between them was sql query made to database with different "where" clause). Now it is two statuses, but in future it could be 7 more, so I don't want to create a new component in angular every time I add new status in backend. So what I should be looking for? And after receiving response from api where should I store this answer? (In order to have those components all time, I don't want them to dissapear after page reload or anything else). A: When displaying data fetched from an API it's good practice to implement a model controller view pattern where the date is downloaded by the controller (a service), saved in the model which is marked with the @Injectable() decortator and is injected in the view component you're displaying the data. So your fetched data is stored in the model and can be accessed everywhere you need it. The controller can look something like that: @Injectable({ providedIn: 'root' }) export class StatusService{ constructor(private http : HttpClient) { } public getStatus() : Observable<any> { return this.http.get('http://myapi.com/getstatus'); } } The model is just storing this data: export class Status { public id : number; public type: string; } @Injectable() export class StatusModel { public statuses: Status[]; constructor(private statusService : StatusService) { } public getStatus() : Observable<Status[]> { return this.statusService.getstatus().pipe(map((status: Status[]) => { this.statuses = data; return this.statuses ; })); } } In you component (view) you're injecting the StatusModel in the constructor and make the API request: @Component({ selector: 'app-status', templateUrl: './status.component.html', styleUrls: ['./status.component.scss'], }) export class StatusComponent implements OnInit { constructor(public statusModel : StatusModel) { this.getStatus(); } public getStatus() : void { this.statusModel.getStatus().subscribe( (data) => { console.log(data); }, (error) => { console.log(error); } ); } } In your HTML you can dispay these statuses stored in statusModel.statuses using *ngFor like that: <div class="status" *ngFor="let status of statusModel.statuses"> <p>{{status.id}</p> <p>{{status.type}}</p> </div> You can also use *ngIf to display different statuses differently or ngClass to set specific style classes for specific statuses.
{ "language": "en", "url": "https://stackoverflow.com/questions/66929396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wrong output in printing values using for loop in C I wrote a simple C program to print all the multiples of 3 but there is some error during runtime my code is: #include <stdio.h> void main(void) { int i, x; for(i = 1; i < 1000; i++) { x = i % 3; if(x == 0) { printf("%d\n", i); } } } the problem is that if I enter numbers greater than 891 till 1000 in the loop the output is starting from 6 instead of 3 and if i write the code as above than the output is starting from 114. for the values less than or equal to 891 it is showing the correct output. A: Make sure you can view all output: reuts@reuts-K53SD:~/ccccc$ cat mmph.c && gcc mmph.c #include<stdio.h> main(){ int i,x; for(i=1;i<1000;i++) { x=i%3; if(x==0){ printf("%d\n",i); } } } reuts@reuts-K53SD:~/ccccc$ ./a.out | egrep "^3$|999" 3 999 As you can see, this works. Your output is probably truncated.
{ "language": "en", "url": "https://stackoverflow.com/questions/21643716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: (Karate) How to intercept the XHR request response code? I am testing a login functionality on a 3rd party website. I have this url example.com/login . When I copy and paste this into the browser (chrome), page sometimes load, but sometime does not (empty blank white page). The problem is that I have to run a script on this page to click one of the elements (all the elements are embedded inside #shadow-root). If the page loads, no problem, script is evaluated successfully. But page sometimes does not load and it returns a 404 in response to an XHR request, and as a result, my * eval(scrip("script") step returns "js eval failed...". So I found the solution to refresh the page, and to do that, I am considering to capture the xhr request response. If the status code is 404, then refresh the page. If not, continue with the following steps. Now, I think this may work, but I do not know how to implement karate's Intercepting HTTP Requests. And firstly, is that something doable? I have looked into documentation here, but could not understand the examples. https://github.com/karatelabs/karate/tree/master/karate-netty Meanwhile, if there is another way of refreshing the page conditionally, I will be more than happy to hear about it. Thanks anyone in advance. A: First, using JavaScript you should be able to handle shadow roots: https://stackoverflow.com/a/60618233/143475 And the above answer links to advanced examples of executing JS in the context of the current page. I suggest you do some research into that, try to take the help of someone who knows JS, the DOM and HTML well - and you should be find a way to know if the XHR has been made successfully or not - for e.g. based on whether some element on the page has changed etc. Finally here is how you can do interception: https://stackoverflow.com/a/61372471/143475
{ "language": "en", "url": "https://stackoverflow.com/questions/69743436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ms-access queries I never really did ms access queries, but today I need one. I have 2 tables, models and orders. From first table one 2 fields are of interest here: number and color, from second only number which can only be equal to values of number from table "models" . What I need is to select most frequent color. In mysql that would be something like SELECT models.color, orders.number FROM models INNER JOIN orders ON (orders.number =models.number) group by color order by count(color) desc limit 1 But in ms-access that doesn't seem to work How do you write query to do same thing in ms-access? A: try this: SELECT TOP 1 models.color, COUNT(orders.number) FROM models INNER JOIN orders ON (orders.number=models.number) GROUP BY models.color ORDER BY 2 desc A: All you need is to get rid of limit and use Top 1 instead: SELECT Top 1 models.color FROM models INNER JOIN orders ON (orders.number =models.number) group by color order by count(color) Desc However, there is a caveat for Top n, in MS Access, Top n will return matches, so if several items have the same count, all will be returned. If this does not suit, you can work around this by ordering by a unique id as well: order by count(color) desc, OrderID Note also that number is a reserved word.
{ "language": "en", "url": "https://stackoverflow.com/questions/13229802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Job for docker.service failed because the control process exited with error code while trying to start docker service in Manjaro[Arch] Getting this error while running docker pull manjarolinux/base: Using default tag: latest Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? List of the previous commands that I've run: sudo groupadd docker sudo usermod -aG docker $(whoami) sudo chown $(whoami) /var/run/docker.sock Output of sudo dockerd --debug which had warnings or errors: WARN[0000] containerd config version `1` has been deprecated and will be removed in containerd v2.0, please switch to version `2`, see https://github.com/containerd/containerd/blob/main/docs/PLUGINS.md#version-header #and WARN[2022-11-18T14:38:01.266464955+05:30] failed to load plugin io.containerd.snapshotter.v1.devmapper error="devmapper not configured" #and WARN[2022-11-18T14:38:01.266829045+05:30] could not use snapshotter devmapper in metadata plugin error="devmapper not configured" #and ERRO[2022-11-18T14:38:01.267936333+05:30] failed to initialize a tracing processor "otlp" error="no OpenTelemetry endpoint: skip plugin" #and ERRO[2022-11-18T14:38:01.279926226+05:30] failed to mount overlay: no such device storage-driver=overlay2
{ "language": "en", "url": "https://stackoverflow.com/questions/74487333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery button toggle show hide div I have these two divs on a page with two buttons beneath them to control hiding and showing them respectively. <div class="threeSixtyContainer"> <div class="toggle360" style="display: block;" id="Blue">Im Blue</div> <div class="toggle360" style="display: none;" id="Red">Im Red</div> <ul class="flashlinks"> <li id="" class="flashlinks"><a href="#Blue" onclick="toggle_visibility('Blue');">Blue</a></li> <li id="" class="flashlinks"><a href="#Red" onclick="toggle_visibility('Red');">Red</a></li> </ul> </div> I am using this javascript at the moment on the onclick of link. function toggle_visibility(id) { var e = document.getElementById(id); console.log(e); if(e.style.display == 'none') { e.style.display = 'block'; } else { e.style.display = 'none'; } } It works however how do I make it so that clicking one button will disable the other. So clicking blue will show the blue div and hide the red div, then disable the button and enable the other button so the same can be donw but in reverse. I have made a fiddle with the code i am using on my page which works, but on the fiddle its not? not sure why, ill post it anyway. EDIT _ Fiddle Now Working. Thanks. JSFIDDLE A: You can't execute your js method before the elements get loaded. so wrap your code in head/body check this fiddle A: Here is a possible solution (no jQuery) : http://jsfiddle.net/wared/A6w5e/. As you might have noticed, links are not "disabled", I simply save the id of the DIV which is currently displayed in order to check the requested id before toggling : if (current !== id). Another thing to note is that toggle_visibility is overwritten (only once) inside itself. It might look weird, but it's just a way to create a closure in order to enclose the variable named current inside a private context. The goal is to avoid polluting the parent scope. Lastly, I've modified the original code to hide all divs except the one targeted by id. function toggle_visibility(id) { var current = 'Blue'; (toggle_visibility = function (id) { var div, l, i; if (current !== id) { current = id; div = document.getElementsByClassName('toggle360'); l = div.length; i = 0; for (; i < l; i++) { div[i].style.display = div[i].id === id ? 'block' : 'none'; } } })(id); } A: Wrap your code in head or body. You are executing your code before DOM is created Fiddle Demo A: A couple people have commented why it doesn't work in fiddle. To answer the question.... It easy to toggle visibility using jquery if there are only two divs: $(document).delegate('.flashlinks a', 'click', function () { $('.toggle360').toggle(); }); I would use a css class to disable the links. Then I would select what to do with the click based on if the class was present: $(document).delegate('.flashlinks a:not(".disabled")', 'click', function () { $('.toggle360').toggle(); $('.flashlinks a').toggleClass("disabled"); }); $(document).delegate('.flashlinks a.disabled', 'click', function () { e.preventDefault(); }); and in my css I would have something like .disabled { color: black; text-decoration:none; } jsfiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/20631764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: g++ __FUNCTION__ replace time Can anyone tell when g++ replaces the __FUNCTION__ 'macro' with the string containing the function name? It seems it can replace it not until it has check the syntactical correctness of the source code, i.e. the following will not work #include <whatsneeded> #define DBG_WHEREAMI __FUNCTION__ __FILE__ __LINE__ int main(int argc, char* argv) { printf(DBG_WHEREAMI "\n"); //* } since after preprocessing using g++ -E test.cc the source looks like [...] int main(int argc, char* argv) { printf(__FUNCTION__ "test.cc" "6" "\n"); //* } and now the compiler rightly throws up because the *ed line is incorrect. Is there any way to force that replacement with a string to an earlier step so that the line is correct? Is __FUNCTION__ really replaced with a string after all? Or is it a variable in the compiled code? A: You are using __FUNCTION__ like a preprocessor macro, but it's a variable (please read http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html). Try printf("%s", __FUNCTION__) just for testing and it will print the function name. A: __FUNCTION__ is not standard. Use __func__. As the documentation says, it's as if: <ret-type> function_name( <args> ) { static const char __func__[] = "function-name"; ... A: In C/C++, the preprocessor will turn "my " "name " "is " "Bob" into the string literal "my name is Bob"; since __FILE__ and __LINE__ are preprocessor instructions, "We are on line " __LINE__ will pass "We are on line 27" to the compiler. __FUNCTION__ is normally a synonym for __func__. __func__ can be thought of as a pseudo-function that returns the name of the function in which it is called. This can only be done by the compiler and not by the preprocessor. Because __func__ is not evaluated by the preprocessor, you do not get automatic concatenation. So if you are using printf it must be done by printf("the function name is %s", __func__); A: Is there any way to force that replacement with a string to an earlier step so that the line is correct? No. __FUNCTION__ (and its standardized counterpart, __func__) are compiler constructs. __FILE__ and __LINE__ on the other hand, are preprocessor constructs. There is no way to make __FUNCTION__ a preprocessor construct because the preprocessor has no knowledge of the C++ language. When a source file is being preprocessed, the preprocessor has absolutely no idea about which function it is looking at because it doesn't even have a concept of functions. On the other hand, the preprocessor does know which file it is working on, and it also knows which line of the file it is looking at, so it is able to handle __FILE__ and __LINE__. This is why __func__ is defined as being equivalent to a static local variable (i.e. a compiler construct); only the compiler can provide this functionality. A: Is this what you want? #include <stdio.h> #define DBG_WHEREAMI(X) printf("%s %s(%d): %s\n",__func__,__FILE__,__LINE__,X) int main(int argc, char* argv) { DBG_WHEREAMI("Starting"); } Note: Since you marked this as C++ you should probably be using the iostreams to make sure it's type safe. A: printf("%s" __FILE__ __LINE__ "\n", __FUNCTION__); Yeah, I know that's not really the same. A: Note that if you create a class, you can build a message from any number of types as you'd like which means you have a similar effect to the << operator or the format in a printf(3C). Something like this: // make sure log remains copyable class log { public: log(const char *function, const char *filename, int line) { f_message << function << ":" << filename << ":" << line << ": "; } ~log() { //printf("%s\n", f_message.str().c_str()); -- printf?! std::cerr << f_message.str() << std::endl; } log& operator () (const char *value) { f_message << value; } log& operator () (int value) { f_message << value; } // repeat with all the types you want to support in the base class // (should be all the basic types at least) private: sstream f_message; }; // start the magic here log log_error(const char *func, const char *file, int line) { log l(func, file, line); return l; } // NOTE: No ';' at the end here! #define LOG_DEBUG log_error(__func__, __FILE__, __LINE__) // usage sample: LOG_DEBUG("found ")(count)(" items"); Note that you could declare the << operators instead of the (). In that case the resulting usage would be something like this: LOG_DEBUG << "found " << count << " items"; Depends which you prefer to use. I kind of like () because it protects your expressions automatically. i.e. if you want to output "count << 3" then you'd have to write: LOG_DEBUG << "found " << (count << 3) << " items";
{ "language": "en", "url": "https://stackoverflow.com/questions/3213571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: show ruby date as a RFC 3339 timestamp Does anyone know how I can convert a ruby time class instance into a RFC 3339 timestamp? The output should be something like this: "2013-10-13T13:34:52.000+02:00" A: require 'date' Time.now.to_datetime.rfc3339
{ "language": "en", "url": "https://stackoverflow.com/questions/21300362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using class properties in angular templates I am trying to use a property from a template in angular. It doesn't work and I can't figure out why. I've set up an example here: https://github.com/Fulkerson/angular-property It is the example from the Tour of Heroes. My commit adds the property propname which simply returns name and uses it in the dashboard (main page). Basically what I want to do is add multiple properties that process a field in different ways. But why is it I cannot use the properties from templates, and how can accomplish what I want to do in another way? A: The data returned by the heroService.getHeroes method is plain JSON object (without the getter you defined in the Hero class). If you want to use the getter defined in the class you have to return an Array of real Hero instance. 1/ We add a constructor for the Hero class in app/hero.ts for convenience constructor ({id,name} = {id: undefined, name: undefined}) { this.id = id; this.name = name; } 2/ Instead of returning plain js data from heroService we map to obtain an array of Hero instance in dashboard.component.ts getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes .slice(1, 5) .map(hero => new Hero(hero)) ); } And Tadaa ! Here is the stackblitz created upon your github repo A: Well, your problem is that, though you're adding a new getter to the Hero class, in the dashboard you're listing the heroes coming from the service. The problem is that the service is mocking data, and that data is, in truth, a simple array of objects (defined in in-memory-data.service.ts): const heroes = [ { id: 11, name: 'Mr. Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: 'Bombasto' }, { id: 14, name: 'Celeritas' }, { id: 15, name: 'Magneta' }, { id: 16, name: 'RubberMan' }, { id: 17, name: 'Dynama' }, { id: 18, name: 'Dr IQ' }, { id: 19, name: 'Magma' }, { id: 20, name: 'Tornado' } ]; In the original example this does not matter as the Hero class is used there basically as an interface or type annotation. You, however, are giving that class methods, but those methods do not exist in the array. So, basically, your template is trying to access a propname property from the items of this array. That property, as you see, is undefined. As a result, you don't see the name in the page. To avoid this, just change the definition of the array: const heroes = [ Object.assign(new Hero(), { id: 11, name: 'Mr. Nice' }), ... ]; (you can also give Hero a constructor with parameters and use it instead of Object.assign). This way you'll get an array of true Hero objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/49389512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do debug Bot code accessed via DirectLine API? We are developing a bot that will primarily be accessed using the DirectLine API. As the bot and the client app are still in development, the development is made difficult by the fact that we cannot Debug both the client app and bot on one box since DirectLine API can't connect back to the local box. What's the story there? Any recommendations on best way to do this? A: Take a look at ngrok. The basic version is free. ngrok allows you to expose a web server running on your local machine to the internet. Just tell ngrok what port your web server is listening on.
{ "language": "en", "url": "https://stackoverflow.com/questions/38771411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: javascript delete not working rails i have a partial am rendering which works well when am creating through javascript but deleting it via javascript is not working , maybe there is something am doing wrong but ma code is thus ... the partial rendering <ul id="<%= dom_id(feed) %>"> <%= render :partial => feed.talks %> </ul> the partial <ul class="unstyled custumer_say" style="list-style: none;"> <li class="clearfix" style="list-style: none;"> <%= link_to image_tag(talk.user.image.url(:tiny)),talk.user,:style=> "width: 7%; padding-right: 0px;", :class=> "pull-left img_client"%> <div class="entry-content"> <header> <strong><%= link_to talk.user.username, talk.user %>:</strong> <%= talk.details %></i><br> <small><i class="muted" style="font-size: 9px;"><%="#{time_ago_in_words(talk.created_at)} ago "%></i></small> <% if current_user.id == talk.user_id %> <%= link_to "x", talk, method: :delete, data: { confirm: "You sure?" },remote: true, class: 'pull-right' %> <% end %> </header> </div> </li> </ul><!-- End Testimonaila list--> <hr> create.js.erb which works fine $('.feed #<%= dom_id(@feed) %>').html("<%= j render(@feed.talks) %>"); $("#new_talk")[0].reset(); destroy.js.erb which doesnt delete unless a full page relod $('.unstyled custumer_say_<%= @talk.id %>').remove(); seems there is something am not doing right A: $('.unstyled custumer_say_<%= @talk.id %>').remove(); You're calling something that doesn't exist as far as I can see Change your ul to this: <ul id="unstyled custumer_say_<%= @talk.id %>" class="unstyled custumer_say" style="list-style: none;"> And the destroy.js.erb to $("#unstyled custumer_say_<%= @talk.id %>").remove(); Notice the double quotes
{ "language": "en", "url": "https://stackoverflow.com/questions/22358312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Events: When implementing interfaces is it better to use the outer class or anonymous classes This is an example of using outer class public class MyActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); findViewById(R.id.myid).setOnClickListener(this)); } public void onClick(View v){...} } This is an example of anonymous classes public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); findViewById(R.id.myid).setOnClickListener(new OnClickListener() { public void onClick(View v){...} })); } } A: Performance and efficiency are slightly a more important consideration in Android. Something considered to be half baked optimization effort, sometimes makes sense in android.(like we should not use enum but java int enum pattern). So to the answer to your question is. If you have to register multiple onClick listeners, Implement interface and use switch case within it. If you have to register only one on click listener, use anonymous class. (Android developers prefers anonymous class, whenever possible. Limiting the scope ;))
{ "language": "en", "url": "https://stackoverflow.com/questions/4750498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Start application when file is received via Bluetooth My application should start when any file is received via Bluetooth. Please tell me, which intent is fired when a file is received via Bluetooth? A: There's no such specific intent action which tells that a file is downloaded. However, you should listen for the following broadcast to detect that a phone is disconnected and then check programatically if a file is downloaded. <intent-filter> <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED"/> </intent-filter>
{ "language": "en", "url": "https://stackoverflow.com/questions/10174805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Just scaling a rectangle I'm trying to start with processing. Now I'm just trying to scale a rectangle. I have found this example: float a = 0.0; float s = 0.0; void setup() { size(200,200); rectMode(CENTER); frameRate(30); } void draw() { s = s + 0.04; translate(width/2, height/2); scale(s); rect(0, 0, 50, 50); } It scales smoothly the rectangle but I'm a bit surprise because for resizing a rectangle I expected the sizing parameters (3rd and 4th) of rect() were modified, something like this way: float r = 1; void setup() { size(200,200); rectMode(CENTER); frameRate(30); } void draw(){ rect(width/2, height/2, r, r); r += 1; } but this way doesn't scale the rectangle smoothly. So, should I use the first approach instead of the second one even if I find it the second one more natural? Any comment will be wellcome. Regards Javier A: The first solution is quite complex, you are not actually scaling the rectangle, but rather the projection matrix. The projection matrix is the series of mathematical operations that are applied before something is drawn to the screen. You can think of it as a camera, but it is far more complex than that. I actually put the code side by side and didn't notice that much difference in the smoothness. I also added a few tweaks, so that may have helped :) float r = 1; float s = 0.0; void setup() { size(200,200); rectMode(CENTER); frameRate(30); smooth(); } void draw(){ rect(width/4, height/2, r, r); r += 1.4; translate(width/2, height/2); scale(s); translate(-width/2, -height/2); rect(width/2, height/2, 50, 50); s += 0.04; } The main change that I made was to turn on smooth. I think that because you didn't have it on, the top square drawing was jumping to each pixel, but with the tranlation / scale operation, it would smooth those over. The other thing I did, was to translate back to the top left after doing the scale operation. This is important to do so that things draw where you expect them to. You will notice that the scaling rect now scale out from the center.
{ "language": "en", "url": "https://stackoverflow.com/questions/5569968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Angularjs ui-grid export functionality, Display dynamic data in the exporterPdfHeader Using Angularjs,ui-grid and uiGridExporterService exporting the data in the grid view. I'm using this export option in report functionality so when I export (PDF) need to display the filtered inputs in the PDF view. $scope.gridOptions2 = { enableSorting: true, enableColumnMenus: false, columnDefs: [ // { field: 'id', width: '60', displayName: 'S.No', cellTemplate: ''}, // { field: 'id', displayName: 'S.No', visible: false}, { field: 'reg_id', width: '130', displayName: 'Id', enableSorting: false}, { field: 'name', width: '160', displayName: 'Username', enableSorting: false} ], exporterMenuCsv: false, // ADD THIS exporterPdfDefaultStyle: {fontSize: 11}, exporterPdfTableStyle: {margin: [10, 30, 30, 30]}, exporterPdfTableHeaderStyle: {fontSize: 11, bold: true, italics: false, color: 'blue' }, exporterPdfHeader: { margin: 20, columns: [{ text: "Employee Salary Detail", alignment: 'center', style: 'defaultStyle', text: "Month : "+ $scope.monthVal, alignment: 'right', style: 'defaultStyle', width: 150 }] }, exporterFieldCallback : function ( grid, row, col, value ) { if ( col.name === 'status' ) { value = decodeStatus( value ); } return value; }, exporterPdfFooter: function ( currentPage, pageCount ) { return { text: currentPage.toString() + ' of ' + pageCount.toString(), style: 'footerStyle' }; }, exporterPdfCustomFormatter: function ( docDefinition ) { docDefinition.styles.headerStyle = { fontSize: 22, bold: true }; docDefinition.styles.footerStyle = { fontSize: 10, bold: true }; return docDefinition; }, exporterPdfOrientation: 'landscape', exporterPdfPageSize:'A4', // exporterPdfMaxGridWidth = Defaults to 720 (for A4 landscape), use 670 for LETTER exporterPdfMaxGridWidth: 600, // bug, for A4, default is 720, set to 600 solve my problem. exporterExcelFilename: 'myFile.xlsx', exporterExcelSheetName: 'Sheet1', onRegisterApi: function (gridApi) { $scope.grid2Api = gridApi; } }; Need to pass the selected inputs into the $scope.monthVal. exporterPdfHeader: { margin: 20, columns: [{ text: "Employee Salary Detail", alignment: 'center', style: 'defaultStyle', text: "Month : "+ $scope.monthVal, alignment: 'right', style: 'defaultStyle', width: 150 }] },
{ "language": "en", "url": "https://stackoverflow.com/questions/56902904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a custom Authorize attribute with specific rules I'm trying to create a custom Authorize attribute to do the following: * *If the user has a role of "Regular user" - he is redirected to /index/subscribe *All other users(Administrator,Subscriber) gets access to /Search/Index This is when the user tries to open up the Search controller. I made the custom Authorize attribute like this: public class DenyRegularUser : System.Web.Mvc.AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.Result = new RedirectResult("~/User/Logon"); return; } if (filterContext.HttpContext.User.IsInRole("Regular user")) { filterContext.Result = new RedirectResult("~/Index/Subscribe"); } } } And this is my Search controller: namespace WebApplication2.Controllers { [DenyRegularUser(Roles ="Regular user")] public class SearchController : Controller { // GET: Search public ActionResult Index() { return View(); } } } But for some reason, even when I update the user's role from Regular user to Administrator or Subscriber, I get redirected to login page: /user/login... This shouldn't happen as the login functionality works perfectly and I get the role of the user... What am I missing out here?? A: This may help. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] public class DenyRegularUser : AuthorizeAttribute { public DenyRegularUser() : base() { } protected override bool IsAuthorized (System.Web.Http.Controllers.HttpActionContext actionContext) { if (AuthorizeRequest(actionContext)) { return true; } return false; } protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext) { //Code to handle unauthorized request actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.TemporaryRedirect); actionContext.Response.Headers.Add("Location", "~/Index/Subscribe"); } private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext) { //Write your code here to perform authorization } } I believe the IsAuthorized method is the correct way to override the AuthorizeAttribute.
{ "language": "en", "url": "https://stackoverflow.com/questions/40310739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Two Python instances, same libraries I currently have both Python 2.6 and 2.7 running on my Linux machine. Now, from Python 2.7, I can't access the libraries that I installed through package manager for Python 2.6. I tried uninstalling the library and installing it back with Python 2.7 installed as my default runtime. No luck. How can I share libraries between two Python instances? Is there a more correct way to do this than just copying them? If useful: my Linux distro is Debian, and my package manager is apt. A: You should be able to install the files to an external location and define the environment variable PYTHONPATH to point to the directory that contains the modules. A: You should have now both a /usr/lib/python2.6 folder and a /usr/lib/python2.7. Try creating links inside the 2.7 folders to the required files or folders inside the 2.6 folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/5981933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Convert an RDD to a DataFrame in Spark using Scala I have textRDD: org.apache.spark.rdd.RDD[(String, String)] I would like to convert it to a DataFrame. The columns correspond to the title and content of each page(row). A: Use toDF(), provide the column names if you have them. val textDF = textRDD.toDF("title": String, "content": String) textDF: org.apache.spark.sql.DataFrame = [title: string, content: string] or val textDF = textRDD.toDF() textDF: org.apache.spark.sql.DataFrame = [_1: string, _2: string] The shell auto-imports (I am using version 1.5), but you may need import sqlContext.implicits._ in an application. A: I usually do this like the following: Create a case class like this: case class DataFrameRecord(property1: String, property2: String) Then you can use map to convert into the new structure using the case class: rdd.map(p => DataFrameRecord(prop1, prop2)).toDF()
{ "language": "en", "url": "https://stackoverflow.com/questions/33023330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: make cells mandatory to fill in google sheets with javascript I am new to programming. Is there a way of making a cell mandatory to be filled in google sheets or microsoft excel using javascript, where by a message pops up to remind users to fill in the cells.
{ "language": "en", "url": "https://stackoverflow.com/questions/61490910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sum calculation for position in intervals in pandas dataframe I have a pandas dataframe with intervals (define by start and stop) : df = pd.DataFrame( { 'start': [1,1,1,2,2,2,2,3,3,3,3,3,3,3], 'stop': [9,9,10,10,10,11,11,11,11,12,11,12,11,11], 'percent' : [0.51,0.29,0.92,0.60,0.10,0.12,0.60,0.30,0.10,0.42,0.51,0.51,0.51,0.10], 'order':[3,80,3,3,4,8,89,2,3,4,5,64,82,68] } ) Which look like : start stop percent order 1 9 0.51 3 1 9 0.29 80 1 10 0.92 3 2 10 0.60 3 2 10 0.10 4 2 11 0.12 8 2 11 0.60 89 3 11 0.30 2 3 11 0.10 3 3 12 0.42 4 3 11 0.51 5 3 12 0.51 64 3 11 0.51 82 3 11 0.10 68 I want to calculate, for each position (by splitting intervals): total count, sum of value, sum of order NB : original dataframe is not coordinate sorted in the example. I want to end up with a dataframe : pos count sum_percent sum_order 1 3 1.72 86 2 7 3.14 190 3 14 5.59 418 4 14 5.59 418 5 14 5.59 418 6 14 5.59 418 7 14 5.59 418 8 14 5.59 418 9 14 5.59 418 10 12 4.79 335 11 9 3.17 325 12 2 0.93 68 I managed to have the result that i want for the count column like this : max_pos=df[['start', 'stop']].values.max() pos_range=np.arange(1, max_pos+1) counts = ((df[['start']].values <= pos_range) & (pos_range <= df[['stop']].values)).sum(axis=0) o = pd.DataFrame({'pos': pos_range, "counts": counts}) But for the sum of column, i didn't manage to do it. Any help ? Thanks in advance A: Use the boolean variable used to count as an index: import numpy as np import pandas as pd names=["start","stop","percent","order"] vals=np.array([ [1,9,0.51, 3], [1,9,0.29,80], [1,10,0.92, 3], [2,10,0.60, 3], [2,10,0.10, 4], [2,11,0.12, 8], [2,11,0.60,89], [3,11,0.30, 2], [3,11,0.10, 3], [3,12,0.42, 4], [3,11,0.51, 5], [3,12,0.51,64], [3,11,0.51,82], [3,11,0.10,68] ]) df = pd.DataFrame(vals, columns=names) df max_pos=df[['start', 'stop']].values.max() pos_range=np.arange(1, max_pos+1) _ix = ((df[['start']].values <= pos_range) & (pos_range <= df[['stop']].values)) counts = _ix.sum(axis=0) sum_percent=[] for i in _ix.T: sum_percent.append(df["percent"].values[i].sum()) sum_order = [] for i in _ix.T: sum_order.append(df["order"].values[i].sum()) o = pd.DataFrame({'pos': pos_range, "counts": counts, "sum_percent":sum_percent, "sum_order":sum_order})
{ "language": "en", "url": "https://stackoverflow.com/questions/67772460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Annotate datatime calculations How could I cast datetime to seconds and perform calculation on that or directly perform calculation on datetime? for example: User.objects.annotate(min=Min('created'), max=Max('created'), perc=F('created') - min/(max - min)) User model class User(AbstractUser): ... created = models.DateTimeField(auto_now_add=True) How to get the value of perc for each user(I'm using postgres)?
{ "language": "en", "url": "https://stackoverflow.com/questions/63243228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Help with jQuery's .live() method I have a function that dynamically creates links for a photo gallery. The function also produces a larger image as a background image of a div when and thumbnail is clicked on. What I want to do is have a third event, where if the user clicks the enlarged image in the div, the jQuery Fancybox loads an even bigger version of the image being displayed in the div. The problem is that the link for the anchor tag I'm using is created dynamically, and I know that Fancybox parses the HTML when the DOM is ready...unfortunately my function changes the DOM by appending the anchor tag for the full sized image. The help I need is using the Fancybox's options to specify the href attribute for the plugin. I'm sorry that was so long-winded...here's the code. jQuery: function gallery(picid, picnum){ var ext = 'jpg'; var fullSize = 'imgs/'+picid+'_full.'+ext; $('#photolarge').css("background", 'url(imgs/'+picid+'_large.'+ext+') no-repeat'); $('#photolarge a').attr( { href: fullSize //rel: 'lightbox', } ); $("#lightboxlink").click(function(){ $('#lightboxlink').fancybox({ 'autoDimensions' : false, 'width' : 'auto', 'height' : 'auto', 'href' : fullSize }); }); return false; } HTML Snippet <div id="photolarge"> <a id="lightboxlink" href="#"></a> </div> <div id="phototable"> <ul id="photorow1"> <li><a onclick="gallery('bigsun',1)"><img id="sun" src="imgs/bigsun.jpg" /></a></li> </ul> </div> CSS: #photolarge { width: 590px; height: 400px; margin-left: 7px; border: 2px solid; background: none;} #phototable { width: 590px; height: 300px; border: 2px solid; margin: 10px 0 0 7px;} #phototable img { cursor: pointer;} #phototable ul { list-style: none; display: inline;} #phototable li { padding-left: 10px;} #lightboxlink { display: block; height: 100%; width: 100%;} Any help would be greatly appreciated!!! A: Try this and see if it works,this is just fancy box bit though,the rest of your code seems fine $("#lightboxlink").live('click', function(){ $.fancybox({ 'autoDimensions' : false, 'width' : 'auto', 'height' : 'auto', 'href' : $(this).attr('href') }); return false; });
{ "language": "en", "url": "https://stackoverflow.com/questions/3424668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inverse Cosine in Python Apologies if this is straight forward, but I have not found any help in the python manual or google. I am trying to find the inverse cosine for a value using python. i.e. cos⁻¹(x) Does anyone know how to do this? Thanks A: To augment the correct answers to use math.acos, it is also worth knowing that there are math functions suitable for complex numbers in cmath: >>> import cmath >>> cmath.acos(1j) (1.5707963267948966-0.88137358701954294j) Stick with math.acos if you're only interested in real numbers, A: The result of math.acos() is in radians. So you need to convert that to degrees. Here is how you can do: import math res = math.degrees (math.acos (value)) A: We have the acos function, which returns the angle in radians. >>> import math >>> math.acos(0) 1.5707963267948966 >>> _ * 2 - math.pi 0.0 A: In response to using inverse cosine to find return angles via math.acos, it's all fine and dandy so long as the angle is <=90* once you go past that, python will have no way of differentiating which angle you wanted. Observe. >>> math.cos(5) 0.28366218546322625 Above, I asked python to fetch me the cosine of a 5 radian angle, and it gave me .28~ Great, below I'll ask python to give me the radian which has a .28~ cosine. Should be 5, right? It literally just told me it was. >>> math.acos(0.28366218546322625) 1.2831853071795865 Wrong! Python returns 1.28~ radians. The reason is obvious when plotted visually, 1.28rad has the same cosine as 5rad, they're inverse angles. Every angle shares the same sine with another angle (and -sine with two others). i.e. 5/175* share an equivalent sine. They share inversely proportional cosines .99~/-.99 respectively. Their -sine cousins would be 185 and 355. The relationship meme here is that all these angles share the same angular deflection from the horizontal axis. 5*. The reason python returns 1.28 and not 5 is that all computers/calculators are based on an abacus-like data table of an angle/radian, its sine, cos, tan etc etc. So when i math.acos(x), python asks the kernal to look through that data table for whichever angle has a cosine of x, and when it finds it, it returns the first entry it appears with. and then python gives that angle to me. Due to this shared, proportional symmetry, sin/cos ratios repeat frequently. And you are likely to see the same figure, multiple times. There's no way for python, or the OS, to determine the difference of which of the two angles you actually require without doing additional logic that takes into account the -/+ value of the angle's sine. Or, the angle's tangent. 1.28 Rad has x cosine, y sine, z tan (72*) 1.88 Rad has -x cosine, y sine, -z tan (108*) 4.39 Rad has -x cosine, -y sine, z tan (252*) 5 Rad has x cosine, -y sine, -z tan (288*) or, viewed Cartesianly, negX,posY | posX,posY -----+----- negX,negY | posX,negY 1.88 Rad has -x cosine, y sine (108) | 1.28 Rad has x cosine, y sine (72*) -----+----- 4.39 Rad has -x cosine, -y sine (252)| 5 Rad has x cosine, -y sine (288) So if, for whatever reason, i need 5 radians to be chosen (say for a vector drawing or game to determine the various vectors enemies are from the player), i would have to do some type of if/then logic comparing the sines/tangents. A: You're looking for the math.acos() function. A: You may also use arccos from the module numpy >>> import numpy >>> numpy.arccos(0.5) 1.0471975511965979 WARNING: For scalars the numpy.arccos() function is much slower (~ 10x) than math.acos. See post here Nevertheless, the numpy.arccos() is suitable for sequences, while math.acos is not. :) >>> numpy.arccos([0.5, 0.3]) array([ 1.04719755, 1.26610367]) but >>> math.acos([0.5, 0.3]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: a float is required A: or just write a function of your own for the taylor expansion of cos^{-1} this would be more time consuming (and maybe slower to run) but is the more general approach
{ "language": "en", "url": "https://stackoverflow.com/questions/6745464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "54" }
Q: How to use @HiltAndroidApp annotation but there's no Application class in the project? As Android documentation said: All apps that use Hilt must contain an Application class that is annotated with @HiltAndroidApp When I create an Android project from template (Tabs template of Android Studio) it seems not to provide any Application class but class MainActivity : AppCompatActivity() instead. So how can I use Hilt in this project? I have tried this: @HiltAndroidApp class MainActivity : AppCompatActivity() { ... } But it didn't work :< A: Your MainActivity is not the Application class. For activities use the @AndroidEntryPoint. See more on https://dagger.dev/hilt/android-entry-point The annotation @HiltAndroidApp is for the Application class. See more on https://dagger.dev/hilt/application
{ "language": "en", "url": "https://stackoverflow.com/questions/66515230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I exclude multiple terms in Kibana 4 How can I exclude multiple search terms in Kibana 4? If I type in only one term, it excludes it...but how can I have more than one excluded term. For example, the term "not yet classified" A: If I understand your question properly, you're trying to use the "Exclude Pattern" to exclude certain values from populating in the chart. The "Exclude Pattern" and "Include Pattern" fields are for Regular Expressions and are documented here: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html. If you want to exclude multiple fields, you could do something like this: term1|term2|term3 A: The query field in Kibana uses Lucene syntax which has some info at http://www.lucenetutorial.com/lucene-query-syntax.html. To exclude a term containing specific text, use -field: "text" to exclude different texts, I use -field: ("text1" or "text2") If it's two separate fields, try -field1: "text1" -field2: "text2" A: in newer version of kibana if you want to exclude some term use this: not field : "text" if you want to exclude a phrase use this: not field : "some text phrase" you can use other logical operation with not: field: "should have phrase" and not field: "excluded phrase" A: https://www.elastic.co/guide/en/kibana/master/kuery-query.html To match documents where response is 200 but extension is not php or css. response:200 and not (extension:php or extension:css) A: So in the query above the visualization, you can use Lucene syntax to exclude the hits, once saved this will perform the same as an attempt of using regex or Lucene syntax in the Exclude Field of the Buckets advanced options.
{ "language": "en", "url": "https://stackoverflow.com/questions/29174649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: Multi-branching model currently I have a task about branching model I should use. Right now I have master branch and I am branching release branches from time to time to release branches about new features. This is how it looks my branching model right now. master | |---- release 1.0 branch | | | | | | | |----- *(1) needed branch | | | | | | | | | | | | |---- | |--------- | |---- release 1.1 | | | |----- needed branch | | | | | | | | *(1) - Each time release branch is closed for features I make new feature branch and then merge this("needed branch") just before next release. Few questions that might come up reading this. I will edit this as questions are given so I can give the answers in the post * *Why you are closing release branch if you need more features? - The thing is I need to have stable branch(release) at any time after development is "over". What I want to accomplish? The problem with this branching model is that I might have a lot of features and each one of them for different client and many of the clients don't want to wait another 1 or 2 weeks until next deploy. I was thinking of making branch for every client and pushing features there and whenever client want to get given feature I can deploy from there without affecting other clients. Cause right now this is impossible. But this is really bad approach since as the clients grow the branches will too. I want more elegant approach. I understand there will be a lot of questions in the comments so please ask them and lets see if I can answer them and come up with solution or at least an idea. A: It sounds like your problem is not Git: your problem is people. Since these people are paying you, presumably, this seems like the right problem to have! What I would do is this: | * tag:r1 |\______________________ | \ \ \ | * feature1 WIP2 WIP3 | __/ | |/ | * tag:r2 * feature2 | ________________/ |/ * tag:r3 | master In words, I would do all my releases from master, and all my work on feature branches. When a feature is complete, tested, and a client wants it, only then would I merge to master, retest, and make another release. In this way, master is never in a development state; it's always "just released", or "just about to release" (or idle). If WIP3 ("Work in progress 3") takes a long time to develop, the graph would evolve like this: | * tag:r1 |\__________ | \ | WIP3 * tag:r2 | |\__________ | | \| | * merge * tag:r3 | |\__________ | | \| | * merge | | | * feature3 | __________/ |/ * tag:r4 | master (I've deleted the feature1 and feature2 branches, now they're merged, but you'd still see the multiple paths in the history.) If you discover that a client wants a bug fix release to some old version (maybe they paid for support, but didn't pay for new features?), then you can always make a release branch from a tag: | * tag:r1 | * tag:r2 |\_________ * tag:r3 \ | * bugfix * tag:r4 | | * tag:r2.1 master | release2.x_branch
{ "language": "en", "url": "https://stackoverflow.com/questions/34745089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is iOS capable of accessing and manipulating files on a Windows network file share? I'm planning an app for work and venturing into potential features which I've not used before. Essentially I need to be able to access files on a network share, read, write and delete files as well as amend the file names. As a pretty closed platform I'm not sure whether iOS is capable of such a thing and if it is, what features should I look for to begin researching? My Google-Fu hasn't come up with anything thus far so hopefully looking for someone to point me in the right direction. Thanks. A: I know this isn't very secure, but I'd personally create an ASP.NET app on your target Windows Server, or a different Server on the domain. Create web services exposed, and make an iOS app with UIWebView. You can do RPC calls from the web service that do WMI/ADSI/File System manipulation. You can prompt for domain credentials, and do remote calls essentially is the gist. You could expose the web app so that your app can access it from local network, or URL. If you were to access it from outside I'd suggest using some secure credentials in Windows/IIS. Some years ago I created a "mobile-friendly" web app that allowed me to manage servers, perform RPC, and do basic Active Directory queries. Also allowed file listing and deletion/moving/copying with some creative scripting. It was essentially a ASP.NET/C# web app that loaded in a iPhone app. UIWebView in iOS was a able to load it, used AJAX and some other client side scripting that looked decent. You'd essentially have to make sure that your web app renders properly in Safari/UIWebView (which is bastardized safari). Here's a link to a demo of what I created: https://www.youtube.com/watch?v=czXmubijHwQ&t=12s I ran it in a browser, but it'd run from my PSP, Android test devices, iPod Touch, Blackberry, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/42936488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In google sheets, how do you use googlefinance to get the high price of a stock in a date range? I wrote the following formula, and it only returns the high of the starting date and not the high of the entire date range: =INDEX(GoogleFinance(C7,"high", A7,B7,"DAILY"),2,2) where C7 is the google sheet cell that contains the stock symbol and A7 contains the starting date and B7 contains the ending date. A: The formula: =MAX(INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2)) …will return the stock's high price between the dates A7 and B7 in your example.1 How does it work? Using the formula: =GOOGLEFINANCE(<symbol>, "high", <StartDate>, <EndDate>) or =GOOGLEFINANCE(C7, "high", A7, B7) (in your example), …will return an array which looks something like this: Using the INDEX() function, you can convert that array to a single column of the high values: =INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2) Now you can pass that array into the MAX() function to get the highest value in a single cell: =MAX(INDEX(GOOGLEFINANCE(C7, "high", A7, B7), , 2)) 1 Important Note: If you include a date range in GOOGLEFINANCE's "high" function, it will not include today's price during the current trading day — so if you need to include today's high price in your range, you will need to compare today's high price to the historical data explicitly. E.g., the function =GOOGLEFINANCE(symbol, "high") gives you today's high price, so: =MAX(GOOGLEFINANCE(C7, "high"), MAX(INDEX(GOOGLEFINANCE(C7, "high", TODAY()-30, TODAY()), , 2))) …will give you the high price over the last 30 days, including today. If there's a possibility that your date range might include today only (i.e. no historical data where A7 and B7 both equal today), unfortunately, the formula above will return #NA. I have the ultimate solution to generate the correct array even if it does not contain historical data. The Bullet-Proof Solution The formula below traps the #NA condition and builds the array to include today's high no matter what date range is specified: =MAX(INDEX({IFNA(GOOGLEFINANCE(E7, "high", A7, TODAY()), {"Date", "High"}); NOW(), GOOGLEFINANCE(E7, "high")}, , 2)) I've been bitten by this quirk a few times and this solution seems to be cover all scenarios. Enjoy! A: Please try: =max(INDEX(GoogleFinance(C7,"high",A7,B7,"DAILY"),0,2)) 0,2 rather than 2,2 at the end to return the range rather than a cell from it and MAX for the maximum.
{ "language": "en", "url": "https://stackoverflow.com/questions/50421851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to reference a method on the object itself In java I can write Arrays.asList("test ").stream().map(String::trim); If I try this in groovy Arrays.asList("test ").stream().map(String.&trim) I get Caught: groovy.lang.MissingMethodException: No signature of method: java.lang.String.trim() is applicable for argument types: (String) values: [test ] Possible solutions: trim(), wait(), grep(), wait(long), split(java.lang.String), print(java.io.PrintWriter) What is the correct syntax or do I have to resort to Arrays.asList("test ").stream().map({ x -> x.trim() }) ? A: you can use .map { it.trim() } too, but otherwise, groovy does not have method reference working like java one
{ "language": "en", "url": "https://stackoverflow.com/questions/51266993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: stripe.net - how to process subscriptionService.Get with no results The stripe.com API only returns active subscriptions. I want to verify when I delete a subscription. So this is going to return an error. I am not sure how to code for it. I would prefer to make this call based on the subscriptionId. Will this cause an exception or will it return an error code? Retrieving a subscription var subscriptionService = new StripeSubscriptionService(); StripeSubscription stripeSubscription = subscriptionService.Get(*subscriptionId*); Another options which is somewhat of a hack is to return all the subscriptions for the given customer and test to see if the subscriptionId was returned. List all subscriptions for a customer var subscriptionService = new StripeSubscriptionService(); IEnumerable<StripeSubscription> responses = subscriptionService .List(*customerId*); foreach( var response in responses ) { if (response.subscriptionId == subscriptionId) { // subscription exists and was not deleted exit; } } A: Per their documentation, https://stripe.com/docs/api they have 2 different APIs. You're trying to use the RESTful API, which is for retrieving information on demand. They also have a WebHooks API, which requires you have an endpoint listening on your site which can accept event notifications. You configure these through your Dashboard with them. The event type you're looking for specifically is probably the customer.subscription.deleted event, but there's a lot more you can do with them and I'd encourage you to explore all of those Webhooks. I can't offer a code sample, as I don't use their service. A: The strip.net example shows the subscriptionService.Cancel as a methed: var subscriptionService = new StripeSubscriptionService(); subscriptionService.Cancel(*customerId*, *subscriptionId*); But you can also use it as a function and it returns the subscription object. var subscriptionService = new StripeSubscriptionService(); StripeSubscription stripeSubscription = subscriptionService.Cancel(*customerId*, *subscriptionId*); If (stripeSubscription.Status != "canceled") { //subscription not cancelled // take action } Per Stripe API docs: Returns: The canceled subscription object. Its subscription status will be set to "canceled" unless you've set at_period_end to true when canceling, in which case the status will remain "active" but the cancel_at_period_end attribute will change to true.One of the fiels is .status , witch is set to canceled.
{ "language": "en", "url": "https://stackoverflow.com/questions/26529546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which components do what when using Python with OpenCV? I'm quite puzzled about what to use or install, because there are a plethora of components old and new, and the relationship between them is quite unclear to me. There is OpenCV, the C++ library that does the heavy lifting. Then there are various packages that provide Python support, including: * *opencv-python - Python packages for OpenCV; also installs OpenCV itself. Available with import cv2. *pyopencv - a very old library. *python-opencv - a Debian package. *libopencv, described in another question here as "only a metapackage", but its purpose remains unclear to me. Possibly I have missed some... For a modern Python 3 project, which of these components should be used? Using import cv I am trying to use OpenCV with a Django project, that expects to find the library with import cv. That recommends installing python-opencv. It also mentions pyopencv which seems odd, given how old the latter is. What package does make a cv module available? System vs Python packages It looks like python-opencv is a system-level package that also installs Python modules, whereas opencv-python is a Python package that also installs system-level modules. Is that correct? In which case, am I right in thinking that one would install both system and Python libraries using one of these but not both? A: in opencv3 the old cv or cv2.cv api was removed, to use opencv correctly in python is enough with import cv2. another package would be opencv-contrib-python
{ "language": "en", "url": "https://stackoverflow.com/questions/56776166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to insert COUNT value of another table in column of a table Hey I have a two tables Likes And other table Comments I want to total likes in comment table . How can i achieve this . I just write fake query in comments table just for understanding i want effect like that , any ideas please A: INSERT INTO Destination(Col) SELECT COUNT(1) FROM Source; A: You can use triggers to automatically update comments tables based on likes table. The following in an Insert After Trigger which will increment the value of total_likes of the corresponding comment_id by one in comments table when an insert in performed in likes table. You have to give initial value of total_likes for comments as zero when inserting in comments table. CREATE TRIGGER update_likes AFTER INSERT ON likes FOR EACH ROW UPDATE comments SET total_likes = total_likes+1 WHERE comment_id = NEW.comment_id; A: If you want a query that resolve this. I suggest some like this: select comment_id,uploader, (select count(*) from likes l where L.COMMENT_ID =CM.COMMENT_ID ) nlikes from commments cm;
{ "language": "en", "url": "https://stackoverflow.com/questions/40288728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C, Fast way to limit a number to <= 64 Which is the fastest way to limit a number to 64 inclusive (ie. <= 64) len = len > 64 ? 64 : len; /* limit to 64 */ Thanks! A: Don't bother. The compiler optimizes better than you could. You might perhaps try len = ((len - 1) & 0x3f) + 1; (but when len is 0 -or 65, etc...- this might not give what you want) If that is so important for you, benchmark! A: I created a program #include <stdio.h> int main(void) { unsigned int len; scanf("%u", &len); len = len > 64 ? 64 : len; printf("%u\n", len); } and compiled with gcc -O3 and it generated this assembly: cmpl $64, 4(%rsp) movl $64, %edx leaq .LC1(%rip), %rsi cmovbe 4(%rsp), %edx the leaq there loads the "%u\n" string in between - I presume it is because the timing of the instructions. The generated code seems pretty efficient. There are no jumps, just a conditional move. No branch prediction failure. So the best way to optimize your executable is to get a good compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/50492891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to display json data using ng-repeat? I am trying to Json data using ng-repeat. But the web page is either showing as white page or a blank page. The Json: { "questions": { "q1": { "qText": " question1", "result":"result1", "options":{ "A":"option1", "N":"option2", "D":"otpion3", "NA":"option4" } }, "q2": { "qText": " question2", "result":"result2", "options":{ "A":"option1", "N":"option2", "D":"otpion3", "NA":"option4" } }, "q3": { "qText": " question3", "result":"result3", "options":{ "A":"option1", "N":"option2", "D":"otpion3", "NA":"option4" } }, "q4": { "qText": " question4", "result":"result4", "options":{ "A":"option1", "N":"option2", "D":"otpion3", "NA":"option4" } }, "q5": { "qText": " question5", "result":"result5", "options":{ "A":"option1", "N":"option2", "D":"otpion3", "NA":"option4" } }, "q6": { "qText": " question6", "result":"result6", "options":{ "A":"option1", "N":"option2", "D":"otpion3", "NA":"option4" } } } } } The HTML: <div ng-repeat="question in questions track by $index"> <div class="q1"> <p>{{question.qText}}</p> <input type="radio" ng-model="qobj.q1" ng-value="'A'" ><label>{{question.options.A}}</label> <input type="radio" ng-model="qobj.q1" ng-value="'N'" ><label>{{question.options.N}}</label> <input type="radio" ng-model="qobj.q1" ng-value="'D'" ><label>{{question.options.D}}</label> <input type="radio" ng-model="qobj.q1" ng-value="'NA'" ><label>{{question.options.NA}}</label> </div> </div> A: Check whether your questions object is in scope. angular.module("test", []) .controller('ctr1', function($scope) { $scope.save = function(ques){ $scope.showAnswer=true; } $scope.ques = { "q1": { "qText": " question1", "result": "", "options": { "A": "option1", "N": "option2", "D": "otpion3", "NA": "option4" } }, "q2": { "qText": " question2", "result": "", "options": { "A": "option1", "N": "option2", "D": "otpion3", "NA": "option4" } }, "q3": { "qText": " question3", "result": "", "options": { "A": "option1", "N": "option2", "D": "otpion3", "NA": "option4" } } } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script> <div ng-app="test" ng-controller="ctr1"> <form name="testForm"> <ul> <li ng-repeat="q in ques"> {{q.qText}} <input type="radio" ng-model="q.result" ng-value="q.options.A" /><label>{{q.options.A}}</label> <input type="radio" ng-model="q.result" ng-value="q.options.N" /><label>{{q.options.N}}</label> <input type="radio" ng-model="q.result" ng-value="q.options.D" /><label>{{q.options.D}}</label> </li> </ul> <input type="submit" ng-click="save(ques)" value="Submit" /> </form> <div ng-if="showAnswer"> <ul> <li ng-repeat="q in ques"> {{q.qText}}== {{q.result}} </li> </ul> </div> </div> A: Your json does not contain an array, but an object with other objects. Therefore you must let angular know to iterate through its keys: <div ng-repeat="(key, question) in questions track by $index"> <!-- .. --> </div> A: I see what you are trying to do! Your model says : `"questions": { "q1": {...} }, "q2": {...}, ... }` so, questions should be an Array for ng-repeat to work with it! Just a guess, I don't think you will need "q1", "q2" tags at all.. Modify your "questions" model to this: `"questions": [ { "qText": " question1", "result":"result1", "options":{ "A":"option1", "N":"option2", "D":"otpion3", "NA":"option4" } }, {...}, {...}, {...} ]` Remember: ng-repeat is well suited for Collections, and is not meant for Objects. Hope this serves your purpose!
{ "language": "en", "url": "https://stackoverflow.com/questions/42028135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: ways to run external shell commands in sbt How can I run external shell commands once I am in sbt interactive shell? That is, after I type sbt and see the prompt showing up, how can I do things like ls, or cd etc.? There should be a way to do this, correct? Thank you. A: On http://www.scala-sbt.org/release/docs/Community/Community-Plugins.html is a list of SBT plugins. A plugin for your purpose can be https://github.com/steppenwells/sbt-sh .
{ "language": "en", "url": "https://stackoverflow.com/questions/16202024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Doctrine many-to-one association keeps pulling all rows from associated table I'm attempting to set up a many-to-one relationship between a series of sales memos and transaction records. /** * @var TransactionInterface * * @ORM\ManyToOne(targetEntity="Twb\Common\Model\Broker\TransactionInterface") * @ORM\JoinColumn(name="FormNoSeller", referencedColumnName="Form") */ private $formnoseller; /** * @var TransactionInterface * * @ORM\ManyToOne(targetEntity="Twb\Common\Model\Broker\TransactionInterface") * @ORM\JoinColumn(name="FormNoBuyer", referencedColumnName="Form") */ private $formnobuyer; They are split between two different bundles at the moment ('SalesBundle' and 'BrokerBundle'), and with that in mind I am using interfaces from the SalesMemo entity in SalesBundle to the Transaction entity in BrokerBundle. For some reason, when I reference either or both of $formnoseller and $formnobuyer in my forms, I notice in dev.log that, after selecting all Transaction rows matching the $formnoseller and/or $formnobuyer fields in the SalesMemos, Doctrine tries to SELECT all rows in the Transaction table (the entity for which TransactionInterface references). This is a bit of a problem, since there is an innumerable amount of rows in the DB, which takes up a lot of memory. Is there any way to have Doctrine avoid selecting all rows with associations? Or am I even understanding properly how Doctrine does associations? Many thanks for any help. A: My understanding of your problem is that you're using an Entity Field Type for $formnoseller and $formnobuyer (or you don't specify the type). Giving the choice to select any élément from the underlying table is the expected behaviour for the Entity Field Type (Used by default for OneToMany relationships) If you don't whant a select list of all the elements of your table for those Fields, you should use an other form field type. You should also have a look at data transformers in the documentation. A: If it were me, I would write a stored procedure and do an inner or outer join as appropriate. Once upon a time, they called this "client server" code. About 15 years ago, it created such a mess the whole industry moved to n-tier development. I'd like to know how the table joins got placed back into the presentation tier again? ORMs and LINQ-to-SQL are a return to client/server". If you have to do it this way, do the join in LINQ on the Models. Do not do it with the ORM language.
{ "language": "en", "url": "https://stackoverflow.com/questions/18836988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WPF Scale Transform and ScrollViewer - When Zoomed can't scroll beyond original size I have a StackPanel inside of a ScrollViewer. I have a slider that does a scale transform on the stackpanel to allow zoom-in and zoom-out functionality. The problem is that when I zoom in, the scrollviewer doesn't treat the content as being 'bigger'. So, if I scroll in a little and scroll as far right as I can go - it stops me before I get to the end of the content. If I zoom back out to the untransformed level, I see that it's stopping exactly at that point. If I zoom in a lot, I can only see a small fraction of my total content when I scroll all the way over. I can change the TransformOrigin to control which side loses the most content; but I figure there should be some way for the scrollviewer (or another control?) to take care of it for me. A: Are you doing render transform, or layout transform? You should be doing the latter.
{ "language": "en", "url": "https://stackoverflow.com/questions/1579167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jRuby on Rails vs Grails I'm looking to develop a greenfield web application which will reuse a lot of Java components. To me, the obvious options for this are Grails or jRuby on Rails, but I'm having trouble finding objective comparisons of the two. Are there any clear reasons to pick one over the other with respect to: *ease of integration with existing Java components (outside the persistent domain), e.g. JMS, EIP *support for functional testing frameworks *performance on a single machine *scalability I am not looking for answers relating to the availability of developers or activity of communities. (I've checked Grails vs. Rails, and it's not relevant to me) A: I know Grails very well (right now I'm working on a Grails project), but not JRuby, so take this as a probably biased opinion: looking at the JRuby documentation, it looks that JRubys integration with Java is a bit more cumbersome, since Java is more native in Groovy than it is in Ruby; therefore, in JRuby, you have a lot of java-specific keywords and methods (e.g. java_import, java_send). Put simply, Groovy is a language targeted specifically at the Java world, while JRuby is, well, Ruby put on the JVM. Grails has JUnit tests built in. Can't say much about performance and scalability, but given the good integration with Java, one can always write performance-critical parts in Java when Groovy is too slow. A: * *ease of integration with existing Java components: it's easier with groovy, cause groovy is basically java. you do not have big context-switches * *support for functional testing frameworks ruby has it's own pile of testing frameworks like rspec/shoulda/cucumber/steak and tons more. since i like ruby syntax i would prefer those * *performance on a single machine as far as i know, grails is better in multithreading, because rails did not fokus too much on that in the past. they are currently catching up, so it might be tie. * *scalability both scale with the jvm environement. if you have a running infrastructure for java, grails is easier to integrate. A: * *As phoet said, Grails has first-class Spring support, so it's typically very easy to integrate Spring libraries - that's what many plugins do, including the JMS plugin. Java code can either be provided in JARs or put in to the project's src/java directory. Groovy classes can reference Java classes which can reference Groovy classes. It's pretty seamless. *Grails has support for HtmlUnit, Selenium-rc & WebDriver through various plugins. Geb has a lot of interest at the moment, especially when combined with Spock. *Test them. I don't know if there are any recent comparisons, but performance typically depends heavily on your application. http://grails.org/ and http://beta.grails.org/ are both running on a single machine - and both are Grails applications. *I gather it's pretty easy to cluster Grails via Terracotta. You can also do it with plain Tomcat if you want. There are options for distributed caching - SpringSource has its own (commercial) offering in the form of GemFire. Hope that helps, and in the interests of full disclosure I'm a member of the Grails team. A: In the end, you are going to make a decision on personal choice, comfort with the two languages and the availability of resources, but in the end, the fact that Grails is based on Spring led me to the conclusion that it was the right choice for me. I knew that if all else failed I could fall back to utilizing the tried and true Spring Framework A: Try both, and pick the language and environment that suits you best. It's true that the Grails stack out of the box is more suited towards Java integration, but many components are just a few lines of Ruby code away from integration with Rails. Rails 3 is a great release that doesn't require you to use ActiveRecord, in fact it would be trivial to use Hibernate for your models instead. See also DataMapper, MongoMapper and a whole host of database adapters for SQL and NoSQL databases alike. Also, JUnit != functional testing. Instead, have a look at Cucumber + Cucumber-Rails + Capybara + Selenium for an integrated browser automation testing experience. Take a look at https://github.com/elabs/front_end_testing for an example application that demonstrates this stack. I'll suggest that Ruby is better suited as a web integration language, and JRuby hits the sweet spot of making integration with Java easy as well as pleasing while making a wealth of non-Java libraries available to you. Don't think that Groovy automatically wins because it's "closer" to Java. Sometimes you need to step into a refreshingly different environment in order to have a new look at how to solve a problem. Disclosure: as a member of the JRuby team my bias is evident in my answer. A: For newcomers interested in this question in 2012... "With the @CompileStatic, the performance of Groovy is about 1-2 times slower than Java, and without Groovy, it's about 3-5 times slower. (...) This means to me that Groovy is ready for applications where performance has to be somewhat comparable to Java." Performance Test: Groovy 2.0 vs. Java http://java.dzone.com/articles/groovy-20-performance-compared And besides the autor, I've used Groovy since 2008 with great success, not only for CV, just to make job done in time business need. Performance is ever relative to what you want to do. About integration, Grails is really "that good". I've never needed to make one step further to integrate it with existing libraries. On the contrary, the Spring-based nature of Grails made the job even easier. For those who could complain about micro-benchmarks and real use cases, here is a somewhat old (Grails 1.8) but good one with web frameworks (Grails 1.3.7): http://www.jtict.com/blog/rails-wicket-grails-play-lift-jsp/ Hope this helps! PS.: I would like to see recent benckmarks with JRuby and other really dynamic JVM languages.
{ "language": "en", "url": "https://stackoverflow.com/questions/4204416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Downcast of function call failing in Swift I have a dictionary that contains function calls plus a generic method for adding functions to that dictionary. The moment I downcast that generic function so that I can add it to the dictionary, the compiler crashes. You can see that when you put the following code in a playground: import Cocoa class Email:NSObject { var Subject:String = "" } class SMS:NSObject { var Message:String = "" } var allfunc = Dictionary<String, (item: NSObject) -> Void>() func test<T:NSObject>(type:T, myfunc:(item: T) -> Void) { allfunc[NSStringFromClass(type.dynamicType)] = myfunc as? (item:NSObject) -> Void } test(Email(), {item in NSLog("\(item.Subject)")}) test(SMS(), {item in NSLog("\(item.Message)")}) for (key: String, value: (item: NSObject) -> Void) in allfunc { if key == NSStringFromClass(Email().dynamicType) { var mail = Email() mail.Subject = "testing mail" value(item: mail) } else { var sms = SMS() sms.Message = "testing SMS" value(item: sms) } } When I change the test function to this then I't won't crash, but I will lose autocomplete: func test<T:NSObject>(type:T, myfunc:(item: NSObject) -> Void) { allfunc[NSStringFromClass(type.dynamicType)] = myfunc } Is this a compiler bug that you cannot downcast functions, or shouldn't it be possible anyway? Is there an alternative that I can use to create similar functionality? Maybe the code in the playground looks a little strange. It's a modified extract from my project. If you want to see the complete project with the same crash, then have a look at https://github.com/evermeer/EVCloudKitDao A: You can not cast functions. In the current Xcode version 6.2 you will get the following run time exception: Swift dynamic cast failure There is however a workaround for this problem which I implemented in my connect function of https://github.com/evermeer/EVCloudKitDao The solution is to wrap the function instead of casting it. The code will look like this : public var insertedHandlers = Dictionary<String, (item: EVCloudKitDataObject) -> Void>() public var updateHandlers = Dictionary<String, (item: EVCloudKitDataObject, dataIndex:Int) -> Void>() public func connect<T:EVCloudKitDataObject>( type:T, completionHandler: (results: [T]) -> Void, insertedHandler:(item: T) -> Void, updatedHandler:(item: T, dataIndex:Int) -> Void, deletedHandler:(recordId: String, dataIndex:Int) -> Void, errorHandler:(error: NSError) -> Void ) -> Void { func insertedHandlerWrapper(item:EVCloudKitDataObject) -> Void { insertedHandler(item: item as T) } func updatedHandlerWrapper(item:EVCloudKitDataObject, dataIndex:Int) -> Void { updatedHandler(item: item as T, dataIndex: dataIndex) } self.insertedHandlers[filterId] = insertedHandlerWrapper self.updateHandlers[filterId] = updatedHandlerWrapper ... Now the updateHandler still uses the T instead of the EVCloudKitDataObject and in the handler itself you can use the original type and does not need to cast it.
{ "language": "en", "url": "https://stackoverflow.com/questions/25707915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access 2007 Encrypted BackEnd Slow Only With New ACCDB I have encrypted back-end ACCDB on Win/2003 network. Front-end on user workstations. Link tables and make copies. All works perfectly. I open a fresh blank database and link to same back-end. It is extremely slow, but only from a new front-end. Clicking on any tables takes forever to launch. It appears to be a problem only if other users have the front-end application open. I have tried renaming the blank DB to match the one that works; no difference. It appears that if you open one front-end to a back-end ACCDB then another front-end (such as a blank ACCDB with fresh links) to the same back-end experiences serious latency. Any ideas on what might be going on here? A: The solution is to maintain a persistent connection. You want to open a table that is very small (maybe just one record) and keep that open. Then everything else responds quickly. You can also open a form that has a small table as its recordset, as long as it keep the connection open/persistent.
{ "language": "en", "url": "https://stackoverflow.com/questions/2126351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Context menu not working on CSS table I have a table on my webpage. I recently changed this from a HTML table to a CSS one. I have a context menu that displays on each row of my table. The context menu was working on the HTML table but not the CSS one. HTML: (sample of CSS table) <div class="tbody"> <div class="td"><%= products[i].productOwner %></div> <div class="td"><%= products[i].engineeringOwner %></div> <div class="td"><%= products[i].engineeringLead %></div> ... #contextMenu: <ul id="contextMenu"> <li><a href="edit" onclick="location.href=this.href+'?id=' + recordID; return false;">Edit</a></li> <li><a onclick="Confirm.render('Delete', 'Are you sure you want to delete this record?', recordID);">Delete</a></li> </ul> jQuery: $(document).bind('contextmenu', function (e) { e.preventDefault(); e.stopPropagation(); recordID = $(e.target).parent().attr('id'); if ($(e.target).hasClass('td')) { $('#contextMenu').css({ left: e.pageX + 'px', top: e.pageY + 'px' }).show().fadeIn(500, startFocusOut()); } return false; }); I have debugged and confirmed that $(e.target) does have td class so the if statement should be entered
{ "language": "en", "url": "https://stackoverflow.com/questions/36764386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Authorization architecture in microservice cluster I have a project with microservice architecture (on Docker and Kubernetes), and 2 main apps are written in Python using AIOHTTP and Django (also there are and Ingress proxy, static files server, a couple more made with NginX). I'd like to split these Python apps into separate smaller microservices, but to accomplish this probably I also should move authentication in a separate app. But how can I do this? Probably I should also add that I'm asking not about specific authentication methods like OAuth, JWT, etc, but about dependencies and responsibilities splitting inside cluster architecture. To my mind, a nice solution would be some plugin to Ingress NginX proxy server, or a microservice before it, so that my Python authenticating proxy won't care about methods destination, like some middleware, just read headers/cookies, check access token or sessionId, then set userId if the access is valid, and pass the request further. A brief and simplified architecture is presented below: And here is what I imagine, mention fewer complicated connections: But I'm not sure if this is reasonable. In addition, such approach would reduce advantages of K8s Ingress, which provides amazing interface for updating path table from the bash, but, as far as I know, doesn't allow to run any request handler before it, so I'll have to run custom NginX proxy without nice K8s integration. Thus, what are other possible architectural solutions? I could only imagine creation of a single request handler, that performs all the authorisation and passes requests to other microservices (or by RPC), which don't care about authentication, but I don't think this is a generally perfect solution. A: Theory Well, I found a lot of info after digging on the Internet and one and a half of consultations. There is an architectural pattern named API Gateway, which describes an entry point in a cluster, and this is just what Kubernetes Ingress does, and what I imagined in my question. In a general case, it is proxy server, which is the only entry point to the cluster microservices, and it may perform caching, DDoS protection, it may support different API protocols, manipulate URIs, manage API throttling, monetisation, and perform the authentication I need. Therefore, there is no authentication during microservices communication inside the cluster, because all the required arguments, identifiers will be presented in the requests. Implementation In Kubernetes, NginX Ingress is quite popular, it also supports Basic Auth and OAuth2, which is not a perfect solution, but at least something. There are alternative Ingress solutions for Kubernetes: Kong, Ambassador, Traefik, which provide much more features (though Kong is based on NginX too). In the world of Java and Spring the Spring Cloud Gateway exists to solve such problems, which, just like K8s Ingress, allows to describe path tables with YAML, yet it is extendable, allows to easily embed your custom code for any authentication method. Besides, most of cloud platforms provide their own API gateway services with more or less features, including Google Cloud, Red Hat, AWS, Yandex Cloud. However, it seems they lack authentication methods just like opportunity to be extended, though they aren't much relevant in this question. To read You can find more about API Gateway pattern and it's implementations here: * *microservices.io: API Gateway pattern *RedHat: What does an API gateway do? *kubernetes.github.io: NginX Ingress External OAUTH Authentication *learnK8S.io: Kubernetes API Gateway *cloud.spring.io: Spring Cloud Gateway A: With microservices, JWT are preferred way of authentication & authorization. You can use cloud resources like GCP IAM or OKTA. OR you can run Keycloak in your cluster as a microservice. * *User is created in one of these resources. *Once the user has authenticated, a JWT token is returned (to frontend). *Token contains authentication & authorization related info for that user. *This token is again sent from frontend to backend services in each request. *Backend service will check authentication and authorization and respond accordingly. Also token is normally valid for fixed amount of time. So frontend app should refresh the token periodically.
{ "language": "en", "url": "https://stackoverflow.com/questions/64687757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Imagemagick issues with Ruby I'm trying to run a ruby script from the command line, and getting the following error: /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require': dlopen(/Users/.../.rvm/gems/ruby-1.9.2-p320@stitching_cron/gems/rmagick-2.13.2/lib/RMagick2.bundle, 9): Library not loaded: /opt/local/lib/libMagickCore.6.dylib (LoadError) I've installed ImageMagick using brew install imagemagick and the command line utilities are available as expected. Not sure what's happening here. I tried running sudo find / -type f -name "libMagickCore.6.dylib" to see if I can perhaps symlink the file into the location Ruby is looking for the library, but couldn't find it... Any idea how to fix? A: try this: rvm get head rvm pkg remove rvm reinstall 1.9.2-p320 --with-opt-dir=$(brew --prefix imagemagick)
{ "language": "en", "url": "https://stackoverflow.com/questions/15026367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQueryUI droppable and sortable - cant change the order and few bugs i cant fix I have put most of the code together, just cant get few things working: - * *Items in the "Selected DVD's" area I need to be able to change the order of these DVDs in this list only, so i can change the order from 1,2,3 to 3,1,2. *Items in the "Un-selected" area wont drag up into the selected dvds area *If i click on the link at the top "add all unselected dvd's" and then click on the link "Remove all selected dvds" it doesnt add them into the correct area at the bottom. However if you click the "Remove all selected dvds" link first... it works *Following #3 if i then add a new dvd at the top right, sometimes it adds loads of the same dvd? Here is a working demo of what i have so far: http://jsfiddle.net/BFWzS/1/ There is more code in the fiddle above ^ // let the gallery items be draggable $( "li", $gallery ).draggable({ cancel: "a.ui-icon", // clicking an icon won't initiate dragging revert: "invalid", // when not dropped, the item will revert back to its initial position containment: "document", helper: "clone", cursor: "move" }); // let the trash be droppable, accepting the gallery items $trash.droppable({ accept: "#gallery > li", activeClass: "ui-state-highlight", drop: function( event, ui ) { deleteImage( ui.draggable ); } }); Hope someone can help us out, Cheers A: As my comments have suggested, you should break this down into more specific problems and ask them as separate questions. But here is some information to help you out: * *Check out JQuery Sortable *Check out the Connect Lists option [EDIT] In your JSFIddle, your problem doesn't exist for me (in Chrome) *This should be a separate question (although you can probably find a duplicate of this already) *If not solved by your answer to 3, then should be an additional question For the purposes of a more meaningful answer, here is some sample code showing the use of JQuery Sortable: <div class="container"> <div class="header">Selected DVDs</div> <ul id="gallery" class="dvdlist"> <li>DVD 1</li> <li>DVD 2</li> <li>DVD 3</li> </ul> </div> <div class="container"> <div class="header">Un-selected DVDs</div> <ul id="trash" class="dvdlist"> <li>DVD 4</li> <li>DVD 5</li> <li>DVD 6</li> </ul> </div> $("#gallery").sortable({ connectWith: "#trash" }); $("#trash").sortable({ connectWith: "#gallery" }); You can see this in action here.
{ "language": "en", "url": "https://stackoverflow.com/questions/15545578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to delete or invalidate gecko / firefox session without closing browser? Is it possible, using the gecko / firefox XPCOM interfaces, to delete or invalidate a user's active session without closing the browser? I am using Gecko embedded (specifically GeckoFX) in an application where it is possible that multiple users might use the browser component across the lifetime of the application. The application packages web browsing with various other functionality, and when the web browser is 'closed', the app remains open. It seems that as far as the gecko engine is concerned, as the process hasn't closed, the active session is still active. If a user is to log into Gmail or Facebook, for instance, and then close the browser, upon reopening the browser and navigating back to one of those pages, that user is determined to still be logged in. As multiple users can use the application without the application actually exiting, this raises privacy issues. I have tried calling NS_InitXPCOM2 and NS_ShutdownXPCOM within the constructor / dispose method of the browser control, however NS_InitXPCOM2 cannot be called after NS_ShutdownXPCOM within the lifetime of the process, so this simply crashes. I have also used the PurgeHistory method of nsISHistory and the evictEntries method of nsICacheService - none of these appear to have an immediate effect within the life of the process. Does anyone know of any XPCOM interfaces that can achieve this? Alternatively, any pointers in direction of similar functionality, be it through XPCOM interfaces or Firefox extensions would be greatly appreciated (are there any extensions that allow you to clear your current browsing session without reopening the browser? or that provide you a different session between each Firefox window / tab?) The program is written in C#, however answers in any language are appreciated. Many thanks A: I finally found the interface that seems to allow this: nsICookieManager removeAll() Relevant C# interfaces / code for those using GeckoFX: [Guid("AAAB6710-0F2C-11d5-A53B-0010A401EB10"), ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface nsICookieManager { void removeAll(); void remove(string aDomain, string aName, string aPath, bool aBlocked); } and Xpcom.GetService<nsICookieManager>("@mozilla.org/cookiemanager;1").removeAll(); in appropriate location.
{ "language": "en", "url": "https://stackoverflow.com/questions/2308170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to send an email with attachment in C# I created a button that changes the name of fields on a word document. Now I'd like to send that document in an email with the same button. I looked at many tutorials but none of them were successful private void button2_Click(object sender, EventArgs e) { var application = new Microsoft.Office.Interop.Word.Application(); var document = new Microsoft.Office.Interop.Word.Document(); document = application.Documents.Add(Template: @"D:\test\test.docx"); application.Visible = true; foreach (Microsoft.Office.Interop.Word.Field fush in document.Fields) { if (fush.Code.Text.Contains("Name")) { fush.Select(); application.Selection.TypeText(txtE.Text); } else if (fush.Code.Text.Contains("LastName")) { fush.Select(); application.Selection.TypeText(txtM.Text); } document.SaveAs(FileName: @"D:\test\testsave.docx"); } } A: Straight from the horses mouth: public static void CreateMessageWithAttachment(string server) { // Specify the file to be attached and sent. // This example assumes that a file named Data.xls exists in the // current working directory. string file = "data.xls"; // Create a message and set up the recipients. MailMessage message = new MailMessage( "jane@contoso.com", "ben@contoso.com", "Quarterly data report.", "See the attached spreadsheet."); // Create the file attachment for this e-mail message. Attachment data = new Attachment(file, MediaTypeNames.Application.Octet); // Add time stamp information for the file. ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(file); disposition.ModificationDate = System.IO.File.GetLastWriteTime(file); disposition.ReadDate = System.IO.File.GetLastAccessTime(file); // Add the file attachment to this e-mail message. message.Attachments.Add(data); //Send the message. SmtpClient client = new SmtpClient(server); // Add credentials if the SMTP server requires them. client.Credentials = CredentialCache.DefaultNetworkCredentials; try { client.Send(message); } catch (Exception ex) { Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", ex.ToString() ); } // Display the values in the ContentDisposition for the attachment. ContentDisposition cd = data.ContentDisposition; Console.WriteLine("Content disposition"); Console.WriteLine(cd.ToString()); Console.WriteLine("File {0}", cd.FileName); Console.WriteLine("Size {0}", cd.Size); Console.WriteLine("Creation {0}", cd.CreationDate); Console.WriteLine("Modification {0}", cd.ModificationDate); Console.WriteLine("Read {0}", cd.ReadDate); Console.WriteLine("Inline {0}", cd.Inline); Console.WriteLine("Parameters: {0}", cd.Parameters.Count); foreach (DictionaryEntry d in cd.Parameters) { Console.WriteLine("{0} = {1}", d.Key, d.Value); } data.Dispose(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/22083214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Effective way to cache GameObjects including meshes/textures? Problem: If possible, I want to cache full GameObjects including meshes that don't exist in the assets, in a way such that I can load them roughly equally quickly as if they were just one of the assets. Even on closing and reopening the app. Context: I'm working on an app where I get arbitrary 3D objects from the backend like this: * *Download data for 3D meshes from the backend in a byte array *Convert byte[] to GameObjects with Meshes and Texture2D etc. using a plugin (https://github.com/atteneder/glTFast). Step 2 can take about 2 seconds per asset and uses blocking methods, so the screen freezes. I could probably pretty easily cache the byte[] to skip the downloading step for repeated assets, but then it still freezes the entire screen, potentially for a pretty long time if there are a lot of assets. Is there a more effective way to store the entire GameObject that the plugin creates, including meshes and textures etc. that loads (close to) as quickly as a normal asset?
{ "language": "en", "url": "https://stackoverflow.com/questions/71718077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Number of iterators depending of a variable with np.nditer I have to iterate over numpy arrays whose the number can be different at each iteration of the program. The goal is to calculate the variance between the same element of these arrays. Here is the code I wrote : for a,s,m in np.nditer([cost_surfaceS[i].ravel() for i in range(0,len(cost_surfaceS),1)]): arr = [a, s, m] if(float(arr[0]) != float("-inf")): variance = np.var(arr,dtype = np.float32) variances.append(variance) else: variances.append(float("-inf")) where cost_surfaceS is a list that contains all my numpy arrays. The issue is that this piece of code works for 3 numpy arrays created and I want to change the "a,s,m" in order to have a number of iterators that depends of the number of numpy arrays created (i.e. len(cost_surfaceS)) . Is it a way to do it ? A: I agree with @Bickknght that the unpacking is unnecessary. Don't use unpacking when dealing with an unknown or variable number of elements. In [57]: alist = [np.arange(10), np.arange(10,20), np.arange(20,30)] Making a list of arrays where the we don't need the ravel. In [58]: for arr in np.nditer(alist): ...: print(arr) ...: (array(0), array(10), array(20)) (array(1), array(11), array(21)) (array(2), array(12), array(22)) (array(3), array(13), array(23)) (array(4), array(14), array(24)) (array(5), array(15), array(25)) (array(6), array(16), array(26)) (array(7), array(17), array(27)) (array(8), array(18), array(28)) (array(9), array(19), array(29)) Compare this with a straight forward list zip iteration: In [59]: for arr in zip(*alist): ...: print(arr) ...: (0, 10, 20) (1, 11, 21) (2, 12, 22) (3, 13, 23) (4, 14, 24) (5, 15, 25) (6, 16, 26) (7, 17, 27) (8, 18, 28) (9, 19, 29) The difference is that nditer makes 0d arrays rather than scalars. So the elements have a shape ((0,)) and dtype. Or in some cases where you want to modify the arrays (but they have to be defined as read/write. Otherwise nditer does not offer any real advantages. In [62]: %%timeit ...: ll = [] ...: for arr in np.nditer(alist): ...: ll.append(np.var(arr)) ...: 539 µs ± 17.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [63]: %%timeit ...: ll = [] ...: for arr in zip(*alist): ...: ll.append(np.var(arr)) ...: 524 µs ± 3.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) If you can avoid the Python level loops, things will be lot faster: In [65]: np.stack(alist,1) Out[65]: array([[ 0, 10, 20], [ 1, 11, 21], [ 2, 12, 22], [ 3, 13, 23], [ 4, 14, 24], [ 5, 15, 25], [ 6, 16, 26], [ 7, 17, 27], [ 8, 18, 28], [ 9, 19, 29]]) In [66]: np.var(np.stack(alist,1),axis=1) Out[66]: array([66.66666667, 66.66666667, 66.66666667, 66.66666667, 66.66666667, 66.66666667, 66.66666667, 66.66666667, 66.66666667, 66.66666667]) In [67]: timeit np.var(np.stack(alist,1),axis=1) 66.7 µs ± 1.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) I've not attempted to test for -inf. === Another important difference with nditer. It iterates on all elements in a flat sense - in effect it is do the ravel: Make a list of 2d arrays. In [81]: alist = [np.arange(10.).reshape(2,5), np.arange(10,20.).reshape(2,5), np.arange(20,30.).reshape(2,5)] PLain iteration operates on the first dimension - in this case the 2, so zipped elements are arrays: In [82]: for arr in zip(*alist): ...: print(arr) ...: (array([0., 1., 2., 3., 4.]), array([10., 11., 12., 13., 14.]), array([20., 21., 22., 23., 24.])) (array([5., 6., 7., 8., 9.]), array([15., 16., 17., 18., 19.]), array([25., 26., 27., 28., 29.])) nditer generates the same tuples as in the 1d array case. Some cases that's fine, but it's hard to avoid if if you don't want it. In [83]: for arr in np.nditer(alist): ...: print(arr) ...: (array(0.), array(10.), array(20.)) (array(1.), array(11.), array(21.)) (array(2.), array(12.), array(22.)) (array(3.), array(13.), array(23.)) (array(4.), array(14.), array(24.)) (array(5.), array(15.), array(25.)) (array(6.), array(16.), array(26.)) (array(7.), array(17.), array(27.)) (array(8.), array(18.), array(28.)) (array(9.), array(19.), array(29.)) A: The zip function is a solution here, as explained by @hpaulj. Working with 2d arrays instead of 1d simply requires to use two times this function, as the following code shows : variances = [] for arr in zip(*cost_surfaceS): for element in zip(*arr): if(float("-inf") not in element): variance = np.var(element, dtype=np.float32) variances.append(variance) else: variances.append(float("-inf")) The -inf values are handled by the if condition that avoids computing the variance of arrays containing at least one infinity value.
{ "language": "en", "url": "https://stackoverflow.com/questions/56821141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to reformat dataframe using pandas? I have the following dataframe: data = {'Names':['Abbey','English','Maths','Billy','English','Maths','Charlie','English','Maths'],'Subject Grade':['Student Name',85,91,'Student Name',82,74,'Student Name',83,96]} df = pd.DataFrame(data, columns = ['Names','Subject Grade']) I would like to reformat the dataframe in order for the names, subject and grades to all be in their respective columns as follows: data2 = {'Names':['Abbey','Abbey','Billy','Billy','Charlie','Charlie'],'Subject':['English','Maths','English','Maths','English','Maths'],'Grade':[85,91,82,74,83,96]} df2 = pd.DataFrame(data2, columns = ['Names','Subject','Grade']) A: Hi you can use those instructions : df['name'] = df['Names'].mask(df['Subject Grade'] != "Student Name") df['name'] = df['name'].fillna(method='ffill') df = df.query('`Subject Grade`!="Student Name"') df = df.rename(columns={'Names':'Subject', 'Subject Grade':'Grade', 'name':'Names'})
{ "language": "en", "url": "https://stackoverflow.com/questions/64859945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to store long binary (up to 512 bit) in C# I'm trying to figure out the best way to store large binary (more than 96 bit) numbers in C# I'm building application that will automatically allocate workers for shifts. Shifts can be as short as 15 minutes (but this might be even smaller in the future). To avoid double-booking of workers, I plan to have binary map of their daily time: 24 hours separated in equal chunks (15 minutes) and every chunk has a flag (0 for free, 1 for busy) So when we try to give another shift to a worker, we can do binary comparison of workers daily availability with shift's time. Simple and easy to decide. But C# long only allows to have up to 64 bit, and with the current set up I need at least 96 bits (24 hours * 60 minutes / 15 minutes per period). This representation must be memory friendly, as there will be about a million objects operated at a time. Few other options i considered: * *String. Memory-hungry, not simple to implement bit-wise operations *Array of bits. But as far as I know C# does not have bit type *Array of unsigned integers. Each array represents only part of a day. The best I can think of Any other suggestions?? Thanks in advance! A: Have you looked at the BitArray class? It should be pretty much exactly what you're looking for. A: Try following, .Net 4 has inbuilt BigInteger type http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx .Net 2 project on code project http://www.codeproject.com/KB/cs/biginteger. Another alternative, http://www.codeplex.com/IntX/ A: Unless you have millions of employees that all need to be scheduled at the same time, I'd be tempted to store your 96 booleans as a char array with 0 meaning "free" and 1 meaning "busy". Simple to index/access/update. The rest of the employees schedules can sit in their database rows on disk where you simply don't care about "96 megabytes". If you can find a class which implements a bit array, you could use that. (You could code one easily, too). But does it really matter spacewise? Frankly, if your organization really has a million employees to schedule, surely you can afford a machine which has space for a 96 mB array as well as the rest of your code? The one good excuse I can see for using bit vectors has to do with execution time cost. If you scheduling algorithm essentially ANDs one employee bit vector against another looking for conflicts, and does that on large scale, bit vectors might reduce the computation time to do this by a factor of roughly 10 (use a two *long*s per employee to get your 96 bits). I'd wait till my algorithm worked before I worried about this. A: You could use and array of bytes. I don't think any language supports an array of bits, as a byte is the smallest addressable piece of memory. Other options are an array of booleans, but each boolean I believe is stored as a byte anyway, so there would be wasted memory, but it might be easier to work with. It really depends on how many days you are going to work with. You could also just store the start and end of the shift and use other means to figure out if there are overlapping schedules. This would probably make the most sense, and be the easiest to debug. A: BitArray has already been mentioned, it uses an array of ints much like you planned to do anyway. That also means that it adds an extra layer of indirection (and some extra bytes); it also does a lot of checking everywhere to make sure that eg the lengths of two bitarrays is the same when operating on them. So I would be careful with them. They're easy, but slower than necessary - the difference is especially big (compared to handling the array yourself) for smallish bitarrays.
{ "language": "en", "url": "https://stackoverflow.com/questions/6632084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to add css of a div when checkbox checked? The Code: #menu-open:checked ~ .logoib { -webkit-filter: invert(100%); filter: invert(100%); } <div id="logo" class="logoib"></div> <input type="checkbox" id="menu-open"> <nav class="menu-list"> <a href="#" class="firsta">Home</a> <a href="#">My Works</a> <a href="#">Contact</a> </nav> <label for="menu-open" class="modmenu logoib"> <span></span> </label> I want to add some CSS of #logo when the checkbox of menu is checked. A: css cant affect anything before it, it can only affect stuff after the targeted element change like below #menu-open + #logo { color: #ccc; font-style: italic; } #menu-open:checked + #logo { color: #f00; font-style: normal; } <input type="checkbox" id="menu-open"> <div id="logo" class="logoib"> my logo here </div> <nav class="menu-list"> <a href="#" class="firsta">Home</a> <a href="#">My Works</a> <a href="#">Contact</a> </nav> <label for="menu-open" class="modmenu logoib"> <span></span> </label> A: You could use pure JS, JQuery or CSS. Here is a pure JS solution. If you want to set it also on load, you could call myFunction when the DOM is ready. function myFunction() { var cb = document.getElementById('menu-open'); var logo = document.getElementById('logo'); if (cb.checked) { logo.setAttribute("class", "newClass"); } else { logo.removeAttribute("class"); } } #menu-open:checked~.logoib { -webkit-filter: invert(100%); filter: invert(100%); } .newClass { color: red; } <div id="logo" class="logoib">Logo </div> <input type="checkbox" id="menu-open" onchange="myFunction()"> <nav class="menu-list"> <a href="#" class="firsta">Home</a> <a href="#">My Works</a> <a href="#">Contact</a> </nav> <label for="menu-open" class="modmenu logoib"> <span></span> </label>
{ "language": "en", "url": "https://stackoverflow.com/questions/36437393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to include github html file in html with php ? Suppose I have a HTML file as -- https://raw.github.com/USER/PROJECT/master/file.html How do I make it available in my website. One method will be using the rawgithub service and then using something like iframe but I want the HTML to be inherited in my website so that Google shows it in the searches. php's include function looks like doing the trick but I don't get it to work. I simply use include "<file_full_URL>"; A: In PHP you can use the file_get_contents() function to grab files over the internet. $html = file_get_contents('https://raw.github.com/USER/PROJECT/master/file.html'); echo $html; Your pages will be slower if you do this, though. Setting up a cronjob that downloads the file to your server periodically, and then serving it from your server, is a much better idea. A: $url = "http://www.example.com"; //write your raw.github.com URL $gethtml = file_get_contents($url); echo $gethtml; //output the content in the page A: if you want to show it as code you can use this jquery plugin for that
{ "language": "en", "url": "https://stackoverflow.com/questions/20717657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TypeError: trace(): argument 'input' (position 1) must be Tensor, not method I get this weird error when I start my script I really don't know why this error is caused or by what it's caused. It would be very very nice if some of you guy's could help me out with this error:) Error message: File "c:/Users/supre/Documents/Python Programs/neuralnet/optimize_graph.py", line 11, in trace traced = torch.trace(model.forward)(xample_inputs=(x, hidden)) TypeError: trace(): argument 'input' (position 1) must be Tensor, not method This is my code: import argparse import torch from model import SpeechRecognition from collections import OrderedDict def trace(model): model.eval() x = torch.rand(1, 81, 300) hidden = model._init_hidden(1) traced = torch.trace(model.forward)(xample_inputs=(x, hidden)) return traced def main(args): print("loading model from", args.model_checkpoint) checkpoint = torch.load(args.model_checkpoint, map_location=torch.device('cpu')) h_params = SpeechRecognition.hyper_parameters model = SpeechRecognition(**h_params) model_state_dict = checkpoint['state_dict'] new_state_dict = OrderedDict() for k, v in model_state_dict.items(): name = k.replace("model.", "") # remove `model.` new_state_dict[name] = v model.load_state_dict(new_state_dict) print("tracing model...") traced_model = trace(model) #print(type(traced_model)) print("saving to", args.save_path) traced_model.save(args.save_path) print("Done!") if __name__ == "__main__": parser = argparse.ArgumentParser(description="testing the wakeword engine") parser.add_argument('--model_checkpoint', type=str, default='NameOfYourCheckpoint', required=False, help='Checkpoint of model to optimize') parser.add_argument('--save_path', type=str, default='path/where/you/want/to/save/the/optimized/model', required=False, help='path to save optmized model') args = parser.parse_args() main(args) Thank's for every help in advance A: In traced = torch.trace(model.forward)(xample_inputs=(x, hidden)) you are passing a method i.e model.forward you should be using something like this traced = torch.trace(model.forward(x)) if your model is already had an instance with parameters
{ "language": "en", "url": "https://stackoverflow.com/questions/66924471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does the EclEmma coverage tool perform node or edge or condition or path coverage? I have a question about EclEmma coverage tool, Does the EclEmma coverage tool perform node or edge or condition or path coverage? Explain Thank you A: EclEmma - is Eclipse plugin based on Java Code Coverage Library called JaCoCo that performs analysis of Java bytecode. Description of coverage counters provided by JaCoCo can be found in its documentation. As you can see in it - JaCoCo and hence EclEmma provide * *instructions coverage *branch coverage *line coverage *and cyclomatic complexity Don't know what you call node coverage, and I'm guessing that what you call edge coverage - is branch coverage. Regarding condition coverage - Wikipedia says if (a && b) { /* ... */ } condition coverage can be satisfied by two tests a=true, b=false, a=false, b=true what seems a bit weird in case of Java where && is a short-circuit operator - second test can't trigger retrieval of value of "b". Regarding path coverage - JaCoCo does not provide it, what can be demonstrated using following example: void fun(boolean a, boolean b) { if (a) { /* ... */ } if (b) { /* ... */ } } Not counting exception there are 4 paths thru this method. And so for full path coverage 4 tests will be required - a = true, b = true, a = true, b = false, a = false, b = true and a = false, b = false. However JaCoCo and EclEmma would report 100% coverage after just 2 tests - a = true, b = true and a = false, b = false.
{ "language": "en", "url": "https://stackoverflow.com/questions/42049091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nested Jasmine Spies on SpyObj I have a constructor that receives a spyObj called TestService: constructor(private testService: TestService) { testService.getTestData().subscribe((settings) => { this.settings = settings; } } Using Jasmine, how can I create spies for subscribe() and getTestData() on TestService? Thanks in advance! Mike
{ "language": "en", "url": "https://stackoverflow.com/questions/49265181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Image size is too small while uploading from local storage, Microsoft Face API I m calling Microsoft Face API for detecting the face in an image. While loading an image from local , I always get an error as below { code: 'InvalidImageSize', message: 'Image size is too small.' } But using the same image via URL , its working fine. const fs = require("fs"); const axios = require("axios"); axios({ method : "post", url : " https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true", headers : { 'Content-Type': 'application/octet-stream', "Ocp-Apim-Subscription-Key" : "2da8e41a647c4079b2f9a6XXXXXXXXX" }, body : fs.readFileSync("./photos/shiva3.jpeg").toString("base64") }).then((res)=>{ console.log("Response"); console.log(res.data); }).catch((err)=>{ console.log(err.response.data.error); }) A: I have fixed the issue by calling default function in the axios. const axios = require("axios").default;
{ "language": "en", "url": "https://stackoverflow.com/questions/46790435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to iterate through a directory and sub-directories using a URL I'm trying to iterate through files in a directory and files in sub-directories within: <?php $dir = get_stylesheet_directory_uri() . '/js'; echo $dir; $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST ); foreach ( $iterator as $path ) { if ($path->isDir()) { print('<div> DIR : ' . $path . PHP_EOL . "</div>"); } else { $path_parts = pathinfo($path); $file_parts = $path_parts['extension']; if ($file_parts == "js") { $array = explode("/opt/lampp/htdocs", $path); unset($array[0]); echo $path = implode("/", $array); print("<div>http://localhost$path" . PHP_EOL . "</div>"); echo("<script src='http://localhost/$path'></script>"); } else if ($file_parts == "css") { echo("<script src='http://localhost/$path'></script>"); echo("<link rel='stylesheet' href='http://localhost/$path'>"); } } } ?> I, however, get the error: Fatal error: Uncaught UnexpectedValueException: RecursiveDirectoryIterator::__construct(http://localhost/projects/wordpress_projects/wp-content/themes/rev_cust/js): failed to open dir: not implemented in /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php:40 echo $dir; gives: http://localhost/projects/wordpress_projects/wp-content/themes/rev_cust/js The StackTrace: Fatal error: Uncaught UnexpectedValueException: RecursiveDirectoryIterator::__construct(http://localhost/projects/wordpress_projects/wp-content/themes/rev_cust/js): failed to open dir: not implemented in /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php:40 Stack trace: #0 /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php(40): RecursiveDirectoryIterator->__construct('http://localhos...') #1 /opt/lampp/htdocs/projects/wordpress_projects/wp-includes/template.php(684): require_once('/opt/lampp/htdo...') #2 /opt/lampp/htdocs/projects/wordpress_projects/wp-includes/template.php(643): load_template('/opt/lampp/htdo...', true) #3 /opt/lampp/htdocs/projects/wordpress_projects/wp-includes/general-template.php(45): locate_template(Array, true) #4 /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/index.php(18): get_header() #5 /opt/lampp/htdocs/pro in /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php on line 40 How can I fix it and make it work right? Thank you all in advance. A: RecursiveDirectoryIterator::__construct expects a path not a uri. To fix this try: $dir = get_stylesheet_directory() . '/js'; // This gives you a path instead A: You are passing an URL, while you have to pass a path. Check it here: http://php.net/manual/en/class.recursivedirectoryiterator.php
{ "language": "en", "url": "https://stackoverflow.com/questions/44138906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django manually fail transaction after done with for loop I'm trying to run over a for loop that validates objects and saves them, and I want to fail it all if at least one have failed, but only after going over all the objects. I've tried different approaches, but on all of them - even if there was an exception, at least one object was saved to DB. In the latest version, see below, I'm trying to set transaction.set_rollback(True) if at least on exception was raised. try: is_failed = False with transaction.atomic(): for identifier, spec in spec_dict.items(): try: spec_data = {'title':my_title, 'identifier': identifier, 'updated_by': user_id, 'created_by': user_id } serializer = SpecSerializer(data=spec_data) serializer.is_valid(raise_exception=True) serializer.save() except DataError as DE: print("** in DataError") is_failed = True pass except ValidationError as VE: print("** in ValidationError") print(str(VE)) is_failed = True pass except Exception as Exc: print("** inside Exception: " + str(Exc)) is_failed = True pass if is_failed: transaction.set_rollback(True) except IntegrityError: print("** inside integrity error") pass Seems like the 'set_rollback' doesn't affect the transaction. Worth to mention that all our http requests are wrapped in transaction. EDIT: Should transaction.atomic() work for non view functions? Couldn't find answer for that A: So, apparently - transaction.atomic(): is managing the transaction for the 'default' DB by default, unless other DB is mentioned: transaction.atomic(using='otherDB'): Since we use more than one DB and the one that I worked on was not set as the default, I was missing the 'using'.
{ "language": "en", "url": "https://stackoverflow.com/questions/49362590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Product management System Tracking with Google Tag Manager I am working on Product Management system site in which on the enquiry of a product i fill a contact us form which has the info of that product as follows as soon as the form is submitted it leads me on the thank you page where I have added the following code in order to track it using GTM <?php $enquiry_id = ""; $enquiry_id = $this->session->userdata('enq_id'); $product_data = ""; $product_data = $this->session->userdata('enq'); echo "<!--<pre>"; print_r($product_data); echo "<pre>-->"; if (!empty($product_data) && !empty($enquiry_id) && isset($product_data)){ ?> <script> <?php foreach($product_data as $value){ ?> dataLayer.push({ 'ecommerce': { 'purchase': { 'actionField': { 'id': '<?php echo $enquiry_id?>' // Transaction ID. }, 'products': [{ 'name': '<?php echo $value ?>', 'id': '<?php echo $enquiry_id?>', 'price': '0.0', 'quantity': 1 }] } } }); <?php } ?> </script> <?php $this->session->unset_userdata('enq_id'); $this->session->unset_userdata('enq'); } ?> <script> Now the thing is I am able to get the values in the GTM debugger as well as i can see them in view source but the values dont show up in Google Analytics , So is there any other way to get the values in the Conversion->Ecommerce section of GA.I have set the track type as Transaction in GTM. Thanking you in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/32884917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JOIN inside a SELECT MAX in Postgres I have the following query that returns these two elements. SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method FROM ticket_holds LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id LEFT JOIN orders ON orders.id = order_items.order_id LEFT JOIN users ON users.id = orders.user_id LEFT JOIN charges on charges.order_id = orders.id; This result is okay. id | created_at | user_id | id | payment_method ----+----------------------------+---------+----+---------------- 1 | 2017-05-26 04:29:22.189628 | 4 | 4 | 2 | 2017-05-26 04:33:00.721404 | 4 | 4 | some_payment_method When I try to filter the query to display the last record created per user it also works okay using SELECT MAX. SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method FROM ticket_holds LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id LEFT JOIN orders ON orders.id = order_items.order_id LEFT JOIN users ON users.id = orders.user_id LEFT JOIN charges on charges.order_id = orders.id WHERE ticket_holds.created_at = (SELECT MAX(ticket_holds.created_at) FROM ticket_holds WHERE orders.user_id = users.id); And the result id | created_at | user_id | id | payment_method ----+----------------------------+---------+----+---------------- 2 | 2017-05-26 04:33:00.721404 | 4 | 4 | some_payment_method (1 row) However, when Im trying to filter to only select items without a payment_method I get no results. SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method FROM ticket_holds LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id LEFT JOIN orders ON orders.id = order_items.order_id LEFT JOIN users ON users.id = orders.user_id LEFT JOIN charges on charges.order_id = orders.id WHERE ticket_holds.created_at = (SELECT MAX(ticket_holds.created_at) FROM ticket_holds WHERE orders.user_id = users.id AND charges.payment_method IS NULL); (Notice the AND charges.payment_method IS NULL) and the end of the query) This is what I get instead id | created_at | user_id | id | payment_method ----+------------+---------+----+---------------- (0 rows) Any idea how can I retrieve the elements with no payment method, in this case would be the record with id 1? A: As per discussion on chat. i think below query will help you to get required result. with data as ( SELECT ticket_holds.id, ticket_holds.created_at, orders.user_id, users.id, charges.payment_method FROM ticket_holds LEFT JOIN order_items ON order_items.id = ticket_holds.order_item_id LEFT JOIN orders ON orders.id = order_items.order_id LEFT JOIN users ON users.id = orders.user_id LEFT JOIN charges on charges.order_id = orders.id where charges.payment_method is null ) select * from data d1 where d1.created_at = (select max(created_at) from data d2 where d1.users_id = d2.user_id ) There are few points while writing an sub query in where clause. Join your table carefully as in your case you are not utilizing any column for joining.
{ "language": "en", "url": "https://stackoverflow.com/questions/44215811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: WPF vs Win App battery usage We want to use wpf application on tablet and looking for difference battery usage impacts between win app and wpf application? Is there any comparision battery usage or document? A: I doubt there is any type of documentation on what you want, but as suggested above, running your own tests shouldn't be too hard. I don't recall the APIs, but on any mobile device, there are going to be battery state objects you can access giving, at the very least, remaining battery energy. Write two test apps, each using the different paradigms. Run each, one at a time and for a long duration. Check on the energy usage at the beginning and end. A: This is late for an answer but one aspect to remember about battery consumption is the use of the radios (Bluetooth and WiFi). For tablet apps try to manage your app by stepping back and analyzing what data you'll need from the database and try to get the data in one shot so the OS can turn off the radio. If you make an sql call each time the user presses a button then the radio is on more and drains the battery. The OS might also leave the radio on "a little longer" in case you make another query. For the rest of the UI of the app, you're safe to count on an 8 hr shift and then they dock it for recharge. You can watch for the battery notifications as well so you can save the info in the app before the OS shuts you down. Other than that, each app is unique and you'll need to run these tests during your QA cycle.
{ "language": "en", "url": "https://stackoverflow.com/questions/32881183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Set branch permissions from Azure DevOps Pipeline with tf.exe I have a Powershell script that tries to set branch permissions that is getting called in a Build Pipeline. Unfortunately, I am getting an unauthorized error and I'm not sure why. Code Snippet: $tfExe = "$(split-path -parent $MyInvocation.MyCommand.Definition)\tf.exe" & $tfExe git permission /deny:CreateBranch /group:[$project]\Contributors /collection:https://dev.azure.com/$organization/ /teamproject:$project /repository:$reposiName /login:$username,$pat & $tfExe git permission /allow:CreateBranch /group:[$project]\Contributors /collection:https://dev.azure.com/$organization/ /teamproject:$project /repository:$reposiName /branch:feature /login:$username,$pat Error Message: TF30063: You are not authorized to access https://dev.azure.com/Company-DevOps. TF30063: You are not authorized to access https://dev.azure.com/Company-DevOps. TF30063: You are not authorized to access https://dev.azure.com/Company-DevOps. Powershell Script in Build Pipeline: Any thoughts? A: The username & password in the /login is for Azure DevOps Server. for Azure DevOps you should use OAuth: param ($oauth) /loginType:OAuth /login:.,$auth In the agent job options you need to enable the "Allow scripts to access the OAuth token": And pass the $(System.AccessToken) as oauth parameter: A: So I wasn't able to get this to work with tf.exe as Microsoft Docs advised us to, but I was able to figure it out with the help of a blog here. Step 1 Get the $descriptor value for the Contributors group $descriptor = az devops security group list --org https://dev.azure.com/$organization --project $project | ConvertFrom-Json | select -expand graphGroups | where principalName -eq "[$project]\Contributors" Step 2 Create your token values for the branches you want. Unfortunately, you cannot explicitly state which branch pattern you would like. Azure DevOps requires the Hex value (don't ask) #Create the tokens function hexify($string) { return ($string | Format-Hex -Encoding Unicode | Select-Object -Expand Bytes | ForEach-Object { '{0:x2}' -f $_ }) -join '' } $hexFeatureBranch = hexify -string "feature" $featureToken = "refs/heads/$hexFeatureBranch" $hexSprintBranch = hexify -string "sprint" $sprintToken = "refs/heads/$hexSprintBranch" $hexHotfixBranch = hexify -string "hotfix" $hotfixToken = "refs/heads/$hexHotfixBranch" Step 3 Get the Namespace ID for your Git Repos #Get the namespace ID for the organization's Git repos $namespaceId = az devops security permission namespace list --org "https://dev.azure.com/$organization/" --query "[?@.name == 'Git Repositories'].namespaceId | [0]" Step 4 Get the project's JSON object from the server #Get the Project's JSON object $projectObj = az devops project show --org https://dev.azure.com/$organization --project $project | ConvertFrom-Json $projectid = $projectObj.id Step 5 Put a Deny on CreateBranch for every branch in your repo. The Azure CLI requires you to know which bits for allow and deny need to be. Luckily, I was able to do this by capturing the JSON response when I did it via the UI. $denyBranch = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token "repoV2/" --deny-bit 16 --allow-bit 16494 Step 6 Put an Allow on CreateBranch for every branch that has the pattern feature/, sprint/ and hotfix/* $featureTokenBuild = "repoV2/$projectid/$repoid/$featureToken" $sprintTokenBuild = "repoV2/$projectid/$repoid/$sprintToken" $hotfixTokenBuild = "repoV2/$projectid/$repoid/$hotfixToken" $allowCreateBranchFeature = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token $featureTokenBuild --deny-bit 0 --allow-bit 16 $allowCreateBranchSprint = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token $sprintTokenBuild --deny-bit 0 --allow-bit 16 $allowCreateBranchHotfix = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token $hotfixTokenBuild --deny-bit 0 --allow-bit 16 It wasn't easy but at least for anyone in the future looking to do the same, here is the solution!
{ "language": "en", "url": "https://stackoverflow.com/questions/58963611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Blocked by Play Protect for a signed release APK I have a React Native (Android) app and for which I signed as per the instructions here; https://reactnative.dev/docs/signed-apk-android I generated a release APK which is also all fine (no errors). I then downloaded the APK to my android device and when I clicked to install I got a message to say the below. This app is not to be published to the Play Store but we will supply a URL to our customers to download the APK. So I want users to be able to install the APK without getting this warning. What I found so far * *Disabling the play protect on the device (We don't want our customers to do this) *Publishing to the play store (We will supply a URL to download the APK) *Play Protect Appeals Submission Form (Is this only for apps to be published to the play store? If not, how does it work once it is verified?) Thanks all. A: Play Protect Appeals Submission Form can solve your problem. Just send your apk details to Google and wait for appeal process. When you enter your apk's URL, Google will control your apk. Just enter your URL to URL to download your APK file section. You do not need publish your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/64263677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ember inject function I have some function which i use in couple controllers App.AController=Ember.Controller.Extend({ area:function(){} }); App.BController=Ember.Controller.Extend({ area:function(){} }); cause i new in Ember i want something to write function in one place and then inject function in Controllers. I try something with services but doesn't work i got error that Ember.Service is not defined, so if someone can write example! I use ember 1.10. A: If you use ember-cli just create a file app/utils/area.js: export default function () {...}; and then you can import it and use it: import area from 'myapp/utils/area`; import Ember from 'ember'; export default Ember.Controller.extend({ area, }); However if you'r not using ember-cli, this question is not ember specific. Then it depends how you organize your code. But you really should check out ember-cli! But always remember, this is just javascript. This is valid code: function area() { ... } App.AController=Ember.Controller.Extend({ area }); App.BController=Ember.Controller.Extend({ area });
{ "language": "en", "url": "https://stackoverflow.com/questions/41943692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to get JaCoCo instrumentation code coverage while executing webApplication on server I want to get a code coverage report (or tracking controller flow of an application) when I execute the some scenario on live application i.e. while application running in server, so I have refereed the official Jacoco documentation and did as fallows As a first step, I tried to bind the jacoco agent to the application running port export MAVEN_OPTS=-javaagent:/home/user/.m2/repository/org/jacoco/org.jacoco.agent/0.7.4.201502262128/org.jacoco.agent-0.7.4.201502262128-runtime.jar=includes=*,output=tcpserver,port=6300,address=*,dumponexit=true then I have started the server and executed some test scenarios by that time I have also requested jacoco to get the dump by executing following command mvn jacoco:dump when I executed the above command first it showed like java.net.BindException: Address already in use then it printed as fallows [INFO] Connecting to localhost/127.0.0.1:6300 When I stopped the server jacoco.exec has been generated to a known location there after I have requested to generate a jacoco report by executing the following command mvn jacoco:report Finally I got the report but when I open the index.html page it showed 0% coverage. you can reproduce my difficulty with following sample Spring MVC project please download Spring MVC project from https://github.com/mkyong/spring4-mvc-ajax-example from the Github In my case I am using WildFly 8.x server to run the project and add the following dependencies to downloaded projects pom.xml maven-surefire-plugin of 2.19.1 version jacoco-maven-plugin of 0.7.4.201502262128 version junit of 4.12 version Then clean and build the project by using following commands. mvn clean install once it is done get the .war file from target folder of the project and keep inside the wildfly serverwildfly-9.0.0.CR2/standalone/deployments/ folder Once the .war is deployed go to /wildfly-9.0.0.CR2/bin/ folder and execute/run the ./standalone.sh file or depending on platform you can run the.dat/.sh file once project is deployed and server is started execute the following command mvn jacoco:dump it displayed like listening/connected to localhost/127.0.0.1:6300 Then execute some test scenarios and execute following maven command mvn jaococ:report Finally report will be generated with 0% coverage!. Downloaded project can be found in MKyong website Please help me to get the code coverage report and any help will be appreciated. A: JaCoCo requires the exact same class files for report generation that were used at execution time, so * *if report is completely empty, then classes were not provided *if report contains classes but their coverage is 0%, then they don't match classes that were used at runtime - this is described along with other related information in JaCoCo documentation on page http://www.jacoco.org/jacoco/trunk/doc/classids.html and in either case check existence of warnings in log. Update for updated question Here is what I did: * *downloaded and unpacked JaCoCo 0.7.9 into /tmp/jacoco/jacoco-0.7.9 *downloaded and unpacked Wildfly 9.0.0.CR2 into /tmp/jacoco/wildfly-9.0.0.CR2 *cloned https://github.com/mkyong/spring4-mvc-ajax-example into /tmp/jacoco/spring4-mvc-ajax-example and built as mvn verify *copied /tmp/jacoco/spring4-mvc-ajax-example/spring4-mvc-maven-ajax-example-1.0-SNAPSHOT.war into /tmp/jacoco/wildfly-9.0.0.CR2/standalone/deployments *Wildfly started as JAVA_OPTS=-javaagent:/tmp/jacoco/jacoco-0.7.9/lib/jacocoagent.jar=output=tcpserver ./standalone.sh and got enough time to deploy application *in directory /tmp/jacoco/spring4-mvc-ajax-example executed mvn org.jacoco:jacoco-maven-plugin:0.7.9:dump org.jacoco:jacoco-maven-plugin:0.7.9:report (note that version of used agent matches version of jacoco-maven-plugin) so that it created /tmp/jacoco/spring4-mvc-ajax-example/jacoco.exec and report /tmp/jacoco/spring4-mvc-ajax-example/site/jacoco: *opened http://localhost:8080/spring4-mvc-maven-ajax-example-1.0-SNAPSHOT/ and did some actions *executed mvn org.jacoco:jacoco-maven-plugin:0.7.9:dump org.jacoco:jacoco-maven-plugin:0.7.9:report again to get an updated report:
{ "language": "en", "url": "https://stackoverflow.com/questions/42133100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to add exclude data in Firebase rules on multiple levels? I have my rules set. Normally, all data can only be read by the person who is auth to do so. However, I want to make exceptions. These are my rules: "rules": { "users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid", "ForEveryone": { ".read": true, ".write": true } "NoWrite" : { ".read": true, ".write": false } } } So I let's say I have 3 string. String 1 is called private and can the auth person can read and write. String 2 is ForEveryone, so everyone can change and write data. String 3 is NoWrite, for everyone but you can not write to it. I get an error, saying:Expecting a ; or " at the line NoWrite. So what am I doing wrong? Is it a wrong placed }? Thank you. A: The approach you're taking to your rule structure won't work. Firebase security rules cascade, meaning that a permission given to any node will apply to any of its children and on down the tree. You cannot grant read or write access on a node and then revoke it further down. (But you can grant permissions not granted above.) See the docs on rule cascading. In your case, you want to have some user data that be can written to by anyone and some that cannot. It's not clear from your example whether you want NoWrite to be written only by the authenticated user, or by nobody. Depending on how you will be reading this data, you will need to either separate these data into different collections, or make $uid inaccessible and define your rules only for ForEveryone and NoWrite. The first approach might look like this: "rules": { "users-public": { "$uid": { ".read": "true", ".write": "true", }, "users-nowrite": { "$uid": { ".read": "true", ".write": "$uid === auth.uid" } } Or the second, like this: "rules": { "users": { "$uid": { "ForEveryone": { ".read": "true", ".write": "true" }, "NoWrite" : { ".read": "true", ".write": "$uid === auth.uid" } } } As to your syntax error, you need a comma , after the closing brace before "NoWrite". A: Here are your rules, properly spaced so you can see the relationship between the parent nodes and child nodes. It seems this is not what you want. So this isn't really an answer but will lead to a better question that we can answer. Will update once we know what the OP is after. { "rules": { "users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid", "ForEveryone": { ".read": true, ".write": true }, "NoWrite" : { ".read": true, ".write": false } } //end uid } //end users } //end rules } //outside closure
{ "language": "en", "url": "https://stackoverflow.com/questions/42426347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why the first if statement conditional is ignored and the last else is executed? When I type in John and 0 the "John is great" statement is not executed. I don't understand why. I know that the question might be really simple but I checked the code in Java and it was working correctly. print("Hello world") myName = input("What is your name?\n") myVar = input("Enter a number: ") if(myName == "John" and myVar == 0): print("John is great") elif(myName == "Bob"): print("You are ok") else: print("Hello world") A: myVar is str type. Not int type. You should fix myVar = int(input("Enter a number: ")) A: 0 and "0" are two different values. 0 == 0 is true; 0 == "0" is false. input always returns a str, so entering 0 sets myVar to "0", not 0. if myName == "John" and myVar == "0":
{ "language": "en", "url": "https://stackoverflow.com/questions/58138436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: undefined attribute in use of $controllerProvider in Angular I'm a newbie in Angular, i whant to make use of $controllerProvider, i see an example like my code, but the attribute register got undefined: var appTmw = angular.module('appTmw', ['ui.router']); appTmw.config(function($stateProvider, $urlRouterProvider, $controllerProvider) { appTmw.register = { controller: $controllerProvider.register }; }) and here, a register of controller, the register attribute got undefined: appTmw.register.controller('CustomersController', ['$scope', 'config', 'dataService', function ($scope, config, dataService) { //Controller code goes here }]); what a problem with the code? A: controllerProvider is the $controller service used by Angular to create new controllers: https://docs.angularjs.org/api/ng/provider/$controllerProvider If you are new to angular I suggest you to use the standard way to create a controller: var appTmw = angular.module('appTmw', ['ui.router']); appTmw.controller('controllerName', function($scope){ //your code for the controller here }); I hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/36439887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Catch if user presses enter key in textbox I'm trying to catch in a Event if the user presses the enter key. If followed these instructions found on the MSDN documentation pages. This is my Event code for the Textbox: Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown ' Check if the enter key is pressed If e.KeyCode = Keys.Return Then OccurrenceElevation_Changed() End If End Sub My problem is: when I push any button on the keyboard the Event is triggered, but when I press the enter ( return ) key nothing happens? I tried changing the Textbox property to AcceptsReturn = True but no luck. Extra info: The textbox is located on a UserControl and not a form control. A: If something else is stopping the text box from receiving the enter key you could try overriding ProcessCmdKey of the UserControl instead. It might work, but it all depends on where in the event chain that the parent intercepts the message. Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean If keyData = Keys.Return AndAlso tbOccurrenceElevation.Focused = True Then 'Do your stuff here. Return True 'We've handled the key press. End If Return MyBase.ProcessCmdKey(msg, keyData) End Function A: Try this: Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown ' Check if the enter key is pressed If e.KeyCode = Keys.Enter or e.KeyCode = Keys.Return Then OccurrenceElevation_Changed() End If End Sub You have to remember most of the keyboards have both Enter and Return. The code for those is different so you have to include them both
{ "language": "en", "url": "https://stackoverflow.com/questions/43119166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding Icons on TabBottomNavigation React Native I have This navigation, how can I add Icons on the bottomTabNavigator const switchNavigator = createSwitchNavigator({ mainFlow: createBottomTabNavigator({ Home: createStackNavigator({ Search: SearchScreen, Results: ResultsShowScreen }), Map: AccountScreen, Scanner: AccountScreen, Account: AccountScreen }) }); A: U can add icons to tabs using defaultNavigationOptions, here is an example, more information about tabs can be got from https://reactnavigation.org/docs/en/4.x/tab-based-navigation.html export default createBottomTabNavigator( { Home: HomeScreen, Settings: SettingsScreen, }, { defaultNavigationOptions: ({ navigation }) => ({ tabBarIcon: ({ focused, horizontal, tintColor }) => { const { routeName } = navigation.state; let IconComponent = Ionicons; let iconName; if (routeName === 'Home') { iconName = focused ? 'ios-information-circle' : 'ios-information-circle-outline'; // Sometimes we want to add badges to some icons. // You can check the implementation below. IconComponent = HomeIconWithBadge; } else if (routeName === 'Settings') { iconName = focused ? 'ios-list-box' : 'ios-list'; } // You can return any component that you like here! return <IconComponent name={iconName} size={25} color={tintColor} />; }, }), tabBarOptions: { activeTintColor: 'tomato', inactiveTintColor: 'gray', }, } );```
{ "language": "en", "url": "https://stackoverflow.com/questions/60329246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do browsers have 3 characters as protocol separator? http:// vs http: Either there is some historical reason or I'm missing something. A: According to RFC 1738, While the syntax for the rest of the URL may vary depending on the particular scheme selected, URL schemes that involve the direct use of an IP-based protocol to a specified host on the Internet use a common syntax for the scheme-specific data: //user:password@host:port/url-path Some or all of the parts "user:password@", ":password", ":port", and "/url-path" may be excluded. The scheme specific data start with a double slash "//" to indicate that it complies with the common Internet scheme syntax. A: // Indicates that a contact to a server is to be achieved. (For example, when sending email the notation 'mailto:<email address>...', without slashes, could be used). Note that this doesn't mean a connection between a browser and server. When a browser has sent a request, there is no connection between the browser and the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/12804370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Browsersync - How to choose which installation of browser to run? I've just installed Firefox Dev Edition, and I don't know how to tell browsersync to start with it when I launch it. I know there is the browser option in which I can specify "firefox", but how can I differenciate one FF installation from one other ? The issue would be the same if I had various regular FF installed (eg a 3.5, a 48.x and a 50.x). I can always open manually the right FF and load the page after browsersync started, but I would like it to do it manually (and not to be opened in my regular non-dev FF). A: In fact, it was quite easy: if you put the absolute path to an executable file in the browser option, it takes it smoothly. So options should be something like : { port: 9000, server: { baseDir: [... ], routes: { '/bower_components': 'bower_components', '/node_modules': 'node_modules', '/temp': 'temp' } }, logLevel: 'info', notify: true, browser: 'C:\\Program Files (x86)\\Firefox Developer Edition\\firefox.exe', reloadDelay: 0 //1000 }
{ "language": "en", "url": "https://stackoverflow.com/questions/40718446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Best way to inform user of an SQL Table Update? I have a desktop python application whose data backend is a MySQL database, but whose previous database was a network-accessed xml file(s). When it was xml-powered, I had a thread spawned at the launch of the application that would simply check the xml file for changes and whenever the date modified changed (due to any user updating it), the app would refresh itself so multiple users could use and see the changes of the app as they went about their business. Now that the program has matured and is venturing toward an online presence so it can be used anywhere. Xml is out the window and I'm using MySQL with SQLAlchemy as the database access method. The plot thickens, however, because the information is no longer stored in one xml file but rather it is split into multiple tables in the SQL database. This complicates the idea of some sort of 'last modified' table value or structure. Thus the question, how do you inform the users that the data has changed and the app needs to refresh? Here are some of my thoughts: * *Each table needs a last-modified column (this seems like the worst option ever) *A separate table that holds some last modified column? *Some sort of push notification through a server? *It should be mentioned that I have the capability of running perhaps a very small python script on the same server hosting the SQL db that perhaps the app could connect to and (through sockets?) it could pass information to and from all connected clients? Some extra information: * *The information passed back and forth would be pretty low-bandwidth. Mostly text with the potential of some images (rarely over 50k). *Number of clients at present is very small, in the tens. But the project could be picked up by some bigger companies with client numbers possibly getting into the hundreds. Even still the bandwidth shouldn't be a problem for the foreseeable future. Anyway, somewhat new territory for me, so what would you do? Thanks in advance! A: As I understand this is not a client-server application, but rather an application that has a common remote storage. One idea would be to change to web services (this would solve most of your problems on the long run). Another idea (if you don't want to switch to web) is to refresh periodically the data in your interface by using a timer. Another way (and more complicated) would be to have a server that receives all the updates, stores them in the database and then pushes the changes to the other connected clients. The first 2 ideas you mentioned will have maintenance, scalability and design uglyness issues. The last 2 are a lot better in my opinion, but I still stick to web services as being the best.
{ "language": "en", "url": "https://stackoverflow.com/questions/10091108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible for WebDriver to click an element with a mouseclick event that invokes a JavaScript file that includes a test tracker? This is a question I have that arises from another user's question. If you look at my answer there, you will get some context for this question. The URL for the web page I am going to is https://hotels.ctrip.com/hotel/347422.html?isFull=F#ctm_ref=hod_sr_lst_dl_n_1_8 if you want to check it out for yourself. Consider the python selenium script found at the bottom of the question. Nothing happens when selenium tries to click on this element: browser.find_element_by_xpath('//*[@id="cPageBtn"]').click() Same thing with this element browser.find_element_by_xpath('//*[@id="appd_wrap_close"]').click() When debugging my selenium script for each element, I confirmed that selenium can find the element just fine; it is not hidden, inside an iFrame, disabled, or any other oddity that I normally check for failed selenium actions. However, it has a mouseclick event that invokes an interesting JavaScript file, and I was actually able to access it by navigating to URL shown here: Hovering over the URL revealed that it is https://webresource.c-ctrip.com/ResUnionOnline/R3/float/floating_normal.min.js?20190306:2. At the very beginning of the file I found document.getElementById("ab_testing_tracker") && "abTestValue_Value" != h ? document.getElementById("ab_testing_tracker").value So I search (via CSS selector in the dev console) the webpage HTML for an element with an id of "ab_testing_tracker" and I am less than surprised that it returns nothing. Then I unminified and searched through the file for all instances of "ab_testing_tracker". That led me to this element: document.getElementsByTagName("body")[0].insertAdjacentHTML("afterBegin","<input type='hidden' name='ab_testing_tracker' id='ab_testing_tracker' value='"+h.split("|")[1]+"'>") Well, it appears there is a hidden input node inserted in the body of the document for the purpose of automation tracking. Google searching revealed that automation tracking is often accomplished by looking at the navigator.userAgent property and finding userAgents that indicate automation. But the script is using a random legitimate userAgent every time, so I don't think the userAgent is how the detection is finding selenium. Summary and possible workarounds Selenium can't click certain elements on the web page likely due to testing tracking by the website. There are a couple things I thought of to get around it: maybe I can disable click events when using selenium? This I don't know how to do and couldn't find a way after searching online. Next, I tried to click on it with a Javascript executor, but that didn't work. Does anyone know a way to get around the test tracker and click the desired element? from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By # url url = "https://hotels.ctrip.com/hotel/347422.html?isFull=F#ctm_ref=hod_sr_lst_dl_n_1_8" # User Agent User_Agent_List = ["Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2", "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)", "Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)", "Opera/9.80 (X11; Linux i686; U; ru) Presto/2.8.131 Version/11.11", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2", "Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1", "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25"] # Define the related lists Score = [] Travel_Types = [] Room_Types = [] Travel_Dates = [] Comments = [] DEFINE_PAGE = 10 def next_page(): current_page = int(browser.find_element_by_css_selector('a.current').text) # First, clear the input box browser.find_element_by_id("cPageNum").clear() print('Clear the input page') # Second, input the next page nextPage = current_page + 1 print('Next page ',nextPage) browser.find_element_by_id("cPageNum").send_keys(nextPage) # Third, press the goto button browser.find_element_by_xpath('//*[@id="cPageBtn"]').click() def scrape_comments(): """ It is a function to scrape User comments, Score, Room types, Dates. """ html = browser.page_source soup = BeautifulSoup(html, "lxml") scores_total = soup.find_all('span', attrs={"class":"n"}) # We only want [0], [2], [4], ... travel_types = soup.find_all('span', attrs={"class":"type"}) room_types = soup.find_all('a', attrs={"class":"room J_baseroom_link room_link"}) travel_dates = soup.find_all('span', attrs={"class":"date"}) comments = soup.find_all('div', attrs={"class":"J_commentDetail"}) # Save score in the Score list for i in range(2,len(scores_total),2): Score.append(scores_total[i].string) Travel_Types.append(item.text for item in travel_types) Room_Types.append(item.text for item in room_types) Travel_Dates.append(item.text for item in travel_dates) Comments.append(item.text.replace('\n','') for item in comments) if __name__ == '__main__': # Random choose a user-agent user_agent = random.choice(User_Agent_List) print('User-Agent: ', user_agent) # Browser options setting options = Options() options.add_argument(user_agent) options.add_argument("disable-infobars") # Open a Firefox browser browser = webdriver.Firefox(options=options) browser.get(url) browser.find_element_by_xpath('//*[@id="appd_wrap_close"]').click() page = 1 while page <= DEFINE_PAGE: scrape_comments() next_page() browser.close() A: The problem is not the tracking or the click event, the problem is timing and possibly browser size. Maximize the browser window and add explicit wait when searching for the banner close button browser = webdriver.Firefox(options=options) browser.maximize_window() browser.get(url) wait = WebDriverWait(browser, 10) wait.until(EC.element_to_be_clickable((By.ID, 'appd_wrap_close'))).click() wait.until(EC.invisibility_of_element_located((By.ID, 'appd_wrap_default'))) current_page = int(browser.find_element_by_css_selector('a.current').text) next_page = current_page + 1 page_number_field = wait.until(EC.visibility_of_element_located((By.ID, 'cPageNum'))) page_number_field.clear() page_number_field.send_keys(next_page) wait.until(EC.element_to_be_clickable((By.ID, 'cPageBtn'))).click()
{ "language": "en", "url": "https://stackoverflow.com/questions/55204297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: %0d%0a getting added behind the URL of a href attribute in an tag In a helper plugin for WooCommerce for WordPress, I'm trying to create a custom message to be sent to a buyer. I don't know why in all the emails that are sent out, %0d%0a is getting added behind the URL in the href attribute. I have tried several different combinations and nothing is working. This is what I'm trying to do: echo "<a href='$cl'> Please click here to redeem the coupon</a>"; But because %0d%0a is being added at the back of it the URL doesn't work properly for coupon codes. This is what the URL looks like afterwards: https://www.example.com/product-1/?couponCode=TDXGUA9G&utm_source=test&utm_medium=testt&utm_campaign=test&aff_code=TSJU89XYZ%0d%0a The only thing that doesn't add %0d%0a is this: echo $cl; But I want to be able to use the <a> tag so that the buyer doesn't have to click on a long URL link. A: Try this echo "<a href='" . $cl . "'> Please click here to redeem the coupon</a>"; If you still have the issue, check how $cl was created. A: I really appreciate all the responses. But I just want to post the code that finally worked for me after 7 hours of work. I understand that it looks silly but this is the best I could do for now. Here's what worked for me: ?> <a href='<?php echo trim($cl); ?>'> <span color="#557da1">Click here to take <?php echo ' '.$_product_name.'</span></a>'; A: I just encountered the same issue, but I'm using ASP.NET. All I did was delete the single quote and type it again. Now it works. <asp:HyperLink ... NavigateUrl='<%# Eval("Url") %>' Text='<%# Eval("Name") %>' /> There were possibly some extra invisible characters which needed to be deleted.
{ "language": "en", "url": "https://stackoverflow.com/questions/35389750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android - TextViews not showing up in ListView I'm having an issue to where none of my TextViews are showing up in the ListView. I'm not sure whether it is an issue with the layout or the java class itself. There are two images here, one of the application running after data had been entered into the database and one of what it is supposed to look like. Layout for each row of data in ListView Fragment for the ListView (Delete Button appears but not the TextViews) row_layout.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="123dp" android:layout_height="wrap_content" android:id="@+id/resultTeamNumber" android:text="Here Number" android:textSize="18dp" android:layout_alignParentTop="true" android:layout_alignParentStart="true" /> <TextView android:layout_width="100dp" android:layout_height="wrap_content" android:id="@+id/textPortcullis" android:text="Portcullis:" android:layout_above="@+id/textChevalFrise" android:layout_alignParentStart="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/resultPortcullis" android:text="Yes/No" android:singleLine="false" android:layout_below="@+id/resultTeamNumber" android:layout_marginLeft="110dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textChevalFrise" android:text="Cheval de Frise:" android:layout_below="@+id/resultPortcullis" android:layout_alignParentStart="true" android:singleLine="false" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/resultChevalFrise" android:text="Yes/No" android:singleLine="false" android:layout_below="@+id/resultPortcullis" android:layout_alignStart="@+id/resultPortcullis" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textMoat" android:singleLine="false" android:layout_below="@+id/textChevalFrise" android:layout_alignParentStart="true" android:text="Moat:" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/resultMoat" android:text="Yes/No" android:singleLine="false" android:layout_below="@+id/resultChevalFrise" android:layout_alignStart="@+id/resultChevalFrise" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textRamparts" android:text="Ramparts:" android:singleLine="false" android:layout_below="@+id/textMoat" android:layout_alignParentStart="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/resultRamparts" android:text="Yes/No" android:singleLine="false" android:layout_above="@+id/textDrawbridge" android:layout_alignStart="@+id/resultMoat" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textDrawbridge" android:text="Drawbridge:" android:singleLine="false" android:layout_below="@+id/textRamparts" android:layout_alignParentStart="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/resultDrawbridge" android:text="Yes/No" android:singleLine="false" android:layout_below="@+id/resultRamparts" android:layout_alignStart="@+id/resultRamparts" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textSallyPort" android:text="Sally Port:" android:singleLine="false" android:layout_below="@+id/textDrawbridge" android:layout_alignParentStart="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/resultSallyPort" android:singleLine="false" android:layout_below="@+id/resultDrawbridge" android:layout_alignStart="@+id/resultDrawbridge" android:text="Yes/No" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textRockWall" android:text="Rock Wall:" android:singleLine="false" android:layout_alignTop="@+id/resultPortcullis" android:layout_toEndOf="@+id/resultPortcullis" android:layout_marginStart="34dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/resultRockWall" android:singleLine="false" android:text="Yes/No" android:layout_marginStart="46dp" android:layout_above="@+id/resultRockTerrain" android:layout_toEndOf="@+id/textRockTerrain" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textRockTerrain" android:text="Rock Terrain:" android:singleLine="false" android:layout_below="@+id/textRockWall" android:layout_alignStart="@+id/textRockWall" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/resultRockTerrain" android:singleLine="false" android:text="Yes/No" android:layout_alignBottom="@+id/textRockTerrain" android:layout_alignStart="@+id/resultRockWall" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textLowBar" android:text="Low Bar:" android:singleLine="false" android:layout_above="@+id/resultRamparts" android:layout_alignStart="@+id/textRockTerrain" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/resultLowBar" android:singleLine="false" android:text="Yes/No" android:layout_below="@+id/resultRockTerrain" android:layout_alignStart="@+id/resultRockTerrain" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#fff" android:background="@color/colorPrimary" android:text="Delete" android:id="@+id/buttonDelete" android:layout_below="@+id/textLowBar" android:layout_toEndOf="@+id/textLowBar" android:layout_above="@+id/resultSallyPort" /> </RelativeLayout> ScoutFragment.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; /** * A simple {@link Fragment} subclass. */ public class ScoutFragment extends Fragment { FloatingActionButton addDataScout; ListView eListScoutInfo; SQLiteDatabase sqLiteDatabase; DatabaseHelper databaseHelper; Cursor cursor; ListScoutInfoAdapter listScoutInfoAdapter; public ScoutFragment() { // Required empty public constructor } //End of ScoutFragment @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_scout, null, false); view.setBackgroundColor(Color.WHITE); eListScoutInfo = (ListView) view.findViewById(R.id.listScoutInfo); listScoutInfoAdapter = new ListScoutInfoAdapter(getActivity().getApplicationContext(), R.layout.row_layout); eListScoutInfo.setAdapter(listScoutInfoAdapter); databaseHelper = new DatabaseHelper(getActivity().getApplicationContext()); sqLiteDatabase = databaseHelper.getReadableDatabase(); cursor = databaseHelper.getInformation(sqLiteDatabase); //Checks if information is available in cursor if(cursor.moveToFirst()){ do { //Declare all strings String teamNumber, portcullis, chevalFrise, moat, ramparts, drawbridge, sallyPort, rockWall, rockTerrain, lowBar; //Get strings from cursor teamNumber = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_NUMBER)); portcullis = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_PORTCULLIS)); chevalFrise = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_CHEVAL_FRISE)); moat = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_MOAT)); ramparts = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_RAMPARTS)); drawbridge = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_DRAWBRIDGE)); sallyPort = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_SALLY_PORT)); rockWall = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_ROCK_WALL)); rockTerrain = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_ROCK_TERRAIN)); lowBar = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_LOW_BAR)); //Get methods from DatabaseProvider DatabaseProvider databaseProvider = new DatabaseProvider(teamNumber, portcullis, chevalFrise, moat, ramparts, drawbridge, sallyPort, rockWall, rockTerrain, lowBar); //Pass objects to add method listScoutInfoAdapter.add(databaseProvider); listScoutInfoAdapter.notifyDataSetChanged(); } while (cursor.moveToNext()); } //End of if statement //Setups Floating Action Button addDataScout = (FloatingActionButton) view.findViewById(R.id.fab); addDataScout.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { AddScoutDataFragment fragment = new AddScoutDataFragment(); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.commit(); } //End of onClick }); //End of setOnClickListener return view; } //End of onCreateView } //End of class I don't believe the issue is with database showing the data because some of the TextViews in the ListView don't even use the data from inside the database. A: It is theme issue on your end,probably textcolor set to white in your theme change these <item name="android:textColorPrimary">@color/white</item> <item name="android:textColorSecondary">@color/white</item> change it to black A: your row_layout.xml file textview in set textcolor: <TextView android:layout_width="123dp" android:layout_height="wrap_content" android:id="@+id/resultTeamNumber" android:text="Here Number" android:textSize="18dp" android:layout_alignParentTop="true" android:layout_alignParentStart="true" android:textColor="@android:color/black" /> A: set your adapter upon listview in the last..............
{ "language": "en", "url": "https://stackoverflow.com/questions/36052170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Append radio buttons to dynamic html table I have an ajax call that returns a sql query result and parses it into an html table. See below: function CreateTableFromJSON() { var email = "<?php echo $user_email; ?>"; console.log(email); $.ajax({ type: 'POST', url: 'api.php', data:{ //format:'json' //data:$.param({ 'userEmail': email }, dataType: 'json', success: function(data) { console.log(data); console.log("success"); // EXTRACT VALUE FOR HTML HEADER. var col = []; for (var i = 0; i < data.length; i++) { for (var key in data[i]) { if (col.indexOf(key) === -1) { col.push(key); } } } // CREATE DYNAMIC TABLE. var table = document.getElementById('excel_tablebody2'); var tr = table.insertRow(-1); // TABLE ROW. //for (var i = 0; i < col.length; i++) { // var th = document.createElement("th"); // TABLE HEADER. // th.innerHTML = col[i]; // tr.appendChild(th); //} // ADD JSON DATA TO THE TABLE AS data. for (var i = 0; i < data.length; i++) { tr = table.insertRow(-1); for (var j = 0; j < col.length; j++) { var tabCell = tr.insertCell(-1); tabCell.innerHTML = data[i][col[j]]; } } // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER. var divContainer = document.getElementById("excel_table2"); divContainer.appendChild(table); }, error: function(error) { console.log(error); console.log("CreateTableFromJSON did not work....."); } }); }; I'd like to append radio buttons to the table. Specifically how can I do this for dynamic tables (undefined number of rows and or columns)? In addition the radio button would need to relate to a specific tr as it will need to be used to send data back for that tr The goal is to return the table based on some criteria (user email). The table will contain data that needs to be verified using the radio buttons. Yes/No button and then sent back. Edit I'll add I'm unsure how to approach my overall goal. Is it best to allow the user to update the each row by using the radio button and once done submit it all back to the server. OR have each radio button fire an individual 'update' back to the server as you progress. Live update vs bulk update?
{ "language": "en", "url": "https://stackoverflow.com/questions/42167039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble in installing Font::TTF module I failed to install the module through cpan Font::TTF. I'm on strawberry perl 5.24, windows 8 32bit. C:\Users\user>cpan Loading internal null logger. Install Log::Log4perl for logging messages There seems to be running another CPAN process (pid 5860). Contacting... Other job not responding. Shall I overwrite the lockfile 'C:\STRAWB~1\cpan\.lock '? (Y/n) [y] cpan shell -- CPAN exploration and modules installation (v2.11) Enter 'h' for help. cpan> o conf build_dir_reuse 0 build_dir_reuse [0] commit: wrote 'C:\Strawberry\perl\lib/CPAN/Config.pm' cpan> o conf commit commit: wrote 'C:\Strawberry\perl\lib/CPAN/Config.pm' cpan> exit Lockfile removed. C:\Users\user>cpan Font::TTF Loading internal null logger. Install Log::Log4perl for logging messages CPAN: CPAN::SQLite loaded ok (v0.211) Database was generated on Fri, 15 Jul 2016 06:47:48 GMT Running install for module 'Font::TTF' CPAN: Digest::SHA loaded ok (v5.95) CPAN: Compress::Zlib loaded ok (v2.069) Checksum for C:\STRAWB~1\cpan\sources\authors\id\M\MH\MHOSKEN\Font-TTF- 1.05.tar. gz ok CPAN: Archive::Tar loaded ok (v2.06) CPAN: File::Temp loaded ok (v0.2304) CPAN: YAML::XS loaded ok (v0.62) CPAN: CPAN::Meta::Requirements loaded ok (v2.140) CPAN: Parse::CPAN::Meta loaded ok (v1.4417) CPAN: CPAN::Meta loaded ok (v2.150005) CPAN: Module::CoreList loaded ok (v5.20160507) Configuring M/MH/MHOSKEN/Font-TTF-1.05.tar.gz with Makefile.PL Checking if your kit is complete... Looks good Generating a dmake-style Makefile Writing Makefile for Font::TTF Writing MYMETA.yml and MYMETA.json MHOSKEN/Font-TTF-1.05.tar.gz C:\Strawberry\perl\bin\perl.exe Makefile.PL -- OK Running make for M/MH/MHOSKEN/Font-TTF-1.05.tar.gz MHOSKEN/Font-TTF-1.05.tar.gz C:\STRAWB~1\c\bin\dmake.exe -- OK Running make test "C:\Strawberry\perl\bin\perl.exe" "-MExtUtils::Command::MM" "-MTest::Harness" "- e" "undef *Test::Harness::Switches; test_harness(0, 'blib\lib', 'blib\arch')" t/ *.t t/tags.t ..... Can't locate Font/TTF/OTTags.pm in @INC (you may need to install the Font::TTF::OTTags module) (@INC contains: C:\STRAWB~1\cpan\build\Font-TTF-1. 05-8DWSyh\blib\lib C:\STRAWB~1\cpan\build\Font-TTF-1.05-8DWSyh\blib\arch C:/Stra wberry/perl/site/lib C:/Strawberry/perl/vendor/lib C:/Strawberry/perl/lib .) at t/tags.t line 5. BEGIN failed--compilation aborted at t/tags.t line 5. t/tags.t ..... Dubious, test returned 2 (wstat 512, 0x200) Failed 6/6 subtests t/ttfcopy.t .. Can't locate Font/TTF/Font.pm in @INC (you may need to install th e Font::TTF::Font module) (@INC contains: C:\STRAWB~1\cpan\build\Font-TTF- 1.05-8 DWSyh\blib\lib C:\STRAWB~1\cpan\build\Font-TTF-1.05-8DWSyh\blib\arch C:/Strawber ry/perl/site/lib C:/Strawberry/perl/vendor/lib C:/Strawberry/perl/lib .) at t/tt fcopy.t line 5. BEGIN failed--compilation aborted at t/ttfcopy.t line 5. t/ttfcopy.t .. Dubious, test returned 2 (wstat 512, 0x200) Failed 4/4 subtests Test Summary Report ------------------- t/tags.t (Wstat: 512 Tests: 0 Failed: 0) Non-zero exit status: 2 Parse errors: Bad plan. You planned 6 tests but ran 0. t/ttfcopy.t (Wstat: 512 Tests: 0 Failed: 0) Non-zero exit status: 2 Parse errors: Bad plan. You planned 4 tests but ran 0. Files=2, Tests=0, 1 wallclock secs ( 0.05 usr + 0.00 sys = 0.05 CPU) Result: FAIL Failed 2/2 test programs. 0/0 subtests failed. dmake.exe: Error code 130, while making 'test_dynamic' MHOSKEN/Font-TTF-1.05.tar.gz C:\STRAWB~1\c\bin\dmake.exe test -- NOT OK //hint// to see the cpan-testers results for installing this module, try: reports MHOSKEN/Font-TTF-1.05.tar.gz Stopping: 'install' failed for 'Font::TTF'. C:\Users\user> A: Jiang Bo, I was also getting the same problem with the latest Strawberry Perl version (5.24.0.1). I downgraded to 5.20.3.3 / 64bit and cpan installations work fine there.
{ "language": "en", "url": "https://stackoverflow.com/questions/38402046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Dynamically executed ARM ASM syscall with relocations from C++ I would like to call ARM/ARM64 ASM code from C++. ASM code contains syscall and a relocation to external function. ARM architecture here is not so important, I just want to understand how to solve my problem conceptually. I have following ASM syscall (output from objdump -d) which is called inside shared library: 198: d28009e8 mov x8, #0x4f // #79 19c: d4000001 svc #0x0 1a0: b140041f cmn x0, #0x1, lsl #12 1a4: da809400 cneg x0, x0, hi 1a8: 54000008 b.hi 0 <__set_errno_internal> 1ac: d65f03c0 ret This piece of code calls fstatat64 syscall and sets errno through external __set_errno_internal function. readelf -r shows following relocation for __set_errno_internal function: 00000000000001a8 R_AARCH64_CONDBR19 __set_errno_internal I want to call this piece of code from C++, so I converted it to buffer: unsigned char machine_code[] __attribute__((section(".text"))) = "\xe8\x09\x80\xd2" "\x01\x00\x00\xd4" "\x1f\x04\x40\xb1" "\x00\x94\x80\xda" "\x08\x00\x00\x54" // Here we have mentioned relocation "\xc0\x03\x5f\xd6"; EDIT: Important detail - I chose to use buffer (not inline assembly etc) because I want to run extra processing on this buffer (for example decryption function on string literal as a software protection mechanism but that's not important here) before it gets evaluated as machine code. Afterwards, buffer can be cast to function and called directly to execute machine code. Obviously there is a problem with relocation, it's not fixed automatically and I have to fix it manually. But during run-time I can't do it because .text section is read-only & executable. Although I have almost full control over source code I must not turn off stack protection & other features to make that section writable (don't ask why). So it seems that relocation fix should be performed during link stage somehow. As far as I know shared library contains relative offsets (for similar external function calls) after relocations are fixed by linker and binary *.so file should contain correct offsets (without need of run-time relocation work), so fixing that machine_code buffer during linking should be possible. I'm using manually built Clang 7 compiler and I have full control over LLVM passes so I thought maybe it's possible to write some kind of LLVM pass which executes during link time. Though it looks like ld is called in the end so maybe LLVM passes will not help here (not an expert here). Different ideas would be appreciated also. As you can see problem is pretty complicated. Maybe you have some directions/ideas how to solve this? Thanks! A: There's already a working, packaged mechanism to handle relocations. It's called dlsym(). While it doesn't directly give you a function pointer, all major C++ compilers support reinterpret_casting the result of dlsym to any ordinary function pointer. (Member functions are another issue altogether, but that's not relevant here)
{ "language": "en", "url": "https://stackoverflow.com/questions/56904943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: error: bind message supplies 1 parameters, but prepared statement "" requires 0 I have a table 'article' with column 'content' .I want to query Postgresql in order to search for a string contained in variable 'temp'.This query works fine- pool.query("select * from article where upper(content) like upper('%some_value%')"); But when I use placeholder $1 and [temp] in place of some_value , I get the above error - pool.query("select * from article where upper(content) LIKE upper('%$1%')",[temp] ); Note - Here $1 is a placeholder and should be replaced by the value in [temp] , but it treats '%$1%' as a string , I guess. Without the quotes ' ' , the LIKE operator doesn't work. I have also tried the query - pool.query("select * from article where upper(content) LIKE upper(concat('%',$1,'%'))",[temp] ); to ensure $1 is not treated as a string literal but it gives the error - error: could not determine data type of parameter $1 A: pool.query( "select * from article where upper(content) LIKE upper('%' || $1 || '%')", [temp] ).then( res => {console.log(res)}, err => {console.error(err)}) This works for me. I just looked at this Postgres doc page to try and understand what concat was doing to the parameter notation. Can't say that I understand the difference between using || operators and using concat string function at this time. A: The easiest way I found to do this is like the following: // You can remove [0] from character[0] if you want the complete value of character. database.query(` SELECT * FROM users WHERE LOWER(users.name) LIKE LOWER($1) ORDER BY users.id ASC`, ["%" + character[0] + "%"] ); // [%${character}%] string literal alternative to the last line in the function call. There are several things going on here, so let me break each line it down. * *SELECT * FROM users * *This is selecting all the columns associated with table users *WHERE LOWER(users.name) LIKE $1 * *This is filtering out all the results from the first line so that where the name(lowercased) column of the users table is like the parameter $1. *ORDER BY users.id ASC * *This is optional, but I like to include it because I want the data returned to me to be in ascending order (that is from 0 to infinity, or starting low and going high) based on the users.id or the id column of the users table. A popular alternative for client-side data presentation is users.created_at DESC which shows the latest user (or more than likely an article/post/comment) by its creation date in reverse order so you get the newest content at the top of the array to loop through and display on the client-side. *["%" + character + "%"] * *This part is the second argument in the .query method call from the database object (or client if you kept with that name, you can name it what you want, and database to me makes for more a sensical read than "client", but that is just my personal opinion, and it's highly possible that "client" may be the more technically correct term to use). The second argument needs to be an array of values. It takes the place of the parameters inserted in the query string, for example, $1 or ? are examples of parameter placeholders which are filled in with a value in the 2nd argument's array of values. In this case, I used JavaScript's built-in string concatenation to provide a "includes" like pattern, or in plain-broken English, "find me columns that contain a 'this' value" where name(lowercased) is the column and character is the parameter variable value. I am pulling in the parameter value for the character variable from req.params (the URL, so http://localhost:3000/users/startsWith/t), so combining that with % on both ends of the parameter, it returns me all the values that contain the letter t since is the first (and only) character here in the URL. I know this is a VERY late response, but I wanted to respond with a more thorough answer in case anyone else needed it broken down further. A: In my case : My variable was $1, instead of ?1 ... I was customizing my query with @Query
{ "language": "en", "url": "https://stackoverflow.com/questions/45039760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Errors only when running shiny application on server - debug I have written a small application in shiny. I have the following files: global.R, server.R and ui.R In the global.R file, I load my data. I read data from three different csv files. a.csv, b.csv and c.csv and I use merge to join a.csv and b.csv and another merge to join a.csv and c.csv In the ui.R file, I have the layout for some filters. In the shinydashboard, I have tabItems, tabPanels containing selectInput and sliderInput for the filters. In the server.R file, I have the implementation. One functionality is that based on the filters, I show a table with some values. If the user selects a row, I activate another tab with more details on the selected row (eg, graphs, tables etc related to the selected row) This whole thing works perfectly when I run it on my machine using RStudio. When I move the code to the shiny server, I get the first tab layout, the functionality to activate second tab on selection all working. However in the second tab, I cannot see the table, and I get an error for the graphs. Error: 'from' cannot be NA, NaN or infinite. I have no clue why I cannot see any data on the tab when I run the application on the server. I suspect maybe there is some problem in the merge. I want to debug and find the problem. I wanted to know how I can debug since I run this on the server using a web browser and all I can see on the browser is a line Error: 'from' cannot be NA, NaN or infinite and blank table. Can someone give some inputs on debugging to find the problem. Thanks A: I was able to figure out the problem. The problem was with the package version of DT on the server. The package version of DT on the server was 0.1 and that version has some bugs (based on this post: https://github.com/rstudio/DT/issues/206) I was able to get the package version updated to 0.2 and all worked fine. The problem was with using input$table_rows_selected with the old version of DT package with selection = 'single' as a parameter. Moving to 0.2 version of DT package resolved the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/40892850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect click when the allow Button in the notification alert permission is tapped I'm developing this iOS app with SwiftUI. How I can detect when the user clicks the allow button of the Notification permission alert? It should happen only one time and I need to take the user to a specific tab the first time he tapped the button. Is this possible? A: you can add the attribute onclick="location.href='https://google.com';". but could you post codesnippets? and do you use javascript and php? A: I found a solution. To create this behaviour, I simply saved in a UserDefault a Bool value. func registerForPushNotifications() { UNUserNotificationCenter.current() .requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in print("Permission granted: \(granted)") self?.userDefault.set(granted, forKey: "notificationGranted") guard granted else { return } self?.getNotificationSettings() } } func getNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { settings in print("Notification settings: \(settings)") guard settings.authorizationStatus == .authorized else { return } // Saving the value to permit to take the user to the Notification screen only the first time if (self.userDefault.value(forKey: "permissionPopUpIsShowed") == nil) { self.userDefault.set(true, forKey: "permissionPopUpIsShowed") } DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } In the Content View inside the onAppear method you can do this: if appDelegate.userDefault.bool(forKey: "permissionPopUpIsShowed") == true && appDelegate.userDefault.bool(forKey: "notificationGranted") == true { tabSelection = .notifications appDelegate.userDefault.set(false, forKey: "permissionPopUpIsShowed") } In this way you will be able to select a new view (through the tabSelection) and obtain this behaviour only once (when the notification permission popUp is showed).
{ "language": "en", "url": "https://stackoverflow.com/questions/68208061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python destroying content to save memory I have a class to get a webpage's html and do some things with it import requests class A(object): def __init__(self, url): self.r = requests.get(url) self.html = self.r.text #other things class B(A): def __init__(self,url): super(B,self).__init__(url) #other things I am going to instantiate this class hundreds of thousands of times, like so for url in many_urls: page = B(url) #other things how can I make sure that the content like page.html and other attributes get deleted and aren't kept in memory to slow it down? A: The html will be held in memory for as long as the object that references it exists. If your for loop does not assign the B object to any other variable, then each time you re-assign page the previously created B object will become eligible for garbage collection, and the html will be removed from memory at the same time. If you are retaining references to each of your B objects you will slowly fill up your memory, but if you allow them to be garbage collected you should be fine. A: You can use del page or page = None, both statements release the content for garbage collection. This makes sense if your for-loop kernel is memory critical or you are using object that bring their own memory management (like numpy.ndarray). Also note that variables "bleed" out of the scope of for-loops. That means that the page from the last iteration will be present until the current scope is terminated (usually at the end of the function/method).
{ "language": "en", "url": "https://stackoverflow.com/questions/26995493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Algorithm prints length of string rather than number of Cs and Gs in it I am new to Java and currently learning it in a 4 week course. I am working on on an assignment to find all of the Cs and Gs in a string named dna, and then divide the number of Cs and Gs by dna. I have written a small program, and it compiles with no syntax errors, but when I run it, all that is printed out is the length of dna and then 1(The output of the dividing part). My code: public static void cgRatio (String dna) { int counter = 0; // counts how many Cs and Gs int index = 0; // start looking from index 0 while (dna.indexOf("C") != -1 && counter != dna.length()) { // while dna is not finished and you can find C in dna index = dna.indexOf("C", index); // Start looking from last index if (index != -1) { counter++; } else { break; } } System.out.println("Number of C in dna: " + counter); System.out.println("Gene cg ratio: " + (counter / dna.length())); } If anyone can help that would be great and appreciated, thanks! A: The problem is that the second argument to indexOf is the first index in the string that it searches. Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. Once it finds the first "C", it will then continue to always find that same "C" in the first index it looks in. You need to change your code to this: index = dna.indexOf("C", index + 1); To start from the first character after the "C" that you already found. You should also change the initial index to -1 so that it starts from the first character. A: There are a few problems with your code: * *It uses counter as the number of cs in your dna string when it is really equal to dna.length(). This causes the ratio to be 1 if there are any cs at all, or 0 if there are none. *There should be a variable that keeps track of how many cs there are in the string and how many gs there are (as seen in the above bullet, counter cannot be used for this.) *As resueman said, this line: index = dna.indexOf("C", index); should be changed to: index = dna.indexOf("C", index + 1);, or else the index will remain the same (it will always be equal to the index of the first c in the string.) *A while loop really is not all that well suited to this kind of thing; instead, a for loop should be used. *The ratio should be a double, not an int since doubles have more precision (they can be decimals.) Here's code I came up with that works: public static void cratio(String dna) { int c = 0; int g = 0; for(int i =0; i < dna.length(); i++) { if((dna.charAt(i) == 'c') || (dna.charAt(i) == 'C')) c++; if((dna.charAt(i) == 'g') || (dna.charAt(i) == 'G')) g++; } System.out.println("Number of 'C's in DNA: " + c + " and number of 'G's in DNA: " + g); int length = dna.length(); double ratio = (double) (c+g)/length * 100; System.out.println("The ratio of 'C's and 'G's to the length of the DNA chain is: " + ratio + "%."); } If you have any questions, just let me know!
{ "language": "en", "url": "https://stackoverflow.com/questions/40064899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: iOS Take or Select Photo The camera app on iOS allows one to take a photo, but also has the button to the left that allows one to browse the photo album. When using the UIImagePickerController I can only tell them to either do one or the other. So, rather than making a custom camera view, or even a custom overlay to add these abilities, I'll ask if there isn't some sort of flag I'm missing to allow this use case. A: When invoking it, you choose which one you want. There isn't a way to get exactly the same functionality as the camera app unless you, as you said, make a custom view for it. But wherever you want to invoke this, you could provide the options for either choosing a photo or taking one at that point. You'll notice other apps that either let you take a photo or choose one from your library give you those as separate options within their UI.
{ "language": "en", "url": "https://stackoverflow.com/questions/20912123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: parity bit and error detection I have faced that in my computer architecture course at university. I can't understand the parity bit; Why it has two kinds of even and odd. Can anyone give me clear explain about parity codes? A: A 'parity bit' is a method of error checking. Imagine that you need to send 8 bits over a connection and determine whether they got through right. You could try sending it twice, that way if there is an error, the receiver will know because the two messages differ. However, this requires two times the bandwidth, which is too much. So often every byte (8 bits) will also have a parity bit. You count up the number of ones in the byte. If it is odd, the parity bit is one. If it is even, the parity bit is zero. That way if there is any single error the receiver will know and only one eighth the extra bandwidth is needed. Examples: Data: 01001001 3 ones, parity bit 1 Data: 00110101 4 ones, parity bit 0 If receiver gets 00111101 and parity bit 0, it will know that there is some corruption. Of course if there are two errors in the same byte there will be no way to detect this - example if original is 00000001 and received is 00000010 - but this is considered to be rare enough to not worry for most applications. A: The first sentence of the Wikipedia article is clear enough, and so is the second paragraph... But ohwell. Given a word of n bits, with n-1 bits to check parity on and 1 bit of parity, the parity bit will be set to: * *1 if the number of bits set to 1 is odd, 0 otherwise (even parity); *0 if the number of bits set to 1 is even, 1 otherwise (odd parity). Example: 1101011x where x is the parity bit. There are 5 bits set to 1, therefore an odd number: x will be set to 1 (even parity) or 0 (odd parity).
{ "language": "en", "url": "https://stackoverflow.com/questions/8694876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Coldfusion counting based on patterns matching I am reading numbers off a database and create a 4 digits patterns such as: 1, 2, 2, 1 0, 2, 2, 2 4, 0, 2, 0 1, 2, 2, 1 2, 1, 1, 2 Each digit can only be from 0-6. The second step is where my problem is. I need to tally each pattern. For example, pattern 1,2,2,1 has a tally of 2 because it appears twice and the other patterns appear only once each. At the end output, I need to be able to display each unique pattern with the count such as: 1, 2, 2, 1 - 2 0, 2, 2, 2 - 1 4, 0, 2, 0 - 1 2, 1, 1, 2 - 1 I was thinking of using a 2-dimensional array. Where combinations[1][1]="1, 2, 2, 1" (the pattern) combinations[1][2]=2 (the count) combinations[2][1]="0, 2, 2, 2" combinations[2][2]=1 etc. How can I actually create the array dynamically while matching the pattern? i.e. if the pattern is not yet found add to the array. If it is found, add to the count. I have tried this: <cfloop index="i" from="1" to="#ArrayLen(combinations)#"> <cfif not arrayFind(combinations[i][1],"#patterns#")> <cfset arrayAppend(combinations,["#patterns#",1]) > <cfelse> <cfset combinations[i][2] = combinations[i][2] + 1> </cfif> </cfloop> But I am getting the error on the ArrayFind: Object of type class java.lang.String cannot be used as an array Any help is appreciated. Thank you in advance. A: Solved my own question. Looks like I used the wrong function. This works: <cfloop index="i" from="1" to="#ArrayLen(combinations)#"> <cfif Find(combinations[i][1],"#patterns#")> <cfset combinations[i][2] = combinations[i][2] + 1> <cfset found = 1> </cfif> </cfloop> <cfif not found> <cfset arrayAppend(combinations,["#patterns#",1]) > </cfif> A: Instead of using a 2-dimensional array, you could also use a structure instead, in which the keys are the patterns and the values the counts. That naturally avoids duplicates because the keys of a structure can only exist once. The code for creating the structure would look something like this: <cfset combinations = {}> <cfloop query="#dbresults#"> <cfif not structKeyExists(combinations, dbresults.pattern)> <cfset combinations[dbresults.pattern] = 1> <cfelse> <cfset combinations[dbresults.pattern]++> </cfif> </cfloop> In the end you just have to loop over the structure to output the counts: <cfloop collection="#combinations#" item="pattern"> <cfoutput><p>#pattern# - #combinations[pattern]#</p></cfoutput> </cfloop>
{ "language": "en", "url": "https://stackoverflow.com/questions/65606019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Amazon ELB and Apache trailing slash issue Actually I've an amazon ELB configured ONLY with rule HTTPS 443 --> HTTP 80. I cannot open the HTTP (port 80) on ELB for contract reasons. I see that for all client requests in https without training slash the apache for some unknown reasons redirect it in http with training slash: https://host/site --> redirect to http://host/site/ (doesn't work) I see different questions about this problem and seems that all people solve opening HTTP on ELB (it add some header informations as well as X-Forwarded-Proto "https") And they apply these Rewrite rules: RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301] to get it working behind an AWS Elastic Load Balancer. For me this automatic apache redirect when is missing the trailing slash on the the URL is not clear (for my understanding apache when see an URL without trailing slash that point to a dir, redirect it adding trailing slash) Is there an alternative way to solve this problem WITHOUT open HTTP on Amazon ELB?
{ "language": "en", "url": "https://stackoverflow.com/questions/40738649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: vb combo box selected item to open in individual form Am actually new in vb and trying to learn it, i have a combo box of 13 collections and a button, i want whenever a user selects an option from the combo box and clicks the button, it should open in an individual form. but the problem is whenever the user clicks on an option, all the 13 forms will open. please help here is my code Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ComboBox1.SelectedValue = "1" Form2.Show() Me.Hide() ComboBox1.SelectedItem = "2" Form3.Show() Me.Hide() ComboBox1.SelectedItem = "3" Form4.Show() ComboBox1.SelectedValue = "4" Form3.Show() Me.Hide() ComboBox1.SelectedItem = "5" Form5.Show() Me.Hide() ComboBox1.SelectedItem = "6" Form6.Show() ComboBox1.SelectedValue = "7" Form7.Show() Me.Hide() ComboBox1.SelectedItem = "8" Form8.Show() Me.Hide() ComboBox1.SelectedItem = "9" Form9.Show() ComboBox1.SelectedValue = "10" Form9.Show() Me.Hide() ComboBox1.SelectedItem = "11" Form10.Show() Me.Hide() ComboBox1.SelectedItem = "12" Form11.Show() Me.Hide() ComboBox1.SelectedItem = "13" Form12.Show() Me.Hide() End Sub A: Based upon what you are trying to do, And what the other members advised you already, It sounds like you did not correctly format your if...then and/or your select...case statements. The code below should do what you are trying to do. We use the SELECTINDEX property to find out which index element in the drop down is selected at present. Additionally, The code below can be affected (affected so it does not work) by any code in the combobox/dropdown object's event procedures if you have any of them setup. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' Select Case Combobox1.SelectedIndex Case 1 Form2.Show() Me.Hide() Case 1, 4 Form3.Show() Me.Hide() Case 3 Form4.Show() Me.Hide() Case 5 Form5.Show() Me.Hide() Case 6 Form6.Show() Me.Hide() Case 7 Form7.Show() Me.Hide() Case 8 Form8.Show() Me.Hide() Case 9, 10 Form9.Show() Me.Hide() Case 11 Form10.Show() Me.Hide() Case 12 Form11.Show() Me.Hide() Case 13 Form12.Show() Me.Hide() End Select ' End Sub A: * *Combo box to open Form *Add & Name Combo Box SelectFormsEdit *Go to Property Sheet, Data Tab, Edit Row Source, SQL: SELECT MsysObjects.Name FROM MsysObjects WHERE (((MsysObjects.Type)=-32768)); *Event Tab, After Update, ... Code Builder: Private Sub SelectFormsEdit_AfterUpdate() DoCmd.OpenForm SelectFormsEdit, , , , acFormEdit End Sub *Save everything
{ "language": "en", "url": "https://stackoverflow.com/questions/45378165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to get url of clicked link in WebEngineView? I've noticed that in Qt version 5.4, WebView has a signal named navigationRequired, which had a clicked URL in parameters. In the new WebView and WebEngineView, there is no such signal. I also haven't found any alternatives. Is there any way to get a clicked link's URL in Qt 5.6? A: Reimplement the method acceptNavigationRequest of QWebEnginePage : class MyQWebEnginePage : public QWebEnginePage { Q_OBJECT public: MyQWebEnginePage(QObject* parent = 0) : QWebEnginePage(parent){} bool acceptNavigationRequest(const QUrl & url, QWebEnginePage::NavigationType type, bool) { if (type == QWebEnginePage::NavigationTypeLinkClicked) { // retrieve the url here return false; } return true; } };
{ "language": "en", "url": "https://stackoverflow.com/questions/36485315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Component not being unmounted I am trying to write a React mixin that creates a few keybindings to easily scroll list views, however, I have problems with removing the event listeners after the component has been removed from the DOM Mixin: componentDidMount: function() { var requiredFunction = Object.getPrototypeOf(this).keyedList; if (!_.isFunction(requiredFunction)) { console.log('[KeyedListMixin] You must define the keyedList() function'); } $(document).on('keydown', this.__handleKeyDown); }, componentDidUnMount: function() { $(document).off('keydown', this.__handleKeyDown); }, render: if (showNewCommentWindow) { centeredWindow = ( <FixedView> <div className='new-comment-window'> <NewResourceWindow listObjects = {searchResults} onSearchItemClick = {this._handleSearchItemClick} handleOnChange = {this._handleSearchChange} /> </div> </FixedView> ) } return ( .... {centeredWindow} .... But once showNewCommentWindow is false, and as a result, the FixedView doesn't get rendered, the component don't unmount for some reason. A: The lifecycle method isn't called componentDidUnMount, it's called componentWillUnmount. Two important differences where the casing is Unmount and not UnMount and that it's Will and not Did. If it was called componentDidUnmount the component would have already been unmounted and the reference to the DOM node would have been released. So you clean up any DOM related things in componentWillUnmount just before the component is unmounted.
{ "language": "en", "url": "https://stackoverflow.com/questions/30340956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing Word2Vec for stemming/lemmatizing Turkish I'm working on building a stemming programm for Turkish which is a morphologically rich language. None of the ressources that I've found are accurate enough for my purpose and I don't think they are built on deep learning technology. How could I use word embeddings to train a stemmer/lemmatizer? What are the main steps I should be considering?
{ "language": "en", "url": "https://stackoverflow.com/questions/43976842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Predictability of Pseudo Random Generators by Quantum computers May classical pseudo random generators be predictable by powerful quantum computers in the future or is it proven that this is not possible? If they are predictable, do scientists know whether there exist PRGs that are unpredictable by quantum computers? A: The security of a classical Cryptographic Pseudo-Random Number Generator (CPRNG) is always based on some hardness assumption, such as "factoring is hard" or "colliding the SHA-256 function is hard". Quantum computers make some computational problems easier. That violates some of the old hardness assumptions. But not all of them. For example, blum blum shub is likely broken by quantum computers, but no one knows how to break lattice-based cryptography with quantum computers. Showing you can break all classical CPRNGs with quantum computers is tantamount to showing that BQP=NP, which is not expected to be the case. Even if quantum computers did break all classical CPRNGs, they happen to also fill that hole. They enable the creation of "Einstein-certified" random numbers.
{ "language": "en", "url": "https://stackoverflow.com/questions/26357131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cannot uninstall node and npm completely on high sierra I recently installed Node on my MacBook running High Sierra 10.13 using the .pkg file supplied on their website. After a few hours of experimenting with installing other packages and writing scripts, I decided I would like to uninstall both Node and NPM to get a fresh start. I tried all of the top answers from this thread, but to my dismay, after having followed all instructions, and repeated all steps many times, terminal would still recognise the Node and NPM versions. I ended up running a bash script through terminal which I found on the same thread, which ended up doing nothing but downgrading my current version of Node to 0.10.8 - making it a lot more difficult to delete in the long run. I've re-done all of the steps from the aforementioned thread with no avail, and terminal still stating that it has version 0.10.8 (and NPM just completely not working at all) Currently at my last stance of what to do, so hopefully someone on here can help me with my problem. Cheers. A: After searching through Google and StackOverflow for hours, I finally came up with a solution to the problem on my own. Running the type command within terminal against node, I got this returned: :~ myusername$ type node node is /Users/myusername/.nvm/v0.10.48/bin/node Subsequently, after deleting that folder, Node appears to be completely removed from my system. I have since made sure that I have deleted all node and node_module folders that I could find within /usr/ to make sure - and I would suggest that anyone attempting this also do the same. A: Try to run the following command brew uninstall node After the above command, you need to scan manually for node_modules if exists. Try following. grep -irl "node_modules/node" sudo rm -rf result_from_above_command rm -rf ~/.npm I hope this will remove all the node and it's components. As I have done like this, once before. Thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/49358028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: On cloudcontrol, how can I do a URL rewrite? For a Python / Django application running on cloudcontrol, what's the recommended way of rewriting urls, e.g. attaching a wordpress blog to a certain url path like example.com/blog/, or even just redirecting a subdomain? I'd know how to do this with an .htaccess file - is there an equivalent that would work on cloudcontrol? I found some sample cctrl apps that use .htaccess files (e.g. https://github.com/cloudControl/example_apps/blob/master/php/kohana/example.htaccess), but that's all PHP and it does not seem to work for my Django app. A: You have multiple options. Let me explain the basic concept first. Generally every app on cloudControl has its own subdomain like APP_NAME.cloudcontrolled.com. Requests to those subdomains (or from a CNAME pointing to that subdomain) are forwarded by the routing tier to one or more of the containers available to serve requests. What runs inside each container is controlled by the Buildpack. Depending on the preferences of each language ecosystem (e.g. PHP vs Python) the runtime environment in the container differs. So for PHP, Apache is available while for Python it is not. Option 1: The recommended way would be to have e.g. www.example.com poing to PYTHON_APP.cloudcontrolled.com and blog.example.com point to PHP_APP.cloudcontrolled.com. Option 2: Alternatively if you have to use /blog instead of a blog. subdomain you can teach the Apache running inside the PHP App's containers to only serve requests for /blog and forward everything else to PYTHON_APP.cloudcontrolled.com. Option 3: Soon you'd have a third option also, but this isn't available yet. We're currently working on enabling the Python buildpack to run Nginx inside the containers and use WSGI to communicate with the Python process. (Currently the Python process has to listen on the $PORT and serve HTTP directly) As soon as Nginx is available you could also configure it to forward /blog to PHP_APP.cloudcontrolled.com and serve everything else directly. My recommendation would be to go with option 1, since that keeps both apps nicely decoupled. By permanently redirecting /blog in the Python app to blog.example.com you can make the migration painless.
{ "language": "en", "url": "https://stackoverflow.com/questions/27444181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WordPress Custom Repeater Controller For Customizer I want to create custom repeater controller for theme, for this i tried but i am stuck with issue and i am unable to save any changes to my repeater section, any help is highly appreciated, here is link to my code The code for customizer class is if (class_exists('WP_Customize_Control')): class Test_Testimonial_Control extends WP_Customize_Control { public $type = 'textarea'; public function render_content() { ?> <div class="test-rep-section-wrap"> <div class="test-rep-section"> <h3 class="test-title"><?php echo esc_html( $this->label ); ?></h3> <div class="test-contents"> <input type="text" name="testimonial" placeholder="Image URL" id="img-link-testimonial"> <a href="javascript:void(0)" class="upload_testimonial">Upload Image</a> <span><?php _e('Description Text','text-domain'); ?></span> <textarea rows="2" style="width:100%;"><?php echo esc_textarea( $this->value() ); ?></textarea> <input type="text" name="cl_name" placeholder="Name"> </div> <a href="javascript:void(0)" class="new_section">Add More</a> <input <?php $this->link(); ?> type="hidden" value="<?php echo esc_attr($this->value()); ?>"/> </div> </div> <?php } } endif; jquery code is $('.test-contents').hide(); $('body').on('click', '.test-title', function(){ $('.test-contents').slideToggle(); }); $('body').on('click', '.new_section', function(){ var tCount = 0; $('.test-rep-section-wrap').append('<div class="test-rep-section"><h3 class="test-title">Testimonial Options</h3><div class="test-contents" style="display: block;"><input type="text" name="testimonial" placeholder="Image URL" id="img-link-testimonial"><a href="javascript:void(0)" class="upload_testimonial">Upload Image</a><span>Description Text</span><textarea rows="5" style="width:100%;"></textarea><input type="text" name="cl_name" placeholder="Name"></div><a href="javascript:void(0)" class="new_section">Add More</a><input data-customize-setting-link="ripple_pro_testimonial_repeater" type="hidden" value=""><div class="delete-test-feature"><a href="javascript:void(0)" class="delete-feature button">Delete Feature</a></div></div>'); }); $(document).on('click', '.delete-test-feature > a', function(){ $(this).parents('.test-rep-section').remove(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/46721644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS Issue in IE7 and IE8 - text-indent on field Is it possible to make IE7 and IE8 respect the text-indent css property on an input field? Here's my code <!DOCTYPE html> <html> <body> <input type="text" style="text-indent:100px; display:block;" value="Test indent" /> </body> </html> When you first load the page in IE8, the text is NOT indented. You can "activate" the text-indent property by focussing in on the text field and typing into it (ie. trigger the onchange event). How do I make IE7 and IE8 respect the text-indent of an input text element on page load instead of on input.onchange event? A: in normal case input tag text-indent does not work in ie6 and ie7 If we add lineheight:1px it will work all browser Text-indent will work all browser <input type="text" style="text-indent:-100px; display:block; line-height:1px;" value="Test indent" /> Text-indent not will work ie7 and ie6 browser <input type="text" style="text-indent:-100px; display:block;" value="Test indent" /> demo http://jsfiddle.net/KczMR/1/ A: Are you sure that you want 'text-indent' instead of either the 'margin-left' or the 'padding-left' property? The 'text-indent' property is meant to affect only the first line of text in an element. You might have better luck with margin or padding.
{ "language": "en", "url": "https://stackoverflow.com/questions/5915287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Is it possible to open an Apple Developer account for a client? My company is developing an iPad app for a technically unsophisticated government client, and I understand that they need their own Apple Developer account. We would like to open and maintain the developer account for them, because we'll be much happier to have the control of our own destiny, and they'll be much happier to delegate the work to us. But in the Apple Enrollment Guidelines, it says this: I'm a contractor who develops apps for companies other than my own. How do I ensure my client's name is listed as the “Seller” on the App Store? If your client plans to distribute the apps you create for them on the App Store with their legal entity name as the “Seller”, they must enroll in the iOS Developer Program. They can add you as a member of their development team so you can access the resources you need to create the app. While they must be the one who submits the app for review, you can assist them if necessary. This makes it sound like any company that wants to be a "Seller" must physically create their own account and do at least some of the work, even when it's clear that another party is the only one that is going to be able to do any of the work. Am I reading this right? Is it really not possible for a contractor to set up a developer account on behalf of a client? A: Yes that is correct. Your client is responsible for creating an account and paying the developer fee. You could create the account, but then when your contract is over you would be getting support requests, be responsible for all future updates, and have to renew the account every year. It's better for your client to create the account. SEE EDIT Edit: Found a thread on this discussion - http://www.buzztouch.com/forum/thread.php?tid=10608297F86BD057C74C0F9. The post by MGoBlue on 10/10/11 at 09:04 PM is Apple's stance, which says not to do that. Don't mess with Apple, have your client create an account and invite you to it. There's also a note about this on Apple's Program Enrollment FAQ: I'm a contractor who develops apps for companies other than my own. How do I ensure my client's name is listed as the “Seller” on the App Store? If your client plans to distribute the apps you create for them on the App Store with their legal entity name as the “Seller”, they must enroll in the iOS Developer Program. They can add you as a member of their development team so you can access the resources you need to create the app. While they must be the one who submits the app for review, you can assist them if necessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/12287775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }