text
stringlengths
15
59.8k
meta
dict
Q: Embedded Tomcat NIO thread pool - no threads added I running a Spring Boot 2.6.x application (bundled with Tomcat 9.56.x) with the following configuration: server.tomcat.accept-count = 100 server.tomcat.threads.max = 1000 server.tomcat.threads.min-spare = 10 on a machine with 16 CPU cores and 32GB of RAM I testing a performance load of my server, during which I'm opening multiple (500) connections and each one sends a HTTP request every 1 second. Expected behavior: tomcat will attempt to use as much threads as possible in order to maximize a throughput. Actual behavior: tomcat always stick to 10 threads (which are configured by "min-spare") and never adding threads above that configured amount. I know that by observing its JMX endpoint (currentThreadCount is always 10). This is despite that it definitely not able to process all requests in time, since I have growing amount of pending requests in my client. Does anyone can explain me such behavior? Based on what Tomcat (the NIO thread pool) supposed to decide whether to add threads? A: Turns out the issue was in my client. For issuing requests, I was using RestTemplate which internally was using HttpClient. Well, HttpClient internally managing connections and by default it has ridiculously low limits configured - max 20 concurrent connections... I solved the issue by configuring PoolingHttpClientConnectionManager (which supposed to deliver better throughput in multi-threaded environment) and increased limits: HttpClientBuilder clientBuilder = HttpClientBuilder.create(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setMaxTotal(10000); connManager.setDefaultMaxPerRoute(10000); clientBuilder.setConnectionManager(connManager); HttpClient httpClient = clientBuilder.build(); After doing that, I greatly increased issued requests per second which made Tomcat to add new threads - as expected
{ "language": "en", "url": "https://stackoverflow.com/questions/70820795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: About div positions My page is split into two columns, like this : <div id="wrapper"> <div id="left" style="float:left; width:15%;"> <span style="width:15%"; id="dog">Hi i'm a dog</span> </div> <div id="right" style="float:left; width:85%;"> <p>Hello world</p> </div> </div> However, the height of the span (dog) is positioned using JS : document.getElementById("dog").style.position = "absolute"; document.getElementById("dog").style.top = "20px"; And in this case, the left column will be considered empty, and the content of the right column will ignore the 15% and start at the left of the screen, overlapping the span text. So far, I can solve this by just writing at least one character in the left column without JS. How else can I "force" the right column to start after the 15% of the left column ? thanks A: Use min-height See: http://jsfiddle.net/jN9SV/ <div id="wrapper"> <div id="left" style="float:left; width:15%; min-height:1px"> <span style="width:15%"; id="dog">Hi i'm a dog</span> </div> <div id="right" style="float:left; width:85%;"> <p>Hello world</p> </div> </div> A: Using float: right for the second division helps if you are dealing with just two divisions. <div id="wrapper"> <div id="left" style="float:left; width:15%;"> <span style="width:15%"; id="dog">Hi i'm a dog</span> </div> <div id="right" style="float:right; width:85%;"> <p>Hello world</p> </div> </div> A: See below - use a combination of "min-width" and change the right div to "float:right": <div id="wrapper"> <div id="left" style="float:left; width:15%; min-width:15%"> <span style="width:15%"; id="dog"></span> </div> <div id="right" style="float:right; width:85%;"> <p>Hello world</p> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/23185490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unity XML Config Test We are constantly having problem with our application being broken due to the Unity configuration not being able to resolve dependencies, either the dll or namespace has been changed or is initially wrong. Can anyone point me in the right direction for writing a Test that will ensure all the Unity config files can resolve their dependencies? Thanks... A: See if this question may be of help to you: Is there TryResolve in Unity?
{ "language": "en", "url": "https://stackoverflow.com/questions/1565168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is jar file not being found with classpath spec? (FileChooserDemo from Oracle) Downloaded the latest Java SE. Ran FileChooserDemo via JNLP at http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html Works fine. (Windows box.) Downloaded the source from http://docs.oracle.com/javase/tutorial/uiswing/examples/components/index.html#JWSFileChooserDemo Following the compile instructions in the java source: C:components> javac -classpath .;jars/jnlp.jar JWSFileChooserDemo.java This works fine. Two class files are generated in the components dir. Then... C:components>cd .. C:src> java -classpath .;jars/jnlp.jar components.JWSFileChooserDemo Exception in thread "main" java.lang.NoClassDefFoundError:javax/jnlp/UnavailableServiceException at java.lang.Class.getDeclaredMethods0(Native Method) . . . So the UnavailableServiceException.class isn't being found. But if you list the jar file, the class IS there. So my classpath is just wrong. C:jars> tar tf jnlp.jar META-INF/ META-INF/MANIFEST.MF javax/jnlp/ javax/jnlp/BasicService.class javax/jnlp/ClipboardService.class javax/jnlp/DownloadService.class javax/jnlp/DownloadServiceListener.class javax/jnlp/ExtensionInstallerService.class javax/jnlp/FileContents.class javax/jnlp/FileOpenService.class javax/jnlp/FileSaveService.class javax/jnlp/JNLPRandomAccessFile.class javax/jnlp/PersistenceService.class javax/jnlp/PrintService.class javax/jnlp/ServiceManager.class javax/jnlp/ServiceManagerStub.class javax/jnlp/UnavailableServiceException.class I tried this on Mac OSX (you have to change semicolons into colons in the classpath) and same exact thing. Update: I found an older version of this demo online that doesn't use UnavailableSewrviceException and compiles standalone. It works fine with current Java and suits my purposes. I still do not understand why the commands given above do not work. A: Follow these steps : Say the directory structure is this on my side, under C Drive : components-JWSFileChooserDemoProject | ------------------------------------ | | | | nbproject src build.xml manifest.mf | components | ------------------------------------------------- | | | | images jars | | JWSFileChooserDemo.java JWSFileChooserDemo.jnlp Under components Directory create a new Directory called build so now Directory - components will have five thingies, instead of four i.e. build, images, jars, JWSFileChooserDemo.java and JWSFileChooserDemo.jnlp. Now first go to components Directory. To compile write this command : C:\components-JWSFileChooserDemoProject\src\components>javac -classpath images\*;jars\*;build -d build JWSFileChooserDemo.java Here inside -classpath option, you are specifying that content of Directories images, jars and build is to be included while compiling JWSFileChooserDemo.java. -d option basically tells, as to where to place the .class files. Move to "build" folder : C:\components-JWSFileChooserDemoProject\src\components>cd build Run the Program : C:\components-JWSFileChooserDemoProject\src\components\build>java -cp .;..\images\*;..\jars\* components.JWSFileChooserDemo Here inside -cp option . represents, that look from the current position, ..\images\* means, go one level up inside images Directory, from the current location and get all its contents and the same goes for ..\jars\* thingy too. Now you will see it working, and giving the following output : EDIT 1 : Since you wanted to do it without -d option of the Java Compiler - javac. Considering the same directory structure, as before, move inside your components Directory. COMPILE with this command : C:\components-JWSFileChooserDemoProject\src\components>javac -classpath images\*;jars\* JWSFileChooserDemo.java Now manually create the package structure in the File System, i.e. create Directory components and then move your .class files created previously, inside this newly created components Directory, and also add images folder to this newly created components folder. Now Directory - components will have five thingies, instead of four i.e. components(which further contains JWSFileChooserDemo.class , JWSFileChooserDemo$1.class and images folder), images, jars, JWSFileChooserDemo.java and JWSFileChooserDemo.jnlp. RUN the program with this command : C:\components-JWSFileChooserDemoProject\src\components>java -cp .;jars\* components.JWSFileChooserDemo This will give you the previous output, though, if you wanted to move as suggested before, again copy images folder to the automatically generated components folder, since I just looked inside the .java and they using relative path for it to work. JUST THIS PARTICULAR SOLUTION, I AM ABOUT TO DESCRIBE WILL WORK FOR YOUR CASE ONLY : If after javac command given before, if you don't wanted to create any folder, then go one level up, i.e. outside components directory and use this command to run the program C:\components-JWSFileChooserDemoProject\src>java -cp .;components\jars\* components.JWSFileChooserDemo If you don't wanted to
{ "language": "en", "url": "https://stackoverflow.com/questions/17738100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python: Combine "if 'x' in dict" and "for i in dict['x']" Really two questions: If I have a dictionary (that originally came from parsing a json message) that has an optional array in it: dict_with = {'name':'bob','city':'san francisco','kids': {'name': 'alice'} } dict_without = {'name':'bob','city':'san francisco' } I would normally have code like: if 'kids' in dict: for k in dict['kids']: #do stuff My first question is there any python way to combine the if protection and the for loop? The second question is my gut tells me the better design for the original json message would be to always specify the kids element, just with an empty dictionary: dict_better = {'name':'bob','city':'san francisco','kids': {} } I can't find any design methodology that substantiates this. The json message is a state message from a web service that supports json and xml representations. Since they started with xml, they made it so the "kids" element was optional, which forces the construct above of checking to see if the element exists before iterating over the array. I would like to know if it's better design-wise to say the element is required (just with an empty array if there are no elements). A: An empty sequence results in no iteration. for k in D.get('kids', ()): A: [x for x in dict_with.get('kids')], You can use this filter, map - a functional programming tools with the list comprehension. * *list comprehension are more concise to write. *run much faster than manual for loop statements. *To avoid key-error use dict_with.get('xyz',[]) returns a empty list. A: for x in d.get("kids", ()): print "kid:", x
{ "language": "en", "url": "https://stackoverflow.com/questions/4464274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Spring MVC with H2 throwing table not found I know that this kind of a question happened to occur many times, but I'm still missing something. I'm building some simple web shop application with a classic Spring MVC (not Boot!), JPA with Hibernate and unfortunate H2 :) This is my application.properties: ################### DataSource Configuration ########################## spring.datasource.url=jdbc:h2:mem:webshop;DB_CLOSE_DELAY=-1 spring.datasource.driverClassName=org.h2.Driver spring.datasource.platform=h2 spring.datasource.username=webshopdba spring.datasource.password=123 spring.datasource.initialize=true ################### JPA ################### spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect ################### H2 ################### spring.h2.console.path=/h2 spring.h2.console.enabled=true ################### Hibernate ################### logging.level.org.hibernate.SQL=INFO hibernate.show-sql=true Here's an example model class: package com.webshop.model; import lombok.Data; import javax.persistence.*; import java.util.Date; @Entity @Data @Table(name = "PROGRAM") public class Program { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") private Long id; @Column(name = "PROGRAM_NAME") private String programName; @Column(name = "DESCRIPTION") private String description; } And here's persistence config: @Configuration @EnableSpringDataWebSupport @EnableTransactionManagement @PropertySource("classpath:application.properties") @ComponentScan(basePackages = "com.webshop.repositories") @EnableJpaRepositories(basePackages = "com.webshop.repositories") public class PersistenceConfig { private final Environment env; @Autowired public PersistenceConfig(Environment env) { this.env = env; } @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .setName("webshop") .build(); } @Bean public EntityManagerFactory entityManagerFactory() { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); Properties jpaProperties = new Properties(); jpaProperties.put("hibernate.show-sql", env.getProperty("hibernate.show-sql")); jpaProperties.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect")); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setDataSource(dataSource()); factory.setPackagesToScan("com.webshop"); factory.setJpaVendorAdapter(vendorAdapter); factory.setJpaProperties(jpaProperties); factory.afterPropertiesSet(); return factory.getObject(); } @Bean public DataSourceInitializer dataSourceInitializer() { ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator(); resourceDatabasePopulator.addScript(new ClassPathResource("/schema-h2.sql")); DataSourceInitializer dataSourceInitializer = new DataSourceInitializer(); dataSourceInitializer.setDataSource(dataSource()); dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator); return dataSourceInitializer; } @Bean public PlatformTransactionManager transactionManager() { JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setEntityManagerFactory(entityManagerFactory()); return txManager; } } And here's schema-h2.sql: CREATE SCHEMA IF NOT EXISTS webshop; SET SCHEMA webshop; CREATE USER IF NOT EXISTS WEBSHOPDBA PASSWORD '123' ADMIN; CREATE TABLE IF NOT EXISTS PROGRAM ( ID BIGINT PRIMARY KEY AUTO_INCREMENT, PROGRAM_NAME VARCHAR(255), DESCRIPTION VARCHAR(255) ); INSERT INTO PROGRAM (PROGRAM_NAME, DESCRIPTION) VALUES ('Example software', 'Example') Right now the application boots up properly, reads schema-h2.sql, loads it and it's ready for work, but if I do anything related to the persistence, it throws SqlExceptionHelper:142 - Table "PROGRAM" not found; SQL statement: insert into PROGRAM (PROGRAM_NAME, DESCRIPTION) values (null, ?, ?) [42102-196] Although I can use /h2-console path and get into H2, where my schema, table and one example insert are present (with a user defined in SQL). I can also see in tomcat logs that my queries where executed successfully. What might be the issue here? I feel like when trying to perform any persistence action my code creates a new instance of the DB and the previous one is lost, however DB_CLOSE_DELAY=-1 should prevent that according to the H2 docs. What I've tried so far: * *Setting hibernate ddl-auto or hibernate.hbm2ddl.auto to create/create-drop/update/none - no difference, spring.jpa.hibernate.ddl-auto=create *Dividing my SQL file into schema/data, import, just schema, no difference as well, *Explicitly declare spring.datasource.initialization-mode=embedded with no effect, *Adding init schema to connection string, *Declaring dataSource with DriverManagerDataSource I'm slowly running out of ideas, can someone advice me what I might be doing wrong here? Help me StackOverflow you are my only hope!
{ "language": "en", "url": "https://stackoverflow.com/questions/63629490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: trigger azure pipeline from another repo, on tag I am trying to trigger a pipeline when another repo is tagged. resources: repositories: - repository: myrepo name: myproject/my-repo ref: main type: git trigger: tags: include: - "*" I can run the pipeline manually, but it's not triggered via tag in the referenced repo. I have also tried to provide a specific tag for test purposes. Which also didn't work when creating a tag from main branch via the UI. tags: include: - "*" Another thing I have tried is using the branch trick, which has helped me in the past for pipeline resources. trigger: branches: include: - refs/tags/* A: Looks like it doesn't work for some reasons or I didn't find the way to make it work. A possible workaround solution would be, if you create a simple pipeline in your source repo, which is triggered on new tag and just runs through or maybe does some validation work if needed. In your target pipeline you create a trigger for it like that: resources: pipelines: - pipeline: myrepo-pipeline source: myrepo-pipeline-build trigger: true If the first pipeline successfully runs, it triggers the actual pipeline.
{ "language": "en", "url": "https://stackoverflow.com/questions/71157052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django Login form not authenticating Trying to create a login view using class based views (first time), and everything populates, but it keeps saying that my username is invalid. Please help me figure out whats wrong. login.html (Edited to show entire form): <div class="card border-grey border-lighten-3 px-1 py-1 m-0"> <div class="card-header no-border"> <div class="card-title text-xs-center"> <img src="{% static 'images/logo/stack-logo-dark.png' %}" alt="branding logo"> {% if form.non_field_errors %} {% for error in form.non_field_errors %} <h6 class="card-subtitle line-on-side text-muted text-xs-center font-small-3 pt-2 danger"><span>Sorry, that login was invalid. Please try again.</span></h6> {% endfor %} {% endif %} </div> </div> <div class="card-body collapse in"> <div class="card-block"> <form class="form-horizontal" method="post" action="{% url 'dispatch:login' %}" role="form"> {% csrf_token %} <fieldset class="form-group position-relative has-icon-left"> <input type="text" class="form-control" id="username" placeholder="Your Username" required> <div class="form-control-position"> <i class="ft-user"></i> </div> </fieldset> <fieldset class="form-group position-relative has-icon-left"> <input type="password" class="form-control" id="password" placeholder="Enter Password" required> <div class="form-control-position"> <i class="fa fa-key"></i> </div> </fieldset> <fieldset class="form-group row"> <div class="col-md-6 col-xs-12 text-xs-center text-sm-left"> <fieldset> <input type="checkbox" id="remember-me" class="chk-remember"> <label for="remember-me"> Remember Me</label> </fieldset> </div> <div class="col-md-6 col-xs-12 float-sm-left text-xs-center text-sm-right"><a href="recover-password.html" class="card-link">Forgot Password?</a></div> </fieldset> <button type="submit" class="btn btn-outline-primary btn-block"><i class="ft-unlock"></i> Login</button> </form> views.py: (Pulled from a tutorial) class LoginView(FormView): """ Provides the ability to login as a user with a username and password """ success_url = '/' form_class = LoginForm redirect_field_name = REDIRECT_FIELD_NAME template_name = 'pages/login.html' @method_decorator(sensitive_post_parameters('password')) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): # Sets a test cookie to make sure the user has cookies enabled request.session.set_test_cookie() return super(LoginView, self).dispatch(request, *args, **kwargs) def form_valid(self, form): auth_login(self.request, form.get_user()) # If the test cookie worked, go ahead and # delete it since its no longer needed if self.request.session.test_cookie_worked(): self.request.session.delete_test_cookie() return super(LoginView, self).form_valid(form) def get_success_url(self): redirect_to = self.request.REQUEST.get(self.redirect_field_name) if not is_safe_url(url=redirect_to, host=self.request.get_host()): redirect_to = self.success_url return redirect_to class LogoutView(RedirectView): """ Provides users the ability to logout """ url = '/accounts/login/' def get(self, request, *args, **kwargs): auth_logout(request) return super(LogoutView, self).get(request, *args, **kwargs) forms.py class LoginForm(forms.Form): username = forms.CharField(max_length=255, required=True) password = forms.CharField(widget=forms.PasswordInput, required=True) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') user = authenticate(username=username, password=password) if not user or not user.is_active: raise forms.ValidationError("Sorry, that login was invalid. Please try again.") return self.cleaned_data def login(self, request): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') user = authenticate(username=username, password=password) return user urls.py app_name = 'dispatch' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^accounts/login/$', views.LoginView.as_view(), name='login'), url(r'^logout/$', views.LogoutView.as_view(), {'next_page': '/accounts/login'}, name='logout'), url(r'^profile/(?P<pk>\d+)/$', views.ProfileDetailView.as_view(), name='profile_detail'), ] A: I'm not sure why that tutorial made it so complex, but all you should have to do is extend the default login view and add your get_success_url function and template_name from django.contrib.auth.views import LoginView as AuthLoginView class LoginView(AuthLoginView): success_url = '/' template_name = 'pages/login.html' redirect_field_name = REDIRECT_FIELD_NAME def get_success_url(self): redirect_to = self.request.GET.get(self.redirect_field_name) if not is_safe_url(url=redirect_to, host=self.request.get_host()): redirect_to = self.success_url return redirect_to Edit: your form is missing the name property on the inputs. That's where django is looking for the values. <input type="text" name="{{ form.username.name }}" /> <input type="password" name="{{ form.password.name }}" />
{ "language": "en", "url": "https://stackoverflow.com/questions/44531069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How find a value in all table postgress I have a db postgress and I need to find a value in all table: For example: I have this value 'Alida' I need to obtain all tables names that contains column value 'alida'. I'm new and I don't know how i can do this? Anyone can help me?
{ "language": "en", "url": "https://stackoverflow.com/questions/68084703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: gdb Debugger Remot localhost Could someone help me with this? I need to do the debugger step by step with the GDB but it is aborted. (gdb) s Single stepping until exit from function main, which has no line number information. warning: Exception condition detected on fd 536 Remote communication error. Target disconnected.: No such file or directory. I have tried normal c code with it and it worked quite well but when I use it with my big project it hangs. A: The errors warning: Exception condition detected on fd 536 and Remote communication error. Target disconnected.: No such file or directory. almost always mean that the remote target has died unexpectedly. You didn't mention if you are using standard gdbserver, or some other remote target, but if you start your remote target in a separate terminal, and then connect GDB and step through, you should notice that your remote target exits (crashes maybe?), and this will correspond to the time when GDB throws the above error. You should file a bug against whoever provides your remote target. If this is stock gdbserver, then that would be the GDB project itself, but if it is some other remote target, then you should approach them.
{ "language": "en", "url": "https://stackoverflow.com/questions/71561308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I am getting this error when compiling my program. Operator " + " cannot be applied to operands of "System.Random" and "System.Random" I am trying to generate random numbers for math problems. When the program is compiled the error Operator " + " cannot be applied to operands of type 'System.Random' and 'System.Random. I really dont know how to fix this error. Random num1 = new Random(0); Random num2 =new Random(0); int rand; Console.Write("What is"); Console.Write(num1); Console.Write( " - "); Console.Write( num2); Console.Write( "?"); int answer = Console.Read(); if (num1 + num2 == answer) ERROR { Console.Write(" Your are Correct!\n"); correctCount++; } else Console.Write( "Your answer is wrong" ); Console.Write(num1); Console.Write(" + "); Console.Write(num2); Console.Write("should be "); Console.Write(num1 + num2); ERROR count++; } } } } Now i am able to compile the program without any errors, but it is not generating any numbers. Does anyone see what i may have donwe wrong. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace Jagtutor { [Activity(Label = "Addition")] public class AdditionsActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Create your application here SetContentView(Resource.Layout.Second); var label = FindViewById<TextView>(Resource.Id.screen3Label); label.Text = Intent.GetStringExtra("ModuleData") ?? "Data not available"; { int correctCount = 0; int count = 0; while (count < 10); { Random gen = new Random(); int num1 = gen.Next(); int num2 = gen.Next(); Console.Write("What is"); Console.Write(num1); Console.Write( " - "); Console.Write( num2); Console.Write( "?"); int answer = Int32.Parse(Console.ReadLine()); if (num1 + num2 == answer) { Console.Write(" Your are Correct!\n"); correctCount++; } else Console.Write( "Your answer is wrong" ); Console.Write(num1); Console.Write(" + "); Console.Write(num2); Console.Write("should be "); Console.Write(num1 + num2); count++; } } } } } A: You misunderstood the way Random is used: it is not a number, it is a class that can be used to generate random numbers. Try this: // Make a generator Random gen = new Random(); // Now we can use our generator to make new random numbers like this: int num1 = gen.Next(); int num2 = gen.Next(); Every time you call gen.Next() you get a new random number. If you would like the sequence of random numbers to be repeatable, pass a number (any number) to the constructor of the Random. Beware that every time you run your program the result will stay the same. A: There are quite a few issues with the code snippet you pasted. I'd suggest (if you haven't already) investing in a decent beginning C# book. Generating random numbers, in fact, is one of the most popular "example programs" you find in those kinds of books. However, to get you started, here's some key points: * *When you paste sample code to a site like this, make sure it is a short, self-contained, correct example. Even if we fix the compiler error in your code, there are several other issues with it, including unbalanced and/or missing braces. Start simple and build your example up until you get the error, then paste that code. Note that a good 75% of the time this will help you fix the error yourself. For example, if you removed the lines of code that did not compile, and just ran the first part, it would print out "What is System.Random - System.Random?", which should give you a pretty clear idea that your num1 and num2 are not what you thought they were. *As the rest of the answers here have pointed out, you have a fundamental misunderstanding of how the C# Random class works. (Don't feel bad, computer-generated "random numbers" make no sense to anyone until someone explains them to you.) The solution provided in those answers is correct: Random is a random number generator, and you need to call one of the Next functions on your instance to get an integer from it. Also, you usually will not want multiple instances of Random unless you actually want to produce the same random sequence more than once. The MSDN article has a very thorough example. *While not "wrong" per-se, you're not being very efficient with your console output. Console's read and write functions operate entirely on string objects, and they have built-in composite formatting capabilities. For example, your first few lines of code could be rewritten as: var random = new Random(); var x = random.Next(); var y = random.Next(); Console.Write("What is {0} + {1}? ", x, y); *As I mentioned in my comment, Console.Read() is not the correct function to read in complete user input; it returns data a single UTF-16 character at a time. For example, if the user typed in 150 you would get 49, 53, and 48, in that order. Since you presumably want to allow the user to type in more than one digit at a time, you should instead called Console.ReadLine(), which returns the entire string, then convert that to an integer using Int32.Parse() or some similar function. A: You are trying to add two random generators not random numbers, use this: Random randomGenerator = new Random(0); var num1 = randomGenerator.Next(); var num2 = randomGenerator.Next(); A: You need to call one of the overloads of Random.Next() http://msdn.microsoft.com/en-us/library/9b3ta19y.aspx to get the actual random number.
{ "language": "en", "url": "https://stackoverflow.com/questions/10321246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: li-tags are vertically aligned in ul-tag but not the text itself My pen: http://codepen.io/helloworld/pen/pCdBe I have aligned 3 li elements in an ul-tag vertically with percent values considerung the height of the parent ul. I also want that the li elements text like 1 or 2 is vertically aligned and there is still a bug in the pen. Why is there such a gap on the left side of the numbers? <ul id="navigationWheeler" > <li>1</li> <li style="background-color: #0094ff;">2</li> <li>3</li> </ul> #navigationWheeler { height: 300px; width:30px; text-align: center; vertical-align: middle; border: black solid 1px; background-color: lightgray; } li{ list-style:none; height:33%; vertical-align: middle; } A: li tags align themselves vertically but not their content, so in order to align the content vertically either you need to use display: table-cell; or line-height property li{ list-style:none; height:33%; vertical-align: middle; line-height: 100px; } Demo Also I don't think you are resetting the stylesheet in your codepen demo, search for CSS reset and you will get loads of reset stylesheets which will reset the browser applied default styles. A: Check this out: http://codepen.io/anon/pen/xHncd #navigationWheeler { height: 300px; width:30px; text-align: center; vertical-align: middle; border: black solid 1px; background-color: lightgray; } li{ list-style:none; height:33%; vertical-align: middle; } li:before { content: ''; display: inline-block; height: 100%; vertical-align: middle; } It's a bit hacky, but you can keep percentage as the height for your li-tags. A: It appears some padding is being applied to the ul. This is most likely the default styling of the browser and a CSS reset would remove this. Remove this padding and place a width on the ul to horizontally center the elements. navigationWheeler { height: 300px; width:30px; text-align: center; vertical-align: middle; border: black solid 1px; background-color: lightgray; padding: 0px; width: 100px; } Adding padding to the li elements can vertically center the text within them. li{ list-style:none; height:33%; vertical-align: middle; padding-top: 50%; } Working Example http://codepen.io/anon/pen/Djzhy A: All solutions I have seen so far work partly. This is the full working pen: * *No padding/margin on ul-tag *li-tags increase with the height of their parent by %. http://codepen.io/helloworld/pen/IfymB <ul id="navigationWheeler" > <li> <div>1</div> </li> <li style="background-color: #0094ff;"> <div>2</div> </li> <li> <div>3</div> </li> </ul> #navigationWheeler { height: 300px; width:30px; text-align: center; vertical-align: middle; border: black solid 1px; background-color: lightgray; padding:0; margin:0; } li{ list-style:none; height:33%; vertical-align: middle; display:table; } div{ width:30px; display:table-cell; vertical-align: middle; }
{ "language": "en", "url": "https://stackoverflow.com/questions/18011887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting ACL values through ACL name via Powershell Hope you guys are safe and healthy! Can I ask if there is a way to use powershell to get the ACL based on the ACL name and extract the values out? I am trying to compare the selected file or registry permissions with the ACL that I would be provided by user. Example: Inputs: * *HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\Test *ACL2 (name of ACL) Output: True (the permissions from input 1 matches the permissions in ACL2) False (does match) With these inputs, the script should get the permissions of the input 1 and compare to the permissions listed in ACL2. What I am confused is, is there a list of ACLs that I can look for in Windows or through powershell? Edit: Updated question.
{ "language": "en", "url": "https://stackoverflow.com/questions/67736519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cloudflare stops javascript passing variables to external files I have Rocketloader enabled in my cloudflare account so that might be the issue, but how can I work around it? The situation is I have an external file login.js which handles login forms across the site, but when a user accesses a page when they aren't logged in, the requested url is appended to the login page. An example of accessing foo.com/secure/page26 when not logged in results in being directed to foo.com/login.php?back=secure/page26. so within my login page I have the following setup: <script>var BackURL="secure/page26";</script> <script src="login.js"></script> Within login.js I have: ** SUCCESFULLY LOGGED IN SCRIPT HERE ** window.location.href = "/"+BackURL; But this doesn't work, I guess it is due to Rocketloader, but how can I get around this? A: You could store the BackUrl parameter in a cookie and check for that cookie existence everytime you log in. If it's defined, then remove it and redirect the user to its value. A: "But this doesn't work, I guess it is due to Rocketloader, but how can I get around this?" The easy way to check this would be to simply disable Rocket Loader in your settings & then try it again (might need to flush your browser cache after doing it). You could also pause CloudFlare entirely in your settings to see if the behavior changes).
{ "language": "en", "url": "https://stackoverflow.com/questions/22642865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what " setContentView " helps in I tried to make a new Relativelayout, I then created a button, finally I added this button to the layout. but what does " setContentView " help to achieve? Here is the code RelativeLayout wassimLayout = new RelativeLayout(this); Button redButton = new Button(this); wassimLayout.addView(redButton); setContentView(wassimLayout); I don't know, but I feel it perhaps sets the buttons height, width and other characteristics to default. how do i prevent that? Thanks A: Since you are creating views in code and not in the xml, you need to create and set LayoutParams for both the RelativeLayout and the Button. A: I am not sure you wrote that correct because setContentView connects Java file with xml file and the correct way to do this is to write this setContentView(R.layout.your_layout_name); in main which in android is onCreate method.
{ "language": "en", "url": "https://stackoverflow.com/questions/29354185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BeanCreationException: autowired dependencies failed with another maven spring project I have some trouble with autowired in combination with a second spring boot project. Hopefully, you can give me some hints to fix the issue. Project setup: The project datahub manages the data store access. The project dataintegration does some other stuff but needs the project datahub to comunicate with the data store. Both projects base on spring boot and are realized as maven projects. Problem: When I try to start dataintegration project (run Application.java), where the datahub project is integrated via maven dependency, I get the exception at the end of the thread. The project datahub works as stand-alone demo application. It works also together (integrated via pom.xml as dependency) with a spring boot web application (Reading data store entities via HTTP request). Any ideas??? The most frustrating point is that the same setup is working when the project dataintegration is realized as web application. But it isn't working when dataintegration is realized as native java application (jar). Datahub (com.example.mcp.datahub): Application.java package com.example.mcp.datahub; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.example.mcp.datahub.model.WorkingDay; import com.example.mcp.datahub.service.WorkingDayService; @SpringBootApplication @EnableTransactionManagement @ComponentScan("com.example.mcp") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } WorkingDayRepository.java package com.example.mcp.datahub.repositories; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.example.mcp.datahub.model.WorkingDay; @Repository public interface WorkingDayRepository extends CrudRepository<WorkingDay, Long> { } WorkingDayService.java package com.example.mcp.datahub.service; import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.example.mcp.datahub.model.WorkingDay; import com.example.mcp.datahub.repositories.WorkingDayRepository; @Service @ComponentScan("com.example.mcp") public class WorkingDayService { @Autowired public WorkingDayRepository workingDayRepository; @Transactional(readOnly=true) public List<WorkingDay> getWorkingDays() { List<WorkingDay> list = (List<WorkingDay>) workingDayRepository.findAll(); return list; } } pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example.mcp.datahub</groupId> <artifactId>com.example.mcp.datahub</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>com.example.mcp.datahub</name> <description>Data Hub</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.7</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Dataintegration (com.example.mcp.dataintegration): Application.java package com.example.mcp.dataintegration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling @ComponentScan("com.example.mcp") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ScheduledTasks.java package com.example.mcp.dataintegration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import com.example.mcp.datahub.model.WorkingDay; import com.example.mcp.datahub.service.WorkingDayService; @Service @ComponentScan("com.example.mcp") public class ScheduledTasks { @Autowired public WorkingDayService workingDayService; @Scheduled(fixedDelay = 5000) public void reportCurrentTime() { //do something with workingDayService } } pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example.mcp.dataintegration</groupId> <artifactId>com.example.mcp.dataintegration</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>com.example.mcp.dataintegration</name> <description>Data Integration Layer</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.7</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.example.mcp.datahub</groupId> <artifactId>com.example.mcp.datahub</artifactId> <version>0.0.1-SNAPSHOT</version> <scope>compile</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Exception org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scheduledTasks': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.example.mcp.datahub.service.WorkingDayService com.example.mcp.dataintegration.ScheduledTasks.workingDayService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'workingDayService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.example.mcp.datahub.repositories.WorkingDayRepository com.example.mcp.datahub.service.WorkingDayService.workingDayRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.mcp.datahub.repositories.WorkingDayRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] ... at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE] at com.example.mcp.dataintegration.Application.main(Application.java:15) [classes/:na] Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.example.mcp.datahub.service.WorkingDayService com.example.mcp.dataintegration.ScheduledTasks.workingDayService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'workingDayService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.example.mcp.datahub.repositories.WorkingDayRepository com.example.mcp.datahub.service.WorkingDayService.workingDayRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.mcp.datahub.repositories.WorkingDayRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] ... 16 common frames omitted Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'workingDayService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.example.mcp.datahub.repositories.WorkingDayRepository com.example.mcp.datahub.service.WorkingDayService.workingDayRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.mcp.datahub.repositories.WorkingDayRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] ... at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] ... 18 common frames omitted Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.example.mcp.datahub.repositories.WorkingDayRepository com.example.mcp.datahub.service.WorkingDayService.workingDayRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.mcp.datahub.repositories.WorkingDayRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] ... 29 common frames omitted Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.mcp.datahub.repositories.WorkingDayRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] ... at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE] ... 31 common frames omitted A: I already solved the problem. The following post was quite helpful: Spring Boot And Multi-Module Maven Projects I moved the file com.example.mcp.dataintegration.Application.java to com.example.mcp.Application.java. But furthermore unclear why my ComponentScan amd JPARepo definition were ignored... A: Did you try @EnableJpaRepositories with @Configuration in Application class that you run. I have tried something like this for one of my projects which is similar to yours and it worked for me; @Configuration @EnableJpaRepositories("com.example.mcp") @EntityScan("com.example.mcp") WorkingDay has @Entity annotation.
{ "language": "en", "url": "https://stackoverflow.com/questions/38262393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Generate a code from a java class that uses another java class (BCEL) I am trying to generate(and modify) the code of an output class from another class using the ByteCode Engineering Library (by Apache) . String class_name = c_gen.getClassName(); Method[] Methods = c_gen.getMethods(); for (int i=0;i<Methods.length;i++) { MethodGen m_gen = new MethodGen(Methods[i], class_name, cpg); InstructionList il = m_gen.getInstructionList(); InstructionHandle h; il.insert(h,factory.createInvoke("ClassName","printSomething", Type.VOID,new Type[]{Type.STRING}, INVOKESTATIC)); } so I am trying to call printSomething from ClassName for every method.The problem is that I don't know how to actually pass the string argument to the method printSomething A: You will need to push the string argument on the stack before the invokestatic. This is done with the LDC opcode. Something like: il.insert( new LDC(cpg.addString("MyString"))); The outline looks like this: JavaClass clazz = Repository.lookupClass( class_name ); ClassGen c_gen = new ClassGen( clazz ); ConstantPoolGen cpg = new ConstantPoolGen( clazz.getConstantPool() ); InstructionFactory factory = new InstructionFactory( c_gen, cpg ); Methods [] methods = clazz.getMethods(); for ( int i = 0; i < methods.length; i ++ ) { if ( m.isAbstract() || m.isNative() || .... ) continue; MethodGen m_gen = new MethodGen( methods[i], class_name, cpg ); InstructionList il = m_gen.getInstructionList(); il.insert( factory.createInvoke("ClassName", "printSomething", Type.VOID, new Type[]{Type.STRING}, INVOKESTATIC) ); il.insert( factory.createPush( "StringToPrint" ) ); methods[i] = m_gen.getMethod(); } clazz.setConstantPool( cpg.getFinalConstantPool() ); clazz.setMethods( methods ); // might be redundant clazz.dump( new File( .... ) ); A few notes: * *Since we're inserting, every insert will prepend to the method. This is why we first insert the instruction opcode, and then the arguments (in reverse), so that the actual sequence will be ldc #stringref; invokestatic #methodref. *We need to replace the ConstantPool and the Methods with our modified versions of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/33457190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Searching multiple fields in elasticsearch I'm indexing meta data on files and my mappings looks like this: curl -XPUT "http://localhost:9200/myapp/" -d ' { "mappings": { "file": { "properties": { "name": { "type": "string", "index": "not_analyzed" }, "path": { "type": "string", "index": "not_analyzed" }, "user": { "type": "string", "index": "not_analyzed" } } } } } ' There are some other fields too, but they are not relevant to this question. Here 'name' is the name of a file, 'path' is the path to the file and user is the owner of that file. When indexing the data could look something like: { name: 'foo', path: '/', user: 'dude' } { name: 'bar', path: '/subfolder/', user: 'dude' } { name: 'baz', path: '/', user: 'someotherdude' } My question is how to build my query so that I can do folder listings given a path and a user. So searching for the user 'dude' and path '/' should result in 'foo'. A: You can use a bool which allows you to specify the queries that must match to constitute a hit. Your query will look something like this { "query": { "bool" : { "must" : [ { "match": { "user" : "dude" } }, { "match": { "path" : "/" } } ] } }, "fields": ["name"] } What this does is checks that there is an exact match for the term "dude" and path "/"
{ "language": "en", "url": "https://stackoverflow.com/questions/18214156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is best TypeConverter for Uri? What is the best method of converting android.net.Uri that it can be used with RoomDatabase? A: The best way to store and retrieve Uri with Room is to persist it in the form of String. Moreover we already have the APIs to convert Uri to String and vice versa. There are 2 ways: * *You'll handle the conversion of Uri to String and then storing it and same for fetching. *Let Room do that for you using a TypeConverter. It's completely your choice and the app requirements to choose the way. That said, here is the TypeConverter for Uri <-> String: class UriConverters { @TypeConverter fun fromString(value: String?): Uri? { return if (value == null) null else Uri.parse(value) } @TypeConverter fun toString(uri: Uri?): String? { return uri?.toString() } }
{ "language": "en", "url": "https://stackoverflow.com/questions/49478079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: gcc optimizations: how to deal with macro expantion in strncmp & other functions Take this sample code: #include <string.h> #define STRcommaLEN(str) (str), (sizeof(str)-1) int main() { const char * b = "string2"; const char * c = "string3"; strncmp(b, STRcommaLEN(c)); } If you don't use optimizations in GCC, all is fine, but if you add -O1 and above, as in gcc -E -std=gnu99 -Wall -Wextra -c -I/usr/local/include -O1 sample.c, strncmp becomes a macro, and in preprocessing stage STRcommaLen is not expanded. In fact in resulting "code" strncmp's arguments are completely stripped. I know if I add #define NEWstrncmp(a, b) strncmp (a, b) and use it instead, the problem goes away. However, mapping your own functions to every standard function that may become a macro doesn't seem like a great solution. I tried finding the specific optimization that is responsible for it and failed. In fact if I replace -O1 with all the flags that it enables according to man gcc, the problem goes away. My conclusion is that -O1 adds some optimizations that are not controlled by flags and this is one of them. How would you deal with this issue in a generic way? There may be some macro magic I am not familiar with or compiler flags I haven't looked at? We have many macros and a substantial code base - this code is just written to demonstrate one example. Btw, GCC version/platform is gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5). Thanks, Alen A: You correctly noted that in preprocessing stage STRcommaLen is not expanded - more precisely, not before the strncmp macro gets expanded. This inevitably leads to an error you probably overlooked or forgot to mention: sample.c:7:30: error: macro "strncmp" requires 3 arguments, but only 2 given Your conclusion that -O1 adds some optimizations that are not controlled by flags and this is one of them is also right - this is controlled by the macro __OPTIMIZE__ which apparently gets set by -O1. If I'd do something like that (which I probably wouldn't, in respect of the pitfall you demonstrated by using sizeof a char *), I'd still choose mapping your own functions to every standard function that may become a macro - but rather like #include <string.h> #define STRNCMP(s1, s2) strncmp(s1, s2, sizeof(s2)-1) int main() { const char b[] = "string2"; const char c[] = "string3"; STRNCMP(b, c); }
{ "language": "en", "url": "https://stackoverflow.com/questions/16491342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding data to JSON file through UI I have a UI form wid 2 textboxes I need my Json file to be appended with the values present in 2 textboxes on clicking the submit button. Am using spring MVC architecture here. Just want to know how do I go about this requirement. A: OnClick of your button or any widget should append value like JsonObject value = Json.createObjectBuilder() .add("firstName", "John") .add("lastName", "Smith") .add("age", 25) .add("address", Json.createObjectBuilder() .add("streetAddress", "21 2nd Street") .add("city", "New York") .add("state", "NY") .add("postalCode", "10021")) .add("phoneNumber", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "home") .add("number", "212 555-1234")) .add(Json.createObjectBuilder() .add("type", "fax") .add("number", "646 555-4567"))) .build(); A: Once you get the data in the request object in the controller from the form, take the values and append the values to JSON file through Java I/O. Note: This is not suggestible. Generally, we make use of web applications only when we need to do CRUD operations with data from DB.
{ "language": "en", "url": "https://stackoverflow.com/questions/46590066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to copy and rename files in shell script I have a folder "test" in it there is 20 other folder with different names like A,B ....(actually they are name of people not A, B...) I want to write a shell script that go to each folder like test/A and rename all the .c files with A[1,2..] and copy them to "test" folder. I started like this but I have no idea how to complete it! #!/bin/sh for file in `find test/* -name '*.c'`; do mv $file $*; done Can you help me please? A: This code should get you close. I tried to document exactly what I was doing. It does rely on BASH and the GNU version of find to handle spaces in file names. I tested it on a directory fill of .DOC files, so you'll want to change the extension as well. #!/bin/bash V=1 SRC="." DEST="/tmp" #The last path we saw -- make it garbage, but not blank. (Or it will break the '[' test command LPATH="/////" #Let us find the files we want find $SRC -iname "*.doc" -print0 | while read -d $'\0' i do echo "We found the file name... $i"; #Now, we rip off the off just the file name. FNAME=$(basename "$i" .doc) echo "And the basename is $FNAME"; #Now we get the last chunk of the directory ZPATH=$(dirname "$i" | awk -F'/' '{ print $NF}' ) echo "And the last chunk of the path is... $ZPATH" # If we are down a new path, then reset our counter. if [ $LPATH == $ZPATH ]; then V=1 fi; LPATH=$ZPATH # Eat the error message mkdir $DEST/$ZPATH 2> /dev/null echo cp \"$i\" \"$DEST/${ZPATH}/${FNAME}${V}\" cp "$i" "$DEST/${ZPATH}/${FNAME}${V}" done A: #!/bin/bash ## Find folders under test. This assumes you are already where test exists OR give PATH before "test" folders="$(find test -maxdepth 1 -type d)" ## Look into each folder in $folders and find folder[0-9]*.c file n move them to test folder, right? for folder in $folders; do ##Find folder-named-.c files. leaf_folder="${folder##*/}" folder_named_c_files="$(find $folder -type f -name "*.c" | grep "${leaf_folder}[0-9]")" ## Move these folder_named_c_files to test folder. basename will hold just the file name. ## Don't know as you didn't mention what name the file to rename to, so tweak mv command acc.. for file in $folder_named_c_files; do basename=$file; mv $file test/$basename; done done
{ "language": "en", "url": "https://stackoverflow.com/questions/12452101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to make Wait until all threads finished it's work from threadpool in c# for (int task = 0; task < 20; task++) { ThreadPool.QueueUserWorkItem(new WaitCallback(TaskCallBack), new object[] { filepath1, filepath2, filepath3 }); } public static void TaskCallBack(object state) { object[] array = state as object[]; string filea = Convert.ToString(array[0]); string fileb = Convert.ToString(array[1]); string filec = Convert.ToString(array[2]); //something below } I want main thread to be waited until all threads finishes its work. Please help A: The best way to handle this would be to use Task.Run() and Task.WhenAll(), or to use Parallel.Invoke(). However, if you need to use ThreadPool.QueueUserWorkItem you can solve this issue as follows: * *For ease of use, encapsulate all the data that you want to pass to the thread in a class. This data should include an instance of CountdownEvent initialised with a count equal to the number of threads you want to wait for. (In the sample code below, this class is called ThreadData.) *Inside your TaskCallBack() methods, call CountdownEvent.Signal() when the method has completed. *Inside the main thread, start all the threadpool threads and then call CountdownEvent.Wait() to wait for all the threads to complete. Putting this all together in a compilable console app: using System; using System.Threading; namespace CoreConsole { public sealed class ThreadData { public ThreadData(CountdownEvent countdown, int index) { Countdown = countdown; Index = index; } public CountdownEvent Countdown { get; } public int Index { get; } } public static class Program { static void Main() { int n = 20; var countdown = new CountdownEvent(n); for (int task = 0; task < n; task++) { ThreadPool.QueueUserWorkItem(TaskCallBack, new ThreadData(countdown, task)); } Console.WriteLine("Waiting for all threads to exit"); countdown.Wait(); Console.WriteLine("Waited for all threads to exit"); } public static void TaskCallBack(object state) { var data = (ThreadData) state; Console.WriteLine($"Thread {data.Index} is starting."); Thread.Sleep(_rng.Next(2000, 10000)); data.Countdown.Signal(); Console.WriteLine($"Thread {data.Index} has finished."); } static readonly Random _rng = new Random(45698); } } The ThreadData.Index property is just used to identify each thread in the Console.WriteLine() calls. Note: In real code, it is important to always signal the Countdown event, even if the thread throws an exception - so you should wrap the code in a try/finally like so: public static void TaskCallBack(object state) { var data = (ThreadData)state; try { // Do work here. Console.WriteLine($"Thread {data.Index} is starting."); Thread.Sleep(_rng.Next(2000, 10000)); Console.WriteLine($"Thread {data.Index} has finished."); } finally { data.Countdown.Signal(); } } A: Like @Ackdari mentioned in his comment, you could use Task.Run. But you don't need the await keyword. Just create a collection with the tasks and wait for it. Example: // Create a list that will hold the tasks List<Task> tasks = new List<Task>; // Create the tasks for (int taskId = 0; taskId < 20; task++) { tasks.Add(Task.Run(() => { TaskCallBack(new object[] { filepath1, filepath2, filepath3 }); })); } // Wait for ALL tasks to complete Task.WaitAll(tasks.ToArray()); That way you could also use your own method that will be run by the task. Example: public static void ReplaceWithABetterName(string[] filePaths) { string filea = filePaths[0); string fileb = filePaths[1]; string filec = filePaths[2]; //do stuff }
{ "language": "en", "url": "https://stackoverflow.com/questions/59353866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to use datetime minvalue in get/set method when null is the database value I have two functions, in my constructor I read from the database and call all of my set functions: while (reader.Read()) { Status = reader["status"].ToString(); Event_Start_Date1 = reader.GetDateTime(reader.GetOrdinal("event_start_date1")); } my get and set method for status works fine. for the date field however, i get an error because sometimes the field coming from the database is a NULL value. how would i modify my method to assign the minvalue incase the database returns a NULL? public DateTime Event_Start_Date1 { get { return event_start_date1; } set { event_start_date1 = value; } } A: Wrap the logic in a method: private static DateTime GetDateTimeValue(SqlDataReader reader, string fieldName) { int ordinal = reader.GetOrdinal(fieldName); return reader.IsDBNull(ordinal) ? reader.GetDateTime(ordinal) : DateTime.MinValue; } ...and call it: Event_Start_Date1 = GetDateTimeValue(reader, "event_start_date1"); A more general and reusable approach could be to make it into an extension method that can (optionally) take a default value as input: public static class SqlDataReaderExtensions { public static DateTime GetDateTimeValue(this SqlDataReader reader, string fieldName) { return GetDateTimeValue(reader, fieldName, DateTime.MinValue); } public static DateTime GetDateTimeValue(this SqlDataReader reader, string fieldName, DateTime defaultValue) { int ordinal = reader.GetOrdinal(fieldName); return reader.IsDBNull(ordinal) ? reader.GetDateTime(ordinal) : defaultValue; } } This assumes that you cannot change the model. If you have that option, go with a Nullable<DateTime> instead, and have the GetDateTimeValue method default to returning null. A: Check for DBNull and based on that you can assign MinValue. int ordinal = reader.GetOrdinal("event_start_date1"); Event_Start_Date1 = reader.IsDBNull(ordinal)? DateTime.MinValue: reader.GetDateTime(ordinal); A: Use a nullable DateTime: public DateTime? EventStartDate { get; set; } Which is similar to: public Nullable<DateTime> EventStartDate { get; set; } Read more about Nullable Types To get the default value of DateTime, you can use either DateTime.MinValue or default(DateTime): while (reader.Read()) { Status = reader["status"].ToString(); var startDate = reader.GetOrdinal("event_start_date1"); EventStartDate = if reader.IsDBNull(startDate) ? reader.GetDateTime(ordinal) : default(DateTime); } Essentially, DateTime is a value-type, not a reference type, and there can't be a null DateTime (or whatever other Value Type) compile-time variable, in order for it to be capable to hold a null value it has to be wrapped in the Nullable<T>). In .NET all the non-nullable types have a default value which can be obtained via the default keyword (e.g. default(DateTime)). A: Use DataReader.IsDBNull to check if the value is null: Event_Start_Date1 = reader.IsDBNull("event_start_date1") ? DateTime.MinValue : reader.GetDateTime(reader.GetOrdinal("event_start_date1")); The above sentence is in the following format: Condition ? accepted action : rejected action A: you can use a try-catch while (reader.Read()) { Status = reader["status"].ToString(); try{ Event_Start_Date1 = reader.GetDateTime(reader.GetOrdinal("event_start_date1")); } catch{ Event_Start_Date1 = //some other thing } or you can use GetSqlDateTime() while (reader.Read()) { Status = reader["status"].ToString(); Event_Start_Date1 = reader.GetSqlDateTime(reader.GetOrdinal("event_start_date1")); }
{ "language": "en", "url": "https://stackoverflow.com/questions/5668531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Nested class with numba I tried using numba to speed up the implementation, but when using jitclass, there was a problem with class nesting. I plan to use numba with multiple nested classes, does anyone know what is causing this error? from numba.experimental import jitclass from numba import f8, njit, typeof, void, types import numpy as np spec = [ ("x", f8[:, :]) ] @jitclass(spec) class Vec: def __init__(self, x): self.x = x @property def length(self): return np.linalg.norm(self.x, ord=2) def __mul__(self, other): return np.dot(self.x, other.x.T) def __add__(self, other): return Vec(self.x + other.x) def __sub__(self, other): return Vec(self.x - other.x) spec_next = [ ("a", Vec.class_type.instance_type), ("b", Vec.class_type.instance_type), ("ll", types.List(Vec.class_type.instance_type, reflected=True)) ] @jitclass(spec_next) class Wrapper: def __init__(self, a, b, ll): self.a = a self.b = b self.ll = ll def bin(self): return (self.a + self.b) * (self.a - self.b) def sum(self): c = Vec(np.array([[0, 0]], dtype=np.float64)) for i in range(len(self.ll)): c = c + self.ll[i] return c if __name__ == "__main__": a = Vec(np.array([[1, 3]], dtype=np.float64)) b = Vec(np.array([[2, 3]], dtype=np.float64)) # c = a *b ll = [Vec(np.array([[1, 1]], dtype=np.float64)) for _ in range(1000)] wrap = Wrapper(a, b, ll) print(wrap.bin()) print(wrap.sum()) I got the following error numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend) - Resolution failure for literal arguments: Failed in nopython mode pipeline (step: native lowering) Failed in nopython mode pipeline (step: nopython frontend) No conversion from array(float64, 2d, C) to float64 for '$8return_value.3', defined at None File "test.py", line 45: def bin(self): return (self.a + self.b) * (self.a - self.b) ^ During: typing of assignment at test.py (45) File "test.py", line 45: def bin(self): return (self.a + self.b) * (self.a - self.b) ^ During: lowering "$22binary_multiply.10 = arrayexpr(expr=(<built-in function mul>, [Var($10binary_add.4, test.py:45), Var($20binary_subtract.9, test.py:45)]), ty=array(float64, 2d, C))" at test.py (45) - Resolution failure for non-literal arguments: None During: resolving callee type: BoundFunction((<class 'numba.core.types.misc.ClassInstanceType'>, 'bin') for instance.jitclass.Wrapper#7faa22b12f50<a:instance.jitclass.Vec#7faa20b19e90<x:array(float64, 2d, A)>,b:instance.jitclass.Vec#7faa20b19e90<x:array(float64, 2d, A)>,ll:reflected list(instance.jitclass.Vec#7faa20b19e90<x:array(float64, 2d, A)>)<iv=None>>) During: typing of call at <string> (3) File "<string>", line 3: <source missing, REPL/exec in use?> I see in the error code that a float is required, but I'm not sure why a float is required. can anyone tell me how it is determined by jitclass?
{ "language": "en", "url": "https://stackoverflow.com/questions/73524787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make complete button process the data ? mean submit i wanna ask how to make the final step process the data ? , i've tried use form method to redirect process but it not work . i'm using modal-steps. Already search on stackoverflow but i got nothing, if somebody know how to do it please tellme. i'm using this wizard https://www.jqueryscript.net/other/Wizard-Modal-Bootstrap-jQuery.html ! function(a) { "use strict"; a.fn.modalSteps = function(b) { var c = this, d = a.extend({ btnCancelHtml: "Cancel", btnPreviousHtml: "Previous", btnNextHtml: "Next", btnLastStepHtml: "Complete", disableNextButton: !1, completeCallback: function() {}, callbacks: {}, getTitleAndStep: function() {} }, b), e = function() { var a = d.callbacks["*"]; if (void 0 !== a && "function" != typeof a) throw "everyStepCallback is not a function! I need a function"; if ("function" != typeof d.completeCallback) throw "completeCallback is not a function! I need a function"; for (var b in d.callbacks) if (d.callbacks.hasOwnProperty(b)) { var c = d.callbacks[b]; if ("*" !== b && void 0 !== c && "function" != typeof c) throw "Step " + b + " callback must be a function" } }, f = function(a) { return void 0 !== a && "function" == typeof a && (a(), !0) }; return c.on("show.bs.modal", function() { var l, m, n, o, p, b = c.find(".modal-footer"), g = b.find(".js-btn-step[data-orientation=cancel]"), h = b.find(".js-btn-step[data-orientation=previous]"), i = b.find(".js-btn-step[data-orientation=next]"), j = d.callbacks["*"], k = d.callbacks[1]; d.disableNextButton && i.attr("disabled", "disabled"), h.attr("disabled", "disabled"), e(), f(j), f(k), g.html(d.btnCancelHtml), h.html(d.btnPreviousHtml), i.html(d.btnNextHtml), m = a("<input>").attr({ type: "hidden", id: "actual-step", value: "1" }), c.find("#actual-step").remove(), c.append(m), l = 1, p = l + 1, c.find("[data-step=" + l + "]").removeClass("hide"), i.attr("data-step", p), n = c.find("[data-step=" + l + "]").data("title"), o = a("<span>").addClass("label label-success").html(l), c.find(".js-title-step").append(o).append(" " + n), d.getTitleAndStep(m.attr("data-title"), l) }).on("hidden.bs.modal", function() { var a = c.find("#actual-step"), b = c.find(".js-btn-step[data-orientation=next]"); c.find("[data-step]").not(c.find(".js-btn-step")).addClass("hide"), a.not(c.find(".js-btn-step")).remove(), b.attr("data-step", 1).html(d.btnNextHtml), c.find(".js-title-step").html("") }), c.find(".js-btn-step").on("click", function() { var m, n, o, p, b = a(this), e = c.find("#actual-step"), g = c.find(".js-btn-step[data-orientation=previous]"), h = c.find(".js-btn-step[data-orientation=next]"), i = c.find(".js-title-step"), j = b.data("orientation"), k = parseInt(e.val()), l = d.callbacks["*"]; if (m = c.find("div[data-step]").length, "complete" === b.attr("data-step")) return d.completeCallback(), void c.modal("hide"); if ("next" === j) n = k + 1, g.attr("data-step", k), e.val(n); else { if ("previous" !== j) return void c.modal("hide"); n = k - 1, h.attr("data-step", k), g.attr("data-step", n - 1), e.val(k - 1) } parseInt(e.val()) === m ? h.attr("data-step", "complete").html(d.btnLastStepHtml) : h.attr("data-step", n).html(d.btnNextHtml), d.disableNextButton && h.attr("disabled", "disabled"), c.find("[data-step=" + k + "]").not(c.find(".js-btn-step")).addClass("hide"), c.find("[data-step=" + n + "]").not(c.find(".js-btn-step")).removeClass("hide"), parseInt(g.attr("data-step")) > 0 ? g.removeAttr("disabled") : g.attr("disabled", "disabled"), "previous" === j && h.removeAttr("disabled"), o = c.find("[data-step=" + n + "]"), o.attr("data-unlock-continue") && h.removeAttr("disabled"), p = o.attr("data-title"); var q = a("<span>").addClass("label label-success").html(n); i.html(q).append(" " + p), d.getTitleAndStep(o.attr("data-title"), n); var r = d.callbacks[e.val()]; f(l), f(r) }), this } }(jQuery); <div class="modal fade" id="order" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="js-title-step"></h4> </div> <div class="modal-body"> <form method="post" action="<?php echo base_url(); ?>pemesanan/submitorder"> <div class="row hide" data-step="1" data-title="Detail Pemesanan"> <div class="col-md-4"> <div class="form-group"> <label>Tanggal Pemesanan</label> <input type="date" class="form-control" name="tanggal_pemesanan" id="tanggal_pemesanan" value="<?php if (empty($this->session->userdata('tanggal_pemesanan'))){ echo date('Y-m-d'); } else { echo $this->session->userdata('tanggal_pemesanan'); } ?>" width="50%"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label>Closer</label> <select name="id_closer" id="id_closer" class="form-control selectpicker" data-live-search="true"> <option value="">Pilih Closer</option> <?php foreach($listcloser->result() as $closer) { ?> <option value="<?php echo $closer->id_closer; ?>" <?php if ($this->session->userdata('id_closer') == $closer->id_closer ) { echo "selected"; } ?>><?php echo $closer->nama_closer; ?></option> <?php } ?> </select> </div> </div> <div class="col-md-4"> <div class="form-group"> <label>Pelayanan</label> <input type="text" name="pelayanan" class="form-control" id="pelayanan" placeholder="Pelayanan" value="<?php echo $this->session->userdata('pelayanan'); ?>"> </div> </div> </div> <div class="row hide" data-step="2" data-title="Data Customer"> <div class="col-md-6"> <input type="hidden" name="halaman" value="pemesanan"> <label>Input Customer Baru</label> <div class="form-group"> <input type="text" class="form-control" placeholder="Nama Customer" name="nama_customer" id="nama_customer"> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="No. HP/WA" name="nohp_wa" id="nohp_wa"> </div> <div class="form-group"> <div class="form-group"> <input maxlength="100" type="text" id="sumber_informasi" class="form-control" placeholder="Sumber Informasi" /> </div> </div> <div class="form-group"> <label for="">Atau</label><br> <select class="form-control selectpicker" data-live-search="true"> <option value="">Yang sudah ada</option> <?php foreach($listcustomers->result_array() as $cs) { $pilih=''; if($cs['id_customer']==$this->session->userdata("id_customer")) { $pilih='selected="selected"'; ?> <option value="<?php echo $cs['id_customer']; ?>" <?php echo $pilih; ?>><?php echo $cs['nama_customer']; ?></option> <?php } else { ?> <option value="<?php echo $cs['id_customer']; ?>"><?php echo $cs['nama_customer']; ?></option> <?php } } ?> </select> </div> </div> <div class="col-md-6"> <label>Input Data Anak</label> <div class="form-group"> <input maxlength="100" type="text" id="nama_anak" required="required" class="form-control" placeholder="Nama Anak" /> </div> <div class="form-group"> <select id="jenis_kelamin" class="form-control" required="required"> <option value="">Pilih Jenis Kelamin</option> <option value="Laki-laki">Laki-laki</option> <option value="Perempuan">Perempuan</option> </select> </div> <div class="form-group"> <input maxlength="100" type="date" id="tanggal_lahir" max="<?php echo date('Y-m-d'); ?>" class="form-control" /> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="Nama Ayah" name="nama_ayah" id="nama_ayah"> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="Nama Ibu" name="nama_ibu" id="nama_ayah"> </div> <div class="form-group"> <input maxlength="100" type="text" id="lahir_di" class="form-control" placeholder="Dilahirkan di" /> </div> </div> <!-- total tagihan --> <!-- <div class="col-md-6"> <div class="form-group"> <label>Total Tagihan</label> <span class="pull-right"><h1><?php echo $this->session->userdata('total') ?></h1></span> </div> </div>--> <!-- end--> </div> <div class="row hide" data-step="3" data-title="Pesanan Hewan"> <div class="col-md-3"> <h3>Data Hewan</h3> <div class="form-group"> <label>Tipe Hewan</label> <select onchange="hitungpaketaqiqahsatuan()" class="form-control" style="width: 100%;" name="id_paketaqiqah" id="id_paketaqiqah" required> <option value="">Pilih Tipe Hewan</option> <?php foreach($listpaketaqiqah->result_array() as $pa) { ?> <option value="<?php echo $pa['id_paketaqiqah']; ?>"><?php echo $pa['tipe_hewan']; ?></option> <?php } ?> </select> </div> <div class="form-group"> <label>Pilih Kandang</label> <select onchange="" class="form-control" style="width: 100%;" name="id_kandang" id="id_kandang" required> <option value="">Pilih Kandang</option> <?php foreach($listkandang->result() as $kandang) { ?> <option value="<?php echo $kandang->id_lembaga; ?>"><?php echo $kandang->nama_lembaga; ?></option> <?php } ?> </select> </div> <div class="form-group"> <label>Tanggal Pemotongan</label> <input type="date" min="<?php echo $this->session->userdata('tanggal_pemesanan');//date_format(date_add(date_create($this->session->userdata('tanggal_pemesanan')), date_interval_create_from_date_string('1 days')), 'Y-m-d'); ?>" class="form-control pemotongan" name="tanggal_potong" id="tanggal_potong" required > </div> <div class="form-group"> <label>Jam Pemotongan</label> <div class="row"> <div class="col-md-6"> <input type="time" class="form-control pemotongan" name="jam_potong1" id="jam_potong1" required> </div> <div class="col-md-6"> <input type="time" class="form-control pemotongan" name="jam_potong2" id="jam_potong2" required> </div> </div> </div> </div> <div class="col-md-3"> <h3>&nbsp;</h3> <div class="form-group"> <label>Disaksikan/Tidak</label> <select class="form-control pemotongan" style="width: 100%;" name="disaksikan_tidak" id="disaksikan_tidak" required > <option value="Disaksikan">Disaksikan</option> <option value="Tidak disaksikan">Tidak disaksikan</option> </select> </div> <div class="form-group"> <label>Catatan untuk kandang</label> <textarea class="form-control" rows="4" placeholder="Catatan untuk kandang" name="catatan_untuk_kandang" id="catatan_untuk_kandang"></textarea> </div> <div class="form-group"> <label>Jumlah</label> <input onchange="hitungpaketaqiqahsatuan()" type="number" class="form-control" placeholder="Jumlah" name="jumlah_paketaqiqah" id="jumlah_paketaqiqah" min="1" value="1" required> </div> </div> <div class="col-md-3"> <h3>Paket Nasi Boks</h3> <div class="form-group"> <label for="">Pilih Paket</label> <select onchange="hitungpaketnasiboxsatuan()" class="form-control chosen-select" style="width: 100%;" name="id_paketnasibox" id="id_paketnasibox" required> <option value="">Pilih</option> <?php foreach($listpaketnasibox->result() as $pn) { ?> <option value="<?php echo $pn->id_paketnasibox; ?>"><?php echo $pn->nama_paketnasibox; ?></option> <?php } ?> </select> </div> <div class="form-group"> <label>Jumlah</label> <input onchange="hitungpaketaqiqahsatuan()" type="number" class="form-control" placeholder="Jumlah" name="jumlah_paketaqiqah" id="jumlah_paketaqiqah" min="1" value="1" required> </div> </div> <div class="col-md-6"> <div class="form-group"> <label>Catatan untuk dapur</label> <textarea class="form-control" rows="4" placeholder="Catatan untuk dapur" name="catatan_untuk_dapur" id="catatan_untuk_dapur"></textarea> </div> </div> <!--<div class="pull-right"> <div class="form-group"> <label style="margin-right: 10px">Total Tagihan</label> <span class="" style="margin-right: 10px"><h1>Rp.0</h1></span> </div> </div> --> </div> <div class="row hide" data-step="4" data-title="Pengantaran"> <div class="col-md-6"> <label> Input Data Pengiriman</label> <div class="form-group"> <textarea class="form-control" placeholder="Alamat" name="alamat" id="alamat"></textarea> </div> <div class="form-group"> <label >Input URL Gmaps</label> <input type="text" name="urlmaps" class="form-control"> </div> <div class="form-group"> <label>Tanggal Pengiriman</label> <input type="date" name="tanggal_kirim" class="form-control" min="<?php echo date_format(date_add(date_create($this->session->userdata('tanggal_pemesanan')), date_interval_create_from_date_string('1 days')), 'Y-m-d'); ?>" required> </div> <div class="col-md-6"> <div class="form-group"> <label>Jam Kirim</label> <input type="time" name="jam_kirim" class="form-control" required> </div> </div> <div class="col-md-6"> <div class="form-group"> <label>Jam Sampai</label> <input type="time" name="jam_sampai" class="form-control" required> </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label>Tarif / Ongkos</label> <input type="number" name="ongkos" class="form-control" min="0"> </div> <div class="form-group"> <label>Petugas Pengantaran</label> <?php foreach ($listdelivery->result() as $ld) { ?> <div class="input-group"> <span class="input-group-addon"> <input type="radio" class="radiopetugaspengantaran" name="petugas_pengantaran" value="<?php echo $ld->id_lembaga;?>"> </span> <input type="text" class="form-control" value="<?php echo $ld->nama_lembaga;?>" readonly> <?php } ?> </div> <div class="input-group"> <span class="input-group-addon"> <input type="radio" class="radiopetugaspengantaran" name="petugas_pengantaran" value="Lainnya"> </span> <input type="text" class="form-control" id="petugas_pengantaran" name="petugas_pengantaran_teks" value="Lainnya" disabled> </div> </div> <!--<div class="form-group"> <label>Total Tagihan</label> <span class="pull-right"><h1>Rp. 0</h1></span> </div>--> </div> </div> <div class="row hide" data-step="5" data-title="Pembayaran dan Tagihan"> <div class="col-md-6"> <div class="form-group"> <label>Diskon</label> <input type="number" min="0" onkeyup="hitungtotaldansisa()" onchange="hitungtotaldansisa()" class="form-control" placeholder="Diskon" name="diskon" id="diskon" value="<?php echo $this->session->userdata('diskon'); ?>"> </div> <div class="form-group"> <label>DP</label> <input type="number" min="0" onkeyup="hitungtotaldansisa()" onchange="hitungtotaldansisa()" class="form-control" placeholder="DP" id="dp" name="dp" value="<?php echo $this->session->userdata('dp'); ?>"> </div> <div class="form-group"> <label>Mekanisme Pembayaran</label> <select class="form-control" id="mekanisme_pembayaran" name="mekanisme_pembayaran"> <option value="TUNAI" <?php if ($this->session->userdata('mekanisme_pembayaran') == "TUNAI" ) { echo "selected"; } ?>>Tunai</option> <option value="TRANSFER" <?php if ($this->session->userdata('mekanisme_pembayaran') == "TRANSFER" ) { echo "selected"; } ?>>Transfer</option> </select> </div> </div> <div class="col-md-6"> <div class="form-group"> <label>Sisa</label> <span class="pull-right"><h2>Rp. 0</h2></span> </div> </div> <div class="col-md-6"> <div class="form-group"> <label>Total Tagihan</label> <span class="pull-right"><h2>Rp. 0</h2></span> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default js-btn-step pull-left" data-orientation="cancel" data-dismiss="modal"></button> <button type="button" class="btn btn-warning js-btn-step" data-orientation="previous"></button> <button type="button" class="btn btn-success js-btn-step" data-orientation="next"></button> </div> </form> </div> </div> </div> A: You can add one more button below the next button. Keep that button hidden till you reach the last step. When you reach the last step make it visible and on click of it write the logic to process your data.
{ "language": "en", "url": "https://stackoverflow.com/questions/59854485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the use of software watchdog in a controller? Heyya, I would like to what is the use of Software Watchdog and why they are used in controllers please.. A: Assuming you mean micro-controllers: A watchdog timer (sometimes called a computer operating properly or COP timer, or simply a watchdog) is an electronic timer that is used to detect and recover from computer malfunctions. Source
{ "language": "en", "url": "https://stackoverflow.com/questions/45885834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to share same instance of domain model in Angular2, and propagate changes? So i have a very simple domain model Shell : import {Injectable} from 'angular2/core'; @Injectable() export class Shell { public loggedIn: boolean = false; Change(item : boolean) { this.loggedIn = item; } } I have an AppComponent which hold this property: @Component({ selector: 'my-app', providers: [TemplateRef], templateUrl: './angular/app/Index.html', directives: [ROUTER_DIRECTIVES, NgIf], viewProviders: [Shell] }) export class AppComponent { public Shell: Shell constructor( @Inject(Shell) _shell: any) { this.Shell = _shell; } } and short piece of index view : <div *ngIf="Shell.loggedIn"> LOGGED IN! </div> and i have a registerview which wants to change loggedin status on successful registration: @Component({ templateUrl: './Angular/app/Html/Account/Register.html', directives: [ROUTER_DIRECTIVES], providers: [AccountService], viewProviders: [Shell] }) export class RegisterView { registerForm: any; public Shell: Shell model = new RegisterVM(); constructor(private _formBuilder: FormBuilder, private _http: Http, private _accountSerivce: AccountService, @Inject(Shell) _shell: any) { this.Shell = _shell } onSubmit(event: any) { this.Shell.Change(true) } As you can see i attempted to make use of dependency injection, but every single time Shell is returned as a new object. Do i really need to make Shell singleton? or are there any other ways? I am very new to angular2 so i might have overseen some very basic things, please correct me if i messed up anywhere. A: For this you need to add your Shell service when bootstrapping your application: bootstrap(AppComponent, [ Shell ]); And remove it from all viewProviders attribute of your components: @Component({ selector: 'my-app', providers: [TemplateRef], templateUrl: './angular/app/Index.html', directives: [ROUTER_DIRECTIVES, NgIf], // viewProviders: [Shell] <------- }) It's because of the way the "hierarchical injectors" feature of Angular2 works. For more details you could have a look at this question: * *What's the best way to inject one service into another in angular 2 (Beta)? A: Indeed you need to make Shell a singleton. You have to add the service in your bootstrap method as a provider.
{ "language": "en", "url": "https://stackoverflow.com/questions/36271916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom device to be emulated in chrome device emulator I am building a mobile webapp for a 10.1 inch screen tablet with 1900x1200 resolution. The device is an HP Elitepad 1000 I would like to know how to set chrome to emulate the specifications above. A: Just press ALT + CMD + I and the Dev.Tools will open. With SHIFT + CMD + M you switch to the device-emulator. At "Screen" fill in your resolution. Reload the page for best results.
{ "language": "en", "url": "https://stackoverflow.com/questions/33518199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring - Using property-placeholder to load properties file that is outside the war file or the classpath but is in the filesystem I have configured the loading of the properties file as shown below (Spring 3.1) my-spring-xml <context:component-scan base-package="com.mypackage"/> <context:property-placeholder location="file:///C:/temp/application.properties"/> web.xml <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/my-spring-xml </param-value> </context-param> application.properties expirationOffset = 777 In my java class i have declared the property as follows: private @Value("${expirationOffset}") String propertyValue; For some reason the value is not being initialised. When i run the following statement: System.out.println("VALUE - " + propertyValue); The output is always 16:03:02,355 INFO [stdout] (http--127.0.0.1-8080-1) VALUE - ${expirationOffset} I have tried to move the properties file in to the war file to try and access it while it is in the classpath but still the same problem. Here is how i access it from the classpath. <context:property-placeholder location="classpath:/conf/application.properties"/> Ideally i would like to keep the properties file outside the war file as i would not want to have to rebuild the war file because of a simple property change. Have i missed something? Edit I removed the msm-spring.xml initialisation paramters from this context: <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/my-spring-xml </param-value> </context-param> and moved it to the servlet context as shown below. <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>myservice</servlet-name> <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/my-spring-xml </param-value> </init-param> </servlet> The above change seems to have fixed as i am now getting the correct value. I thought the way i had originally was that i had it on the application context meaning that it will be available throughout the application/webapp. What is the difference in having the msm-spring in the either of 3 i have listed above? A: This is a bit of speculation based on the information you have provided: You probably don't have the <context:property-placeholder.. in your Root Web Application context - the one loaded by ContextLoaderListener, instead you may be having it in the web context(loaded by Dispatcher servlet). Can you please confirm this. Update: Based on the comment, the issue seems to have been that the <context:propert-placeholder.. was defined in the Root Web application context, but being referred to in a component from Web Context. The fix is to move the propertyplaceholder to the web context (one defined through MessageDispatcherServlet) in this case. A: EDIT : Did you try using setter method with #{expirationOffset} ?? i.e. : private String propertyValue; @Value("#{expirationOffset}") public void setPropertyValue(String property) { propertyValue = property; } Another Option : Add Properties bean instead of PropertyPlaceConfigurer like this : <util:properties id="myProps" location="file:///C:/temp/application.properties" /> OR <util:properties id="myProps" location="classpath:application.properties" /> And Replace Setter with a slight modification as private String propertyValue; @Value("#{myProps.expirationOffset}") public void setPropertyValue(String property) { propertyValue = property; } You'll have to add xmlns:util="http://www.springframework.org/schema/util" to xmlns decalrations and correcsponding http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd to xsi:schemalocation in your context configuration xml. This should definitely work.! Hope it Helps. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/11141193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to develop gtalk plugin? I want to develop a simple plugin for gtalk is this possible? Is there api's or tutorial that shows how to do that? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/3611548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Seam App accessing data via an EJB I have to investigate the possibility of using JBoss and Seam to build user interfaces to data held in a database controlled by an off-the-shelf package. I've been reading through some of the Seam documentation, and various other sources, but I can't seem to clear the confusion I'm currently suffering from. My problem is that everything I've read so far talks about using JPA/Hibernate to access and persist data directly in a database schema, but the package I'm working with doesn't allow (or actively discourages) direct updates to any schema that it controls. It does however present what looks like a comprehensive data-access API delivered as an EJB. With the basic assumption that it's entirely possible, my question is how would I go about building a Seam app that uses this EJB for all data access? Is it a simple thing or am I heading for a whole heap of pain? Can anyone point me in the direction of reading material that will help me? Apologies in advance for the newbie nature of this question, but I've been dropped in at the deep end on this and I'm struggling to pick up so much new knowledge. Any help will be very gratefully received. Many thanks Steve A: Seam is mainly an inversion of control (IoC) container that provides a lot of boilerplate functionality for web development. It has no real hard requirements for you to use JPA/Hibernate. It's just that the most usual scenario for Java web development is a database backend that's mapped by an ORM, of which JPA/Hibernate is probably the de-facto standard. If your data access layer (DAL) does not exist or is just wrapper around an existing API (web services, REST, etc.), Seam will also handle that scenario very easily and provide you with all its remaining functionality (session management, JSF integration, security, navigation flow management and lots more). In essence, a simple component (or set of) that exposes the API you mention and handles its state should be enough. Then again, I do not know your requirements, so I can't say that for sure. A more complex example is the Seam Social module in Seam 3. It uses Twitter, Facebook or other social web APIs to connect to those services and inject them into Seam's contexts', so that your application can leverage their functionality. I don't know if your scenario is so complex that it would require you to build an entire CDI module from scratch (as Seam Social does) but take a look at their documentation. It might give you some ideas on what further investigate.
{ "language": "en", "url": "https://stackoverflow.com/questions/11742026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Double integration with a differentiation inside in R I need to integrate the following function where there is a differentiation term inside. Unfortunately, that term is not easily differentiable. Is this possible to do something like numerical integration to evaluate this in R? You can assume 30,50,0.5,1,50,30 for l, tau, a, b, F and P respectively. UPDATE: What I tried InnerFunc4 <- function(t,x){digamma(gamma(a*t*(LF-LP)*b)/gamma(a*t))*(x-t)} InnerIntegral4 <- Vectorize(function(x) { integrate(InnerFunc4, 1, x, x = x)$value}) integrate(InnerIntegral4, 30, 80)$value It shows the following error: Error in integrate(InnerFunc4, 1, x, x = x) : non-finite function value UPDATE2: InnerFunc4 <- function(t,L){digamma(gamma(a*t*(LF-LP)*b)/gamma(a*t))*(L-t)} t_lower_bound = 0 t_upper_bound = 30 L_lower_bound = 30 L_upper_bound = 80 step_size = 0.5 integral = 0 t <- t_lower_bound + 0.5*step_size while (t < t_upper_bound){ L = L_lower_bound + 0.5*step_size while (L < L_upper_bound){ volume = InnerFunc4(t,L)*step_size**2 integral = integral + volume L = L + step_size } t = t + step_size } A: Since It seems that your problem is only the derivative, you can get rid of it by means of partial integration: Edit Not applicable solution for lower integration bound 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/73135559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What kind of language should I design for a particle engine scriptable engine? I was wondering which kind of expressiveness fits a language used to generate particle effects.. Supposing to want an engine as flexible as possible what kind of 'features' should it have? (in addition to trivial ones like color, position, velocity, acceleration) A: Don't try and design a new language just for your application, instead embed another, well-established language in there. Take a look at the mess it has caused for other applications trying to implement their own scripting language (mIRC is a good example). It will mean users will have to learn another language just to script your application. Also, if you design your own language it will probably end up not as useful as other languages. Don't try to reinvent the wheel. You might want to look at Lua as it is light-weight, popular, well-established, and is designed to be used by games (users of it include EA, Blizzard, Garry's Mod, etc.), and has a very minimal core library (it is designed to be a modular language). A: SO everybody's urging you not to reinvent the wheel and that's a great idea, I have a soft spot for Python (which would allow your scripting users to also install and use plenty of other useful math libs &c), but LUA's no doubt even easier to integrate (and other scripting languages such as Ruby would also no doubt be just fine). Not writing your own ad-hoc scripting language is excellent advice. But reading your question suggests to me that your issue is more about -- what attributes of the objects of my engine (and what objects -- particles, sure, but, what else besides) should I expose to whatever scripting language I ember (or, say via MS COM or .NET, to whatever scripting or non-scripting language my users prefer)? Specific properties of each particle such as those you list are no doubt worthwhile. Do you have anything else in your engine besides point-like particles, such as, say, surfaces and other non-pointlike entities, off which particles might bounce? What about "forces" of attraction or repulsion? Might your particles have angular momentum / spin? A great idea would be to make your particles' properties "expando", to use a popular term (other object models express the same idea differently) -- depending on the app using your engine, other programmers may decide to add to particles whatever properties they need... maybe mass, say -- maybe electric charge -- maybe cost in eurocents, for all you know or care;-). This makes life easier for your users compared to just offering a "particle ID" (which you should anyway of course;-) for them to use in hash tables or the like to keep track of the specific attributes they care about! Allowing them to add "methods" and "triggers" (methods that you call automatically if and when certain conditions hold, e.g. two particles get closer than a certain distance) would be awesome, but maybe a bit harder. Don't forget, BTW, to allow a good method to "snapshot" the current state of the particle system (INCLUDING user-added expando properties) to a named stream or file and restore from such a snapshot -- that's absolutely crucial in many uses. Going beyond specific particles (and possibly other objects such as surfaces if you have them) you should probably have a "global environment" with its own properties (including expando ones) and ideally methods and triggers too. E.g., a force field acting on all particles depending on their position (and maybe their charge, mass, etc...!-)... Hope some of these ideas strike you as interesting -- hard for me to tell, with little idea of your intended field of application!-) A: Just embed Lua. It's a great language design, excellent performance, widely used by game developers, and small enough that you can master it in a few days. Then you can get on with your game design.
{ "language": "en", "url": "https://stackoverflow.com/questions/1077563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Share Maven repository ***only one user connected at a time*** We have a bank of virtual machines used by developers to make changes and perform tests of a large suite of projects using Maven for dependency management. Each user has a unique login, so their local .m2/repository folders are separate from one another. I have read that sharing maven repositories is a bad idea due to lack of thread-safety and general lack of concurrent access support. My question is, is there a reason not to share local maven "repository" folders when only one user at a time will be using them? The limitation is a limitation of the host operating system - it is not possible for two users to log in to these machines simultaneously.
{ "language": "en", "url": "https://stackoverflow.com/questions/32315796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to adjustsFontSizeToFitWidth to UIButton label ? ios when i set adjustsFontSizeToFitWidth to the button UILabel, the text go out side of the button frame, I don't know why ? here is my code: shareBtn = UIButton() shareBtn.setTitle(IconsConstants.share, forState: UIControlState.Normal) shareBtn.titleLabel?.font = UIFont.iconmoonFont(100) shareBtn.titleLabel?.adjustsFontSizeToFitWidth = true; shareBtn.contentVerticalAlignment = UIControlContentVerticalAlignment.Center shareBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center //EdgeInsets shareBtn.contentEdgeInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10) and here is the result: A: for single line set shareBtn.titleLabel?.adjustsFontSizeToFitWidth = YES; instead of this factLabel.adjustsFontSizeToFitWidth = true; for multiple line us use actLabel.numberOfLines = 0; factLabel.lineBreakMode = NSLineBreakByWordWrapping; CGSize maximumLabelSize = CGSizeMake(factLabel.frame.size.width, CGFLOAT_MAX); CGSize expectSize = [factLabel sizeThatFits:maximumLabelSize]; factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, expectSize.width, expectSize.height);
{ "language": "en", "url": "https://stackoverflow.com/questions/34896858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do i change the clicked button Currently i have 3 buttons with names start_btn , about_btn and stats_btn which are movieClips.All 3 of them are in a container (also a movieClip) with the name of group_btn.So my question is how do i tell the exact element to change its ScaleX and ScaleY when im using only one MouseEventListener for all 3 of them. I did figure that ill have to detect which one is clicked but then ,after that i dont know what to do . so i have this code so far : private function onAddedToStage(eve:Event):void { trace("we are good to go"); this.group_btn.start_btn.addEventListener(MouseEvent.MOUSE_OVER, makeButtonBigger) this.group_btn.start_btn.addEventListener(MouseEvent.MOUSE_OUT, makeButtonSmaller) this.group_btn.about_btn.addEventListener(MouseEvent.MOUSE_OVER, makeButtonBigger) this.group_btn.about_btn.addEventListener(MouseEvent.MOUSE_OUT, makeButtonSmaller) this.group_btn.stats_btn.addEventListener(MouseEvent.MOUSE_OVER, makeButtonBigger) this.group_btn.start_btn.addEventListener(MouseEvent.MOUSE_OUT, makeButtonSmaller) } private function makeButtonBigger(ev:MouseEvent):void{ var nameOfButton:String = ev.currentTarget.name; //this.group_btn.nameOfButton.scaleX = 1.2 <--- doesnt work trace(nameOfButton) } A: You need to access the property using square brackets; the way you have it is implying that there's a button that's literally called 'nameOfButton', which is why it's failing. Try the following: private function makeButtonBigger(ev:MouseEvent):void{ var nameOfButton:String = ev.currentTarget.name; this.group_btn[nameOfButton].scaleX = 1.2; trace(nameOfButton); } That will use the actual captured string, rather than the variable name itself. Although, you can also access the button directly from the event's currentTarget property: private function makeButtonBigger(ev:MouseEvent):void{ ev.currentTarget.scaleX = 1.2; }
{ "language": "en", "url": "https://stackoverflow.com/questions/18748549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call loadmore function(only once) on scroll down javascript function? i am using the following code to trigger my onloadmore funciton when user scroll down and reaches bottom of page. But i notice that many times the function get called multiple times on scroll down! could any one tell me why loadmore function get called more then once for same set of data! is it internet connection problem ? I just want loadmore called only once! <script> var nextTagId = null; function callLoadMore() { $.ajax({ type: "GET", dataType: "jsonp", cache: false, url: "http://api.sometime.com/api.php?count=100" + ( nextTagId ? "&next_id=" + nextTagId : ""), success: function(data) { for (var i = 0; i < 100; i++) { document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].pics.standard.path+'\n' ; } } }); } </script> <script> $(function() { $(window).bind("scroll", function (){ console.log("SCROLL : " + $(window).scrollTop() + " - " + $(window).innerHeight() + " - " + document.body.clientHeight); if ($(window).scrollTop() + document.body.clientHeight >= $(window).innerHeight()) { //alert('Bottom!'); callLoadMore(); } }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/30830282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to plot ROC-AUC figures without using scikit-learn I have the following list containing multiple tuples of (TP, FP, FN): [(12, 0, 0), (5, 2, 2), (10, 0, 1), (7, 1, 1), (13, 0, 0), (7, 2, 2), (11, 0, 2)] each tuple represents the scores for a single image. This means I have 7 images and I have calculated the scores for a object detection task. Now I calculate precision and recall for each image(tuple) using the following function: def calculate_recall_precision(data): precisions_bundle = [] recalls_bundle = [] for tp, fp, fn in data: precision = tp / (tp + fp) recall = tp / (tp + fn) precisions_bundle.append(precision) recalls_bundle.append(recall) return (precisions_bundle, recalls_bundle) This function returns a tuple which contains two lists. The first one is precision values for each image and the second one is recall values for each image. Now my main goal is to plot ROC and AUC curves using only matplotlib. Please note that I do not want to use scikit-learn library. A: You can simply use matplotlib.pyplot.plot method. For example: import numpy as np import matplotlib.pyplot as plt def plot_PR(precision_bundle, recall_bundle, save_path:Path=None): line = plt.plot(recall_bundle, precision_bundle, linewidth=2, markersize=6) line = plt.title('Precision/Recall curve', size =18, weight='bold') line = plt.ylabel('Precision', size=15) line = plt.xlabel('Recall', size=15 ) random_classifier_line_x = np.linspace(0, 1, 10) random_classifier_line_y = np.linspace(1, 0, 10) _ = plt.plot(random_classifier_line_x, random_classifier_line_y, color='firebrick', linestyle='--') if save_path: outname = save_path / 'PR_curve_thresh_opt.png' _ = plt.savefig(outname, dpi = 100, bbox_inches='tight' ) return line and then just use it as plot_PR(precision_bundle, recall_bundle). Note: here I also added a dashed line for a random classifier and the possibility to save the figure in case you want to
{ "language": "en", "url": "https://stackoverflow.com/questions/68951426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Avoid adding NSWindowWillEnterFullScreenNotification in OS version prior Lion(On Leopard or Snow Leopard) How can I avoid adding NSWindowWillEnterFullScreenNotification in OS version prior to 10.7 because it is only available in OS 10.7 or above and I want to use this notification in above 10.7 but my application got crashed if I run it on prior OS version. I have check the crash log and it was saying that Symbol not found NSWindowWillEnterFullScreenNotification Right now I am checking the OS version using this if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_5) { /* On a 10.5.x or earlier system */ } else if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_6) { /* On a 10.6 - 10.6.x system */ } else { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterFull:) name:NSWindowWillEnterFullScreenNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didExitFull:) name:NSWindowDidExitFullScreenNotification object:nil]; } But app got crashed in prior version as soon as it get launched. Here is the crash log although I have change the app name to XYZ in the log due to NDA Process: XYZ [53319] Path: /Applications/XYZ.app/Contents/MacOS/XYZ Identifier: com.XYZ.XYZ Version: 2.0.5 (2.0.5) Code Type: X86 (Native) Parent Process: launchd [224] Date/Time: 2012-10-28 07:44:11.717 -0500 OS Version: Mac OS X 10.6.8 (10K549) Report Version: 6 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000002, 0x0000000000000000 Crashed Thread: 0 Dyld Error Message: Symbol not found: _NSWindowDidExitFullScreenNotification Referenced from: /Applications/XYZ.app/Contents/MacOS/XYZ Expected in: /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit in /Applications/XYZ.app/Contents/MacOS/XYZ A: Here's what I think happens. The crash happens already in the linker, because it expects NSWindowDidExitFullScreenNotification to exist, but it doesn't in older versions of os x. I haven't got any experience in this. The solutions seem to be kind of hacky. Have a look at this question, where someone has an almost exact same question: How to build a backwards compatible OS X app, when a new API is present?
{ "language": "en", "url": "https://stackoverflow.com/questions/13267714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error - "Cannot invoke "org.openqa.selenium.WebElement.sendKeys(java.lang.CharSequence[])" because "this.UserName" is null I am a newbie in Java and Selenium. Below are my java classes for POM, Driver Utilites and Test Case. When I run the Test Case as TestNG test, I have : FAILED: verifyLogin java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebElement.sendKeys(java.lang.CharSequence[])" because "this.userName" is null. Please help me out. Let me know if further info is needed. Thanks in advance. <----------------------------------------POM--------------------------------------------------> package com.inetBankingV1.pageObjects; import org.openqa.selenium.WebDriver; import com.inetBankingV1.utilities.callBrowserDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; public class LoginPage { WebDriver driver; @FindBy(how=How.LINK_TEXT, using="Log in") WebElement logUser; @FindBy(how=How.NAME, using="username") WebElement userName; @FindBy(how=How.NAME, using="password") WebElement passWord; //constructor public LoginPage(WebDriver driver) { this.driver=driver; } public void loginCheck(String uname,String passwd) { userName.sendKeys(uname); passWord.sendKeys(passwd); logUser.click(); } } <----------------------------------------Driver------------------------------------------------> package com.inetBankingV1.utilities; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.remote.DesiredCapabilities; public class callBrowserDriver { public WebDriver startApplication(String browser, String baseURL, WebDriver driver) { if(browser.equalsIgnoreCase("firefox")) { System.setProperty("webdriver.gecko.driver", "./Drivers/geckodriver.exe"); FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.setCapability("marionette", true); driver = new FirefoxDriver(firefoxOptions); } if(browser.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe"); driver=new ChromeDriver(); } driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.navigate().to(baseURL); return driver; } } <--------------------------------------Test Case-----------------------------------------------> package com.inetBankingV1.testCases; import com.inetBankingV1.utilities.callBrowserDriver; import org.openqa.selenium.WebDriver; import org.testng.annotations.Test; import com.inetBankingV1.pageObjects.LoginPage; public class TC2_VerifyLogin { WebDriver driver; callBrowserDriver browserDriver=new callBrowserDriver(); @Test public void verifyLogin() { driver=browserDriver.startApplication("chrome","https://demosite.com/",this.driver); LoginPage login=new LoginPage(driver); login.loginCheck("admin","Password"); } } A: See if this works:- @FindBy(how=How.ID, using="inline-search-submit") WebElement logUser; @FindBy(how=How.NAME, using="user") WebElement userName; @FindBy(how=How.NAME, using="pass") WebElement passWord; A: The issue is resolved after initialising the webelements of the POM class using initElements: LoginPage login=PageFactory.initElements(driver, LoginPage.class); A: Use below line in your constructor PageFactory.initElements( driver, this); ---------------------------------------------- public LoginPage(WebDriver driver) { this.driver=driver; PageFactory.initElements( driver, this); } This should solve your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/67957566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display message if user clicks on browser button? My question is it possible to display a message if browser buttons have been pressed in order to be able to display a message stating if user should leave the page or stay on a page? Also can a message be displayed if user tries to change a url if they are on a certain page? Thanks A: * *Server side is needed for foolproofing this. On the server, when assessment is started, you should first have start screen URL. You must program it so that once assessment is started (after clicking start), it goes to the exam URL, and your assessment is always saved - when user goes back, using server side tricks have it so that instead of showing the start screen, it redirects back to the correct page (in a way that still maintains history), shows the exam with the data still in it, and pops up the warning not to click back button. Then, if user does it again, it does the same thing, again. *You have to have it so the exam is saved all the time. unload javascript event can be used to notify via alert() that they shouldn't be leaving the exam, and thats about all. onbeforeunload event can be used to try to give them the choice to stay, but shouldn't be depended on as it doesn't work on every browser. A: Use onbeforeunload as suggested in a comment. There are various example, like this one: https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm If you want to call out the buttons that the user must click, you will need to do some browser detection, as most browsers have OK/Cancel buttons on the window that they display, but Chrome has "Leave this page" and "Stay on this page".
{ "language": "en", "url": "https://stackoverflow.com/questions/14187850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TCP Server Applet I have an open Social container and I need to put an applet in that container, the applet is required to act as a tcpServer, I need some guidence how can I do this? A: The networking tutorial explains, in full detail, how to create a TCP server socket and accept connections from it. Here's the gist of it: ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } // now get the input and output streams from the client socket // and use them to read and write to the TCP connection clientSocket.close(); serverSocket.close();
{ "language": "en", "url": "https://stackoverflow.com/questions/14745318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get Current balance of each user from a bunch of transactions in MongoDB using NodeJS? Im using Node.js with Mongoose to Store data in MongoDB. I need to show a list of all the users with their current available balance. I tried using multiple for loops, but I kept getting errors somewhere or the other. I'm able to show the list of unique users, but summation of their balance is incorrect. I felt I was doing it the wrong way. Could someone suggest a good way to get my required output with lesser and pretty code? Current Data in My Database: ID Name Amount Credit 1 Andy 500 true 2 Andy 1000 false 3 Tina 400 false 4 John 700 true 5 Tina 2000 true 6 Andy 100 true 7 Tina 200 false 8 John 300 false Required Final Output ID Name Balance 1 Andy -400 2 Tina 1400 3 John 400 What I have tried till now: Accounts.find({}).exec(function (err, transList) { var finalArr= []; var currentAmount = 0; for(var i=0; i<transList.length; i++) { if(transList[i].status===true) // Credited { currentAmount = currentAmount + transList[i].amount; } else // Debited { currentAmount = currentAmount - transList[i].amount; } if(i===0) { } else if (i===transList.length-1) { var obj = {}; obj._id = transList[i]._id; obj.name = transList[i].name; obj.amount = currentAmount; finalArr.push(obj); } else { if(transList[i].student._id!=transList[i-1].student._id) { var obj = {}; obj._id = transList[i-1]._id; obj.name = transList[i-1].name; obj.amount = currentAmount; finalArr.push(obj); currentAmount = 0; } } } data = JSON.stringify({list:finalArr}); res.end(data); });
{ "language": "en", "url": "https://stackoverflow.com/questions/45375724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the testability problems of window in javascripts which is solved in $windows in Angular JS As a novice start to learn angular js and with a weak javascript background, could someone give some more illustrative examples and explain further what is the idea/purpose behind the $window, a built-in service in AngularJS? what is the below mentioned global problem for testing? Thanks Reading a book "AngularJS up and running", but do not understand its explanation: The $window service in AngularJS is nothing but a wrapper around the global window object. The sole reason for its existence is to avoid global state, especially in tests. Instead of directly working with the window object, we can ask for and work with $window. In the unit tests, the $window service can be easily mocked out (available for free with the AngularJS mocking library). and then visit official documentation of AngularJS: https://docs.angularjs.org/API/ng/service/$window A reference to the browser's window object. While the window is globally available in JavaScript, it causes testability problems, because it is a global variable. In AngularJS we always refer to it through the $window service, so it may be overridden, removed or mocked for testing. Mark bold and italic for the concepts/words that I do not understand.
{ "language": "en", "url": "https://stackoverflow.com/questions/44611762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Function calls in smart contract from script and checking value of variables I am currently using Brownie to learn smart contract and blockchain development. I am having trouble understanding how to call functions and check value of variables from smart contracts using python script. How would I be able to do this? Below I have a contract DutchAuction where I have defined a function bid() which returns 'Hello world' just for testing purposes that I am trying to call. pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract DutchAuction { uint public startTime; uint public endTime; uint public price; uint public startPrice; address public assetOwner; constructor(uint _startPrice, uint _endTime) public { startTime = block.timestamp; price = _startPrice; startPrice = _startPrice; endTime = _endTime; assetOwner = msg.sender; } function bid() public returns (string calldata) { return 'hello world'; } } A: Change the string calldata to string memory in your bid() function returns statement. The string literal is loaded to memory (not to calldata) and then returned. If you wanted to return calldata, you'd need to pass the value as calldata first: function foo(string calldata _str) public pure returns (string calldata) { return _str; } Docs: https://docs.soliditylang.org/en/v0.8.10/types.html#data-location
{ "language": "en", "url": "https://stackoverflow.com/questions/70173962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Git - Weirdness when using .gitattributes to force consistent line endings So, I've recently added a .gitattributes file to one of our repositories to try to force consistent line endings: # All Perl Sources should use Unix style line endings *.pl text eol=lf *.pm text eol=lf But both myself and a lot of other developers are encountering a lot of "phantom changes" where git seems to detect the file as "changed" even though there's no change. Every line shows up as added, then deleted. I suspect it's getting confused about line endings (and thus detecting each line as changed), but what's weird here is: * *I can't reset the file (the reset is completed, but the file remains as an unstaged change) *Changing the line endings in the affected text file does not affect whether it shows up as a changed file. Has anyone encountered this before, and is there a way to avoid or resolve this issue? A: With Git 2.16 or more, do at least once: git add --renormalize . git commit -m "normalize eol files" git push Then try and clone your repo elsewhere, and check that git status behaves as expected. Make sure you don't have core.autocrlf set to true. git config core.autocrlf And you can test for your files eol style.
{ "language": "en", "url": "https://stackoverflow.com/questions/52637974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ios adding a collectionView inside UITableView's header view I've an UICollectionView inside the headerView of my UITableView which is made in other xib file (custom view) . So my question is, should I declare delegate methods on the same class I've declared my tableView or on the custom view which is header of tableView? Which is more convenient? A: Define the delegates of UITableView & UICollectionView in same controller, set there delegates to the same class as self.mytableview.delegate = self; self.mycollectionview.delegate = self; You can follow this tutorial, Putting a UICollectionView in a UITableViewCell
{ "language": "en", "url": "https://stackoverflow.com/questions/40713323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Subscript indices must either be real positive integers or logicals with interp2 What does the error "Subscript indices must either be real positive integers or logicals" means when using interp2. X,Y,Z,XI,YI are all vectors of the same length. A: It means that you trying to access an element in an array by using index as number with decimal point or a negative number, or maybe even using a string that looks like a number e.g. "2". The only way to access the elements is by using positive integer OR logical (0 or 1). array = [1 2 3 4 5 6]; array(4) # returns 4th element of the array, 4. mask = array > 3; # creates a mask of 0's and 1's (logicals). array(mask) # return elements greater than 3, 4 5 6. BUT you can't do: array(2.0) Or anything else other than positive integer or logical. Alex
{ "language": "en", "url": "https://stackoverflow.com/questions/3956011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Nokogiri to search through XML file based on user input in Rails app So I've got an XML file (XML file) with a schema (XML schema). I'm trying to create a quick Rails app to allow users to search through the XML file based on the 'lastName" element that are children of an sdnEntry element. I don't have any problems setting up the rails app, or the search-form. I was also able to get the XML file loaded using Nokogiri and can run simple commands like... xmldoc.css("lastName") ...to return a NodeSet with all the 'lastName' elements in them. Unfortunately, that's not good enough, since that lists not just the 'lastName' elements directly underneath an 'sdnEntry' element. Plus that doesn't even get me started to insert the user's input from the form. I was thinking something like this would work... xmldoc.xpath("/xmlns:sdnList/sdnEntry/lastName[text()='#{param[:name]}']") ...but that didn't work. Oddly, I couldn't even get... xmldoc.xpath("/xmlns:sdnList/sdnEntry/lastName") ...to work. I just don't know enough about Nokogiri or XPath or CSS queries for XML documents to figure out how to pass the param from user-input form to create the appropriate query that will return the right info for me. I tried looking through the Nokogiri Documentation and the W3Schools XPath Tutorial. No joy. I would really appreciate any pointers, code snippets or suggestions. Thank you. A: Your issue is with the XPath that Nokogiri is using. You need to specify what the namespace is in attributes. More info at the Nokogiri documentation. Here is an example for looking up an item, using your params will probably work as well. doc = Nokogiri::XML(File.read("sdn.xml")) doc.xpath("//sd:lastName[text()='INVERSIONES EL PROGRESO S.A.']", "sd"=>"http://tempuri.org/sdnList.xsd") >> [#<Nokogiri::XML::Element:0x80b35350 name="lastName" namespace=#<Nokogiri::XML::Namespace:0x80b44c4c href="http://tempuri.org/sdnList.xsd"> children=[#<Nokogiri::XML::Text:0x80b34e3c "INVERSIONES EL PROGRESO S.A.">]>] A: user_input = "CHOMBO" # However you are getting it doc = Nokogiri.XML(myxml,&:noblanks) # However you are getting it doc.remove_namespaces! # Simplify your life, if you're just reading # Find all sdnEntry elements with a lastName element with specific value sdnEntries = doc.xpath("/sdnList/sdnEntry[lastName[text()='#{user_input}']]") sdnEntries.each do |sdnEntry| p [ sdnEntry.at_xpath('uid/text()').content, # You can get a text node's contents sdnEntry.at_xpath('firstName').text # …or get an element's text ] end #=> ["7491", "Ignatius Morgan"] #=> ["9433", "Marian"] #=> ["9502", "Ever"] Instead of requiring the exact text value, you might also be interested in the XPath functions contains() or starts-with().
{ "language": "en", "url": "https://stackoverflow.com/questions/8017667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Copy 12MB folder with 2500 files from assets to sd card quickly I'm trying to copy a large number of folders and subfolders from my apk asset folder to my sd card quickly. the folders contain 12mb of small files, probably 2500 total. The code example from this SO question works but it takes over 5 minutes on my device. Is there a faster way to do this? I originally tried adding the folder to a zip archive and unzipping it after it was moved onto the device but it created to many problems on different devices and was failing a lot throughout the process. A: 12mb should save a bit faster that, if you are using the methods from the other SO question, try increasing the buffer size in copyFile like so, private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[8192]; // 1024 is kind small,..try 8192 or 4096!! int read; while((read = in.read(buffer)) != -1){ out.write(buffer, 0, read); } } A: I've had very good, consistent results with creating a zip file, putting it in raw or assets in my app, and unzipping it when the user first opens the app. I'd recommend you give it another shot, as I've been impressed that I've seen zero issues with hundreds of installs. The tutorials I based the helper methods to zip and unzip files are here: Unzipping Files w/ Android, and Zipping Files w/ Android It should be noted that I used the Java API to create the zip that I include with the install of my app. That might be why I had such consistent results unzipping them as well, using the Java API in Android. Hope this helps! Best of luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/17862901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using Emacs server and emacsclient on other machines as other users I know that after I call (start-server) inside an existing Emacs session I can then use emacsclient -c (on the same computer) to create new frames that connect into that server, so that each new frame created by emacsclient has access to the same set of shared state (e.g. buffers). Most of the documentation I've found focuses on the "give me fast access to my local Emacs" use case, and so there are two things that I haven't seen any details of yet: * *Can emacsclient -c access Emacs servers started by other users, or is it hard-wired to detect only sessions started by my own user? *Does Emacs server (directly or indirectly) support remote connections? That is, is there some way to set up Emacs (possibly involving SSH) that allows calls to emacsclient -c on remote machines to have access to the local state of my Emacs server? (In case you haven't already guessed, what I'd ultimately like to do is combine the two techniques above to provide rudimentary collaborative editing support.) This is a real-world problem, so here's what I'm working with: * *The necessary functionality should be built into Emacs already (23.3.1, 64-bit). I can stretch to Emacs extensions from the standard Ubuntu repositories, but I'd prefer not to. (Which I believe rules out Rudel, sadly.) *No new users or user spoofing. Solutions should work with the existing set of user accounts, and users must not pretend to be other users (e.g. via su or ssh). If it makes any difference, the machines are on a private LAN, have OpenSSH clients and servers installed (and running), and all users can connect to (their own account on) all machines, but they have no shared filesystem. So, does anybody know whether Emacs server can * *grant access to other users, or *provide remote access? EDIT As commented in rwb's answer, it's clear that the new windows being opened locally by running emacsclient -c are actually being created by the remote Emacs server process. That is, emacsclient is simply triggering the relevant behaviour in the server. This causes some issues with incorrect display settings, since the server does not normally have access to the local desktop (see below). However, I can now connect in to a remote Emacs session if I use the following sequence of commands: In one terminal, where 1.22.333.44 is the IP address of remotehost: ssh -t -X remotehost \ "emacs -nw --eval '(progn (setq server-host \"1.22.333.44\" server-use-tcp t) (server-start))'" Then in another (on the same machine): scp remotehost:.emacs.d/server/server /tmp/server-file DISPLAY=localhost:10 emacsclient -c -f /tmp/server-file The emacsclient command causes the remote Emacs server (which it finds details of in /tmp/server-file) to open up a graphical Emacs window (on the local display) that shares state with the Emacs session on the remote host. Since the remote Emacs server was started via ssh -X, SSH provides it with access to my local display via a "fake" :10 display. The DISPLAY=:10 passed to it (via emacsclient) thus causes a window to be opened on my local desktop. Although the approach above does tick the "Run Emacs server on remote machine, connect to it using emacsclient locally" box, it's very limited. In fact, it's not much different to running the server and clients all locally as a single user: the only difference is that the server is now remote, so has access to different system resources. Unfortunately, launching via ssh -X is the only way I've been able to successfully open a window on a different machine's X server: * *Specifying a basic DISPLAY=remote:0 gets nowhere (since Ubuntu X servers are started with the -nolisten tcp option). *Connecting via SSH and then using DISPLAY=:0 also fails, but this time only due to lack of suitable authentication credentials. (I believe that's the case, anyway: the error message cryptically says No protocol specified / Can't open display.) I think that finding a way around the second problem would probably get me a good deal closer to a solution. Having read the posts at http://comments.gmane.org/gmane.emacs.devel/103350 (starting at the '25 Oct 14:50' post, about half way down) I'm starting to wonder if this might be one of the rare things that Emacs cannot do (i.e. is impossible ;-) ). However, if anyone does have a way to provide access to remote X displays without the permissions error above, I'm still open to persuasion.... TL;DR As pointed out by rwb's answer, my questions above about whether Emacs can grant remote access have got things backwards. There's no real problem with Emacs granting access to other users (server-use-tcp and a suitable server-file take care of this): rather the problem is how to allow a process on one machine to open new X windows on other users' X displays (specifically, the Emacs running (start-server) needs to open windows for users who ask it to via emacsclient -c). That answer's beyond the scope of this question. Alternative solution As a workaround, we use the following: * *machine0: tmux -S /tmp/shared-tmux-socket new-session *machine1..machineN: ssh -t machine0 tmux -S /tmp/shared-tmux-socket attach with suitable file permissions on /tmp/shared-tmux-socket. Then we run a text-mode Emacs in the shared terminal. :-) This does raise some user-spoofing questions, but at least the host can see everything that the guests are doing. A: Aaron Gallagher implemented a solution: http://blog.habnab.it/blog/2013/06/25/emacsclient-and-tramp/ It works (AFAIU) like: * *emacs server is started with tcp *He opens a connection to a remote system with tramp-sh, opening a forward port ("back channel") *tramp-sh is advised to copy an extended auth cookie file to the remote system *On the remote system he calls a special emacsclient.sh shell script that emulates emacsclient but prefixes the file names with the corresponding tramp prefix that is found in the extended auth cookie I've added a comment to his blog post proposing this idea to be discussed and enhanced on emacs-devel. A: If you are doing this to enable people to remotely edit files you may want to look at 'tramp mode' http://emacswiki.org/emacs/TrampMode A: This should provide a starting point for what you want. From the info node (emacs) emacsclient Options `--server-file=SERVER-FILE' Specify a "server file" for connecting to an Emacs server via TCP. An Emacs server usually uses an operating system feature called a "local socket" to listen for connections. Some operating systems, such as Microsoft Windows, do not support local sockets; in that case, Emacs uses TCP instead. When you start the Emacs server, Emacs creates a server file containing some TCP information that `emacsclient' needs for making the connection. By default, the server file is in `~/.emacs.d/server/'. On Microsoft Windows, if `emacsclient' does not find the server file there, it looks in the `.emacs.d/server/' subdirectory of the directory pointed to by the `APPDATA' environment variable. You can tell `emacsclient' to use a specific server file with the `-f' or `--server-file' option, or by setting the `EMACS_SERVER_FILE' environment variable. Even if local sockets are available, you can tell Emacs to use TCP by setting the variable `server-use-tcp' to `t'. One advantage of TCP is that the server can accept connections from remote machines. For this to work, you must (i) set the variable `server-host' to the hostname or IP address of the machine on which the Emacs server runs, and (ii) provide `emacsclient' with the server file. (One convenient way to do the latter is to put the server file on a networked file system such as NFS.) You also may want to look at variables server-auth-dir, server-auth-key and server-port A: I think what you're asking for is impossible by definition, because if you give a remote user unrestricted access to your Emacs, this is just as much "user spoofing" as letting that remote user access a shell via ssh. To spell it out, from a security point of view this is probably a bad idea. Also, the results of letting two users access one Emacs aren't as good as you might hope. It isn't designed with simultaneous access in mind. It's years since I tried it, so things might have moved on a bit, but when I did it was quirky to say the least. Still, I'll try to answer your question. It sounds like you're thinking about this back-to-front, because, counter-intuitively, in network terms, the X11 display is the server, and the X11 application is the client. This is surprising because typically the display is local to the user and the application is running on some remote server. You can instruct a running emacs to connect to a remote display and open a new window with M-x make-frame-on-display. For this to work, the owner of that display will need to grant you access to it. We will assume host-l is the computer that is running Emacs, and that you want to make it accessible to a user of display 0 on host-r. Be aware that you've said you don't want to use SSH forwarding, so following this method will cause all traffic will go across the network unencrypted. First, make sure that display host-r:0 is accepting TCP connections. You don't mention your operating system, but this is probably the default on Unix and probably isn't on Linux (for security reasons). If, for example, the following mentions -nolisten tcp then you'll need to change this configuration. host-r$ ps -ef | grep X Next, get the user of host-r to run the following, and send you the output. Be sure to warn them that this will allow you to take complete control of their current desktop session, should you choose. host-r$ xauth list $DISPLAY host-r/unix:0 MIT-MAGIC-COOKIE-1 01234567890abcdef0123456789abcd This is, effectively, the "password" for the display. On host-l, put it where Emacs will be able to find it with: host-l$ xauth add host-r:0 MIT-MAGIC-COOKIE-1 01234567890abcdef0123456789abcd Now enter M-x make-frame-on-display host-r:0 and an Emacs window should pop up on the remote display.
{ "language": "en", "url": "https://stackoverflow.com/questions/12546722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: SAP UI5: Re-align simple form label and fields to left side I need to move all these highlighted elements to left side of the page(Screen attached). Below is the code for simple form in my xml view: <---XML View---> <f:SimpleForm id="SimpleFormDisplay354" minWidth="1024" maxContainerCols="3" editable="false" layout="ResponsiveGridLayout" title="{i18n>searchFormTitle}" labelSpanL="3" labelSpanM="3" emptySpanL="4" emptySpanM="4" columnsL="1" columnsM="1"> <f:content> <Label text="{i18n>labelDate}" labelFor="datePickerId" design="Bold" > <layoutData> <l:GridData span="L2 M3 S6"/> </layoutData> </Label> <DatePicker id="datePickerId" visible="true" displayFormat="MMM dd,yyyy" valueFormat="dd-MM-yyyy" placeholder="{i18n>dateInput}" change="handleChange"> <layoutData> <l:GridData span="L2 M3 S6"/> </layoutData> </DatePicker> <Button text="{i18n>search}" id="searchButton" width="50%" type="Emphasized" class="Button" press="OnDateSearch"> <layoutData> <l:GridData span="L2 M3 S6"/> </layoutData> </Button> </f:content> </f:SimpleForm> Can anyone help me with what GridData span setting I should make in order to move these elements to left most corner? enter image description here A: If you want to use the existing properties for the Grid Data, you can use indentL property. <Label text="{i18n>labelDate}" labelFor="datePickerId" design="Bold" > <layoutData> <l:GridData span="L1 M3 S6" indentL="0"/> </layoutData> </Label> Give one column (out of 12) to your label and then indent it to 0 (span value=0 for the Large screen), similarly, you can do it for different screen sizes. A: You have to set labelSpanL/labelSpanM to 1 or 2 to decrease left space, but SimpleForm always align the label to right and put colon ":" between Label and Control. If labelSpan 1 or 2 dont resolve. The only way i know is trying use CSS.
{ "language": "en", "url": "https://stackoverflow.com/questions/50975174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OpenShift - no awt in java.library.path I use Openshift for a small app. In this app, I upload images and resize them and stores them in a database. I use: BufferedImage bufferedImage = ImageIO.read(inputStream); But today when I run this part of code I got this exception: java.lang.UnsatisfiedLinkError: no awt in java.library.path java.lang.ClassLoader.loadLibrary(ClassLoader.java:1886) java.lang.Runtime.loadLibrary0(Runtime.java:849) java.lang.System.loadLibrary(System.java:1088) sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:67) sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:47) java.security.AccessController.doPrivileged(Native Method) java.awt.Toolkit.loadLibraries(Toolkit.java:1657) ... I do not know if the OpenShift team has done any upgrade lately. Last time I run that code was perhaps 6 months ago. Do you guys have any solution? Best regards Fredrik A: A rebuild, a redeploy and a restart solved the problem. Really strange. To me this sounds like a system thing and would not have to do with the app itself. Best regards Fredrik
{ "language": "en", "url": "https://stackoverflow.com/questions/33729798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Splitting one table into multiple tables based on columns using velocity Ok below is the code that i have. Here we read a map from a JAVA object and populate columns based on the key and values of the map. The Java object map is of the form HashMap<HashMap<String, Object>>. The required table will have columns equal to number of outer hashmap. The row count will be equal to number of Sting/Objects in the inner hashmap. Following is the code which generates table. As described above, the number of columns in the table will depend on the values in the java object. The problem we are facing is, if the value in hashmap is above 10 then PDH generation resuls in loss of data. <table style="font-family:Arial;font-size:xx-small;color:black" width="100%" border="0" cellspacing="0" cellpadding="0"> #set ($allLegs = $ConfirmationObject.getAllLegs()) #set ($i = 1) <tr> <td valign="top" width="30%"> </td> #foreach($legSzie in $allLegs.keySet()) <td valign="top" width="30%" align="left"><b>Leg $i</b></td> #set ($i=$i+1) #end <tr><td></td></tr> <td valign="top" width="10%" align="right">&nbsp;</td> </tr> <td colspan="1"> <table style="font-family:Arial;font-size:xx-small;color:black" width="100%" border="0" cellspacing="0" cellpadding="0"> #set ($map = $ConfirmationObject.getLegMap(1)) #foreach($key in $map.keySet()) <tr> <td valign="top" width="60%">$key </td> </tr> #end </table> </td> #foreach($legString in $allLegs.keySet()) <td colspan="1"> <table style="font-family:Arial;font-size:xx-small;color:black" width="100%" border="0" cellspacing="0" cellpadding="0"> #set ($legMap = $allLegs.get($legString)) #foreach($legKey in $legMap.keySet()) <tr> <td >$legMap.get($legKey)</td> </tr> #end </table> </td> #end </table> Expectation: Is it possible to have the data split into different tables when ever the column value reaches more than 3? so for example consider a scenario where the table looks like LEG 1 LEG 2 LEG 3 LEG 4 LEG 5 A 12 13 14 15 16 B 12 13 14 15 16 C 12 13 14 15 16 D 12 13 14 15 16 E 12 13 14 15 16 How can we split this like LEG 1 LEG 2 LEG 3 A 12 13 14 B 12 13 14 C 12 13 14 D 12 13 14 E 12 13 14 LEG 4 LEG 5 A 15 16 B 15 16 C 15 16 D 15 16 E 15 16 A: You could try something like that: #set ($columns = $allLegs.keySet().toArray()) #set ($maxCols = 3) #set ($groups = ($columns.size() + $maxCols - 1)/$maxCols) #set ($lastGroup = $groups - 1) #foreach ($group in [0..$lastGroup]) <table style="font-family:Arial;font-size:xx-small;color:black" width="100%" border="0" cellspacing="0" cellpadding="0"> #set ($firstCol = $maxCols*$group ) #set ($lastCol = $firstCol + $maxCols - 1) #if ($lastCol >= $columns.size()) #set ($lastCol = $columns.size() - 1) #end <tr> <th></th> #foreach ($col in [$firstCol..$lastCol]) <th>$columns[$col]</th> #end </tr> #set ($rows = $allLegs.get($columns[$firstCol]).keySet()) #foreach($row in $rows) <tr> <th>$row</th> #foreach ($col in [$firstCol..$lastCol]) #set ($legMap = $allLegs.get($columns[$col])) <td>$legMap.get($row)</td> #end </tr> #end </table> #end A: #set ($allLegs = $ConfirmationObject.getAllLegs()) #set ($columns = $allLegs.keySet()) #set ($maxCols = 3) #set ($groups = ($columns.size() + $maxCols - 1)/$maxCols) #set ($lastGroup = $groups - 1) #foreach ($group in [0..$lastGroup]) #if($group >0 ) <br> <br> #end <table style="font-family:Arial;font-size:xx-small;color:black" width="100%" border="0" cellspacing="0" cellpadding="0"> #set ($allLegs = $ConfirmationObject.getAllLegs()) #set ($i = (($group*$maxCols)+1)) #set ($groupLegs = $ConfirmationObject.getGrouplLegSet($group, $maxCols)) <tr> <td valign="top" width="30%"> </td> #foreach($legSzie in $groupLegs.keySet()) <td valign="top" width="30%" align="left"><b>Leg $i</b></td> #set ($i=$i+1) #end <td></td> <td valign="top" width="10%" align="right">&nbsp;</td> </tr> <td colspan="1"> <table style="font-family:Arial;font-size:xx-small;color:black" width="100%" border="0" cellspacing="0" cellpadding="0"> #set ($map = $ConfirmationObject.getLegMap(1)) #foreach($key in $map.keySet()) <tr> <td valign="top" width="60%">$key </td> </tr> #end </table> </td> #foreach($legString in $groupLegs.keySet()) <td colspan="1"> <table style="font-family:Arial;font-size:xx-small;color:black" width="100%" border="0" cellspacing="0" cellpadding="0"> #set ($legMap = $allLegs.get($legString)) #foreach($legKey in $legMap.keySet()) <tr> <td >$legMap.get($legKey)</td> </tr> #end </table> </td> #end </table> #end Here we wrote a java method getGrouplLegSet($group, $maxCols). The method would just return sub-set of hashmap based on the group and maxCols. So for example if the group is 0 then values from 0 till 2 will be returned, if group value is 1 then sub map from 3 till 5 will be returned and so on..
{ "language": "en", "url": "https://stackoverflow.com/questions/45561330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: log4j2 filePattern doesn't interpolate I've tried to add the following RollingFile appender; <RollingFile name="appFile" fileName="${sys:catalina.base}${sys:file.separator}logs${sys:file.separator}${web:contextPath}${sys:file.separator}app.log" filePattern="app-%d{dd-MM-yyyy}.log"> <PatternLayout pattern="%d{dd/MM/yyyy HH:mm:ss} %c{2} - %m%n" /> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="250 MB" /> </Policies> <DefaultRolloverStrategy max="20" /> </RollingFile> The file is created in the correct path but the name is always the same (app.log) instead of app-xx-xx-xxxx.log. What do I miss? A: The filePattern attribute is the pattern of the file name to use on rollover. But if you want the date pattern in the name of the file that is actively written tom, you can use Date Lookup in the filename attribute, i.e: fileName="${sys:catalina.base}${sys:file.separator}logs${sys:file.separator}${web:contextPath}${sys:file.separator}app-${date:dd-MM-yyyy}.log"
{ "language": "en", "url": "https://stackoverflow.com/questions/41934268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Identityserver4/OpenId Connect, Hybrid mode, Token Refresh Fails I have as ASP.net Core MVC site, that uses OpenId connect to authenticate with another ASP.net Core site, that uses IdentityServer4, that uses another IdentityServer4 site as identity provider. On the client, there is a very few pages, that in theory could be used for a long time with only AJAX-calls. I wan't the site to refresh the access token, so that the user won't be forced to log in, let's say the next day. I've set up a timer, that calls a WebAPI method on the MVC-site, that refreshes the token. It works with the two first refreshes, but always fails on the third. The method returns a JWT to be used on external API-calls. I can see this updates on the fist call as expected, and that it gets a new expiration timestamp. In the third call, the tokenClient.RequestRefreshTokenAsync fails, because the refreshToken is null. public async Task<IActionResult> RefreshToken() { var disco = await DiscoveryClient.GetAsync(_authenticationOptions.Value.Authority); if (disco.IsError) return BadRequest(disco.Error); var tokenClient = new TokenClient(disco.TokenEndpoint, _authenticationOptions.Value.ClientId, _authenticationOptions.Value.ClientSecret); var refreshToken = await HttpContext.Authentication.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken); var tokenResult = await tokenClient.RequestRefreshTokenAsync(refreshToken); if (tokenResult.IsError) return BadRequest(disco.Error); var old_id_token = await HttpContext.Authentication.GetTokenAsync(OpenIdConnectParameterNames.IdToken); var new_access_token = tokenResult.AccessToken; var new_refresh_token = tokenResult.RefreshToken; var tokens = new List<AuthenticationToken>(); tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.IdToken, Value = old_id_token }); tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.AccessToken, Value = new_access_token }); tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.RefreshToken, Value = new_refresh_token }); var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn); tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) }); var info = await HttpContext.Authentication.GetAuthenticateInfoAsync("Cookies"); info.Properties.StoreTokens(tokens); await HttpContext.Authentication.SignOutAsync("Cookies"); await HttpContext.Authentication.SignInAsync("Cookies", info.Principal, info.Properties); return Ok(HttpContext.Authentication.GetTokenAsync("access_token").Result); } I can see, that Chrome is notifying in the console, that a set-cookie header is ignored, because it exceeds 4kb. Any tips? A: Got it. The clients IdentityToken expired, and since that api method wasn't protected by [Authorize] attribute, it didn't renew + changed the script to use an iframe instead of AJAX-calls! Case closed.
{ "language": "en", "url": "https://stackoverflow.com/questions/43052630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Flutter: disable dropdownbutton option I have this widget: DropdownButton<String>( value: rentPeriod, items: rentPeriods.map((String value) { return DropdownMenuItem<String>( value: value, child: Text(translate("expense.$value")), ); }).toList(), onChanged: (value) async { setState(() { rentPeriod = value; }); }, ), How can I disable, let's say, the first option of the list? A: i dont think there is any straight forward way of disabling a DropdownMenuItem but you can have a list of the DropdownMenuItems you want to disable and then when you run setState you can check if that DropdownMenuItem is contained in that list and if it is then do nothing, also check by the DropdownMenuItem text if its contained in that list and if it is then change the color to be greyed out. Like this class MyWidget extends StatefulWidget { @override _MyWidgetState createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { var rentPeriods = <String>['one', 'two']; final disabledItems = ['one']; var rentPeriod; @override Widget build(BuildContext context) { return DropdownButton<String>( value: rentPeriod, items: rentPeriods.map((String value) { return DropdownMenuItem<String>( value: value, child: Text( translate("expense.$value"), style: TextStyle( color: disabledItems.contains(value) ? Colors.grey : null, ), ), ); }).toList(), onChanged: (value) async { if (!disabledItems.contains(value)) { setState(() { rentPeriod = value; }); } }, ); } } A: You can create your own disable customization, changing the color and the callback of onChangedfunction in the DropdownButton, like this example: https://dartpad.dev/587b44d2f1b06e056197fcf705021699?null_safety=true
{ "language": "en", "url": "https://stackoverflow.com/questions/68039731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find the file associated with a memory mapped address in C Is there an existing example of how, in C, to take a memory address and get which, if any, file is mapped to that address? Specifically, I am modifying how msync works and I want to know what file is associated with the address being synced. I can see how in the proc man page such a thing could be found by looking at the contents of the /proc/self/map_files directory, but I am hoping there is an already existing helper function for doing this.
{ "language": "en", "url": "https://stackoverflow.com/questions/30602859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split MySQL fields by character count to the nearest full word? I have a MySQL field for the body texts of blog posts in markdown format. Due to an API I'm using I can only send 3000 character blocks, however some of my posts are as large as 4500 characters and there are over 2000 of them so I don't want to manually split them out. I'm trying to figure out a function to check the char_length of each field in the column and if it is over 3000 characters the function would split out anything beyond 3000 characters (rounded to the nearest word) into a second column I have. It's beyond the scope of functions I've dealt with before and so I'm hoping for a push in the right direction. Here is the base of what I have so far: SELECT `Body` from `blogposts` WHERE char_length(Body) > 3000 SET Body2 = SUBSTRING(`Body`, 3001, char_length(Body)) Body = SUBSTRING(`Body`, 1, 3000) Since it isn't yet complete I've not tested it yet. I'm not convinced it would come close to doing what I want but the two other problems I'm still trying to solve before I test are: 1) How to have it go to the end of the most recent word (rounded down under 3000 characters) rather than split at exactly the 3000th character. 2) If it is trying to deal in words will it break on markdown/html that is in the text such as splitting <div> into <div" "> if that's the 3000th character. For background I've read through the following: Split string into table in groups of 26 characters or less, rounded to the nearest word The responses seem to have come up with custom functions to split the string based on a set length, although the functions aren't well explained/commented so I'm a bit lost. If it isn't easy to do in MySQL I am open to pulling this out in PHP and manipulating the data there. Any insights would be appreciated! A: update `blogposts` set `Body2` = substring(`Body`,3000-instr(reverse(left(`Body`,3000)),' ')+1) ,`Body` = left(`Body`,3000-instr(reverse(left(`Body`,3000)),' ')) where char_length(Body) > 3000 ; Demo on 30 characters set @Body = 'My name is Inigo Montoya! You''ve killed my father, prepare to die!'; select left(@Body,30-instr(reverse(left(@Body,30)),' ')) as field_1 ,substring(@Body,30-instr(reverse(left(@Body,30)),' ')+1) as field_2 ; +---------------------------+------------------------------------------+ | field_1 | field_2 | +---------------------------+------------------------------------------+ | My name is Inigo Montoya! | You've killed my father, prepare to die! | +---------------------------+------------------------------------------+ Full Example create table `blogposts` (`Body` varchar(3000),`Body2` varchar(3000)); insert into blogposts (`Body`) values ('Hello darkness, my old friend' ) ,('I''ve come to talk with you again' ) ,('Because a vision softly creeping' ) ,('Left its seeds while I was sleeping' ) ,('And the vision that was planted in my brain' ) ,('Still remains' ) ,('Within the sound of silence' ) ,('In restless dreams I walked alone' ) ,('Narrow streets of cobblestone' ) ,('''Neath the halo of a street lamp' ) ,('I turned my collar to the cold and damp' ) ,('When my eyes were stabbed by the flash of a neon light' ) ,('That split the night' ) ,('And touched the sound of silence' ) ,('And in the naked light I saw' ) ,('Ten thousand people, maybe more' ) ,('People talking without speaking' ) ,('People hearing without listening' ) ,('People writing songs that voices never share' ) ,('And no one dared' ) ,('Disturb the sound of silence' ) ; select left(`Body`,30-instr(reverse(left(`Body`,30)),' ')) as Body ,substring(`Body`,30-instr(reverse(left(`Body`,30)),' ')+1) as Body2 from `blogposts` where char_length(Body) > 30 ; +------------------------------+---------------------------+ | Body | Body2 | +------------------------------+---------------------------+ | I've come to talk with you | again | +------------------------------+---------------------------+ | Because a vision softly | creeping | +------------------------------+---------------------------+ | Left its seeds while I was | sleeping | +------------------------------+---------------------------+ | And the vision that was | planted in my brain | +------------------------------+---------------------------+ | In restless dreams I walked | alone | +------------------------------+---------------------------+ | 'Neath the halo of a street | lamp | +------------------------------+---------------------------+ | I turned my collar to the | cold and damp | +------------------------------+---------------------------+ | When my eyes were stabbed by | the flash of a neon light | +------------------------------+---------------------------+ | And touched the sound of | silence | +------------------------------+---------------------------+ | Ten thousand people, maybe | more | +------------------------------+---------------------------+ | People talking without | speaking | +------------------------------+---------------------------+ | People hearing without | listening | +------------------------------+---------------------------+ | People writing songs that | voices never share | +------------------------------+---------------------------+ update `blogposts` set `Body2` = substring(`Body`,30-instr(reverse(left(`Body`,30)),' ')+1) ,`Body` = left(`Body`,30-instr(reverse(left(`Body`,30)),' ')) where char_length(`Body`) > 30 ; select `Body` ,`Body2` from `blogposts` where `Body2` is not null ; +------------------------------+---------------------------+ | Body | Body2 | +------------------------------+---------------------------+ | I've come to talk with you | again | +------------------------------+---------------------------+ | Because a vision softly | creeping | +------------------------------+---------------------------+ | Left its seeds while I was | sleeping | +------------------------------+---------------------------+ | And the vision that was | planted in my brain | +------------------------------+---------------------------+ | In restless dreams I walked | alone | +------------------------------+---------------------------+ | 'Neath the halo of a street | lamp | +------------------------------+---------------------------+ | I turned my collar to the | cold and damp | +------------------------------+---------------------------+ | When my eyes were stabbed by | the flash of a neon light | +------------------------------+---------------------------+ | And touched the sound of | silence | +------------------------------+---------------------------+ | Ten thousand people, maybe | more | +------------------------------+---------------------------+ | People talking without | speaking | +------------------------------+---------------------------+ | People hearing without | listening | +------------------------------+---------------------------+ | People writing songs that | voices never share | +------------------------------+---------------------------+ A: That code will always divide string with 3000 characters and push it to the array. You can use this code block no matter what's the character length is. Don't forget if your text have characters lower than 3000 there will be just 1 element in the $bodyParts variable. $bodyText; // That came from SQL Ex Query : SELECT body FROM blogposts $bodyParts = []; $lengthOfBody = strlen($bodyText); if($lengthOfBody > 3000){ $forLoopInt = ceil($lengthOfBody / 3000); // For example if your body text have 3500 characters it will be 2 echo $forLoopInt; for($i = 0; $i<= $forLoopInt - 2; $i++){ $bodyParts[] = substr($bodyText, ($i) * 3000 , 3000); } // lets fetch the last part $bodyParts[] = substr( $bodyText,($forLoopInt - 1) * 3000); }else{ $bodyParts[] = $bodyText; } /* anyway if your body text have characters lower than 3000 , bodyParts array will contain just 1 element, if not it will have Ceil(Length of body / 3000) elements in it. */ var_dump($bodyParts);
{ "language": "en", "url": "https://stackoverflow.com/questions/40832395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to apply an attribute to a descendant element? XSLT Take a look at the following code: <xsl:template match="tocline[@toclevel='2']"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:for-each select="descendant::toctitle"> <xsl:if test="position() = last()"> <xsl:attribute name="last"> <xsl:value-of select="'true'"/> </xsl:attribute> </xsl:if> </xsl:for-each> <xsl:apply-templates /> </xsl:copy> </xsl:template> This template applies the attribute to the tocline element. I want it to apply the attribute to the last toctitle in the nodeset, which can be located at different levels. With this sample: <tocline id="d1e11" toclevel="1"> <toctitle>Section 1. Legislative Powers</toctitle> <tocline id="d1e40" toclevel="2"> <toctitle>Separation of Powers and Checks and Balances</toctitle> <tocline id="d1e51" toclevel="3"> <toctitle>The Theory Elaborated and Implemented</toctitle> </tocline> <tocline id="d1e189" toclevel="3"> <toctitle>Judicial Enforcement</toctitle> </tocline> </tocline> </tocline> I want this: <tocline id="d1e11" toclevel="1"> <toctitle>Section 1. Legislative Powers</toctitle> <tocline id="d1e40" toclevel="2"> <toctitle>Separation of Powers and Checks and Balances</toctitle> <tocline id="d1e51" toclevel="3"> <toctitle>The Theory Elaborated and Implemented</toctitle> </tocline> <tocline id="d1e189" toclevel="3"> <toctitle last="true">Judicial Enforcement</toctitle> </tocline> </tocline> </tocline> But I get this: <tocline id="d1e11" toclevel="1"> <toctitle>Section 1. Legislative Powers</toctitle> <tocline id="d1e40" toclevel="2" last="true"> <toctitle>Separation of Powers and Checks and Balances</toctitle> <tocline id="d1e51" toclevel="3"> <toctitle>The Theory Elaborated and Implemented</toctitle> </tocline> <tocline id="d1e189" toclevel="3"> <toctitle>Judicial Enforcement</toctitle> </tocline> </tocline> </tocline> A: This transformation: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match= "toctitle [. is (ancestor::tocline[@toclevel eq '2'][1]//toctitle)[last()]]"> <toctitle last="true"> <xsl:apply-templates select="@*|node()"/> </toctitle> </xsl:template> </xsl:stylesheet> when applied on the provided XML document: <tocline id="d1e11" toclevel="1"> <toctitle>Section 1. Legislative Powers</toctitle> <tocline id="d1e40" toclevel="2"> <toctitle>Separation of Powers and Checks and Balances</toctitle> <tocline id="d1e51" toclevel="3"> <toctitle>The Theory Elaborated and Implemented</toctitle> </tocline> <tocline id="d1e189" toclevel="3"> <toctitle>Judicial Enforcement</toctitle> </tocline> </tocline> </tocline> produces the wanted, correct result: <tocline id="d1e11" toclevel="1"> <toctitle>Section 1. Legislative Powers</toctitle> <tocline id="d1e40" toclevel="2"> <toctitle>Separation of Powers and Checks and Balances</toctitle> <tocline id="d1e51" toclevel="3"> <toctitle>The Theory Elaborated and Implemented</toctitle> </tocline> <tocline id="d1e189" toclevel="3"> <toctitle last="true">Judicial Enforcement</toctitle> </tocline> </tocline> </tocline> A: I added a key, and here's what I came up with: <xsl:key name="l2id" match="tocline[@toclevel eq '2']" use="@id"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="toctitle[. is (ancestor-or-self::tocline/key('l2id',@id)/descendant-or-self::toctitle[last()])]"> <xsl:copy> <xsl:attribute name="last"> <xsl:value-of select="'true'"/> </xsl:attribute> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template>
{ "language": "en", "url": "https://stackoverflow.com/questions/14380209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reason to use String instead of Text in Haskell I hear that good practice in Haskell to use Text instead of String. I am trying to follow this rule, and coming up with the following question: Why parseRoute of Network-HTTP-Client is designed to work with String and not Text? What is the general recommendation to use String instead of Text? https://www.stackage.org/haddock/lts-14.2/http-client-0.6.4/Network-HTTP-Client.html#v:parseRequest A: I suspect the most likely answer is, sadly, that String is still the path of least resistance: the ability to reuse all the familiar list functions (and the very good support for lists in parsing libraries) is so convenient that a largish collection of libraries continue to use String despite possible technical advantages of choosing a different type. Until the cost of the "worse" (but more convenient) choice is carefully quantified and a fix written by somebody who cares, you can expect that to pretty much stay unchanged in any given library.
{ "language": "en", "url": "https://stackoverflow.com/questions/57617292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: angularjs and localStorage change event I store some data in the localStorage what I want in my angularjs app is that when the data in the localStorage changed, the app rerender the app, how can I do this? A: I recently created a module allows you to simply bind a localStorage key to a $scope variable and also store Objects, Arrays, Booleans and more directly inside the localStorage. Github localStorage Module A: There is an angular localStorage module: https://github.com/grevory/angular-local-storage var DemoCtrl = function($scope, localStorageService) { localStorageService.clearAll(); $scope.$watch('localStorageDemo', function(value){ localStorageService.add('localStorageDemo',value); $scope.localStorageDemoValue = localStorageService.get('localStorageDemo'); }); $scope.storageType = 'Local storage'; if (!localStorageService.isSupported()) { $scope.storageType = 'Cookie'; } }; After further thought you may need to change the module to broadcast on setItem so that you can get notified if the localStorage has been changed. Maybe fork and around line 50: localStorage.setItem(prefix+key, value); $rootScope.$broadcast('LocalStorageModule.notification.setItem',{key: prefix+key, newvalue: value}); // you could broadcast the old value if you want or in the recent version of the library the casing was changed $rootScope.$broadcast('LocalStorageModule.notification.setitem',{key: prefix+key, newvalue: value}); Then in your controller you can: $scope.$on('LocalStorageModule.notification.setItem', function(event, parameters) { parameters.key; // contains the key that changed parameters.newvalue; // contains the new value }); Here is a demo of the 2nd option: Demo: http://beta.plnkr.co/lpAm6SZdm2oRBm4LoIi1 ** Updated ** I forked that project and have included the notifications here in the event you want to use this project: https://github.com/sbosell/angular-local-storage/blob/master/localStorageModule.js I believe the original library accepted my PR. The reason I like this library is that it has a cookie backup in case the browser doesn't support local storage. A: Incidentally, I've created yet another localStorage module for AngularJS which is called ngStorage: https://github.com/gsklee/ngStorage Usage is ultra simple: JavaScript $scope.$storage = $localStorage.$default({ x: 42 }); HTML <button ng-click="$storage.x = $storage.x + 1">{{$storage.x}}</button> And every change is automagically sync'd - even changes happening in other browser tabs! Check out the GitHub project page for more demos and examples ;) A: $scope.$on("LocalStorageModule.notification.setitem", function (key, newVal, type) { console.log("LocalStorageModule.notification.setitem", key, newVal, type); }); $scope.$on("LocalStorageModule.notification.removeitem", function (key, type) { console.log("LocalStorageModule.notification.removeitem", key, type); }); $scope.$on("LocalStorageModule.notification.warning", function (warning) { console.log("LocalStorageModule.notification.warning", warning); }); $scope.$on("LocalStorageModule.notification.error", function (errorMessage) { console.log("LocalStorageModule.notification.error", errorMessage); }); this event calling when using https://github.com/grevory/angular-local-storage#getstoragetype in app config myApp.config(function (localStorageServiceProvider) { localStorageServiceProvider .setPrefix('myApp') .setStorageType('sessionStorage') .setNotify(true, true) });
{ "language": "en", "url": "https://stackoverflow.com/questions/16150311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: How to get value of completed task while uploading video to AWS? I have implemented the AWSS3 to upload the video to the AWS server and also I want to get the value of task which has been completed using AWSS3TransferUtilityUploadExpression() to show the value on progress bar. But I am not getting the value please see the below code atached. ///1 typealias progressBlock = (_ progress: Double) -> Void //2 typealias completionBlock = (_ response: Any?, _ error: Error?) -> Void //3 //2 // Upload video from local path url func uploadVideo(videoUrl: URL, progress: progressBlock?, completion: completionBlock?) { print("video url is \(videoUrl)") let fileName = self.getUniqueFileName(fileUrl: videoUrl) print("keyname \(fileName)") self.uploadfile(fileUrl: videoUrl, fileName: fileName, contenType: "video", progress: progress, completion: completion) } //method to upload the video private func uploadfile(fileUrl: URL, fileName: String, contenType: String, progress: progressBlock?, completion: completionBlock?) { // Upload progress block let expression = AWSS3TransferUtilityUploadExpression() expression.progressBlock = {(task, awsProgress) in guard let uploadProgress = progress else { return } DispatchQueue.main.async { debugPrint("completed portion of the task is \(awsProgress.fractionCompleted)") uploadProgress(awsProgress.fractionCompleted) //progress!(awsProgress.fractionCompleted) } } // Completion block var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock? completionHandler = { (task, error) -> Void in DispatchQueue.main.async(execute: { if error == nil { let url = AWSS3.default().configuration.endpoint.url let publicURL = url?.appendingPathComponent(self.bucketName).appendingPathComponent(fileName) if let completionBlock = completion { completionBlock(publicURL?.absoluteString, nil) } } else { if let completionBlock = completion { print("error is at completionBlock \(error?.localizedDescription)") completionBlock(nil, error) } } }) } // Start uploading using AWSS3TransferUtility let awsTransferUtility = AWSS3TransferUtility.default() awsTransferUtility.uploadFile(fileUrl, bucket: bucketName, key: fileName, contentType: contenType, expression: expression, completionHandler: completionHandler).continueWith { (task) -> Any? in if let error = task.error { print("error is: \(error.localizedDescription)") } if let url = task.result { // your uploadTask print("url is \(url)") } return nil } } A: Install cocoapods pod 'AWSS3'. Here filePath is the path of the file to be uploaded. func saveModelInAmazonS3() { let remoteName = fileName + ".mov" //extension of your file name let S3BucketName = "bucketName" let uploadRequest = AWSS3TransferManagerUploadRequest()! uploadRequest.body = filePath! uploadRequest.key = remoteName uploadRequest.bucket = S3BucketName uploadRequest.contentType = "application/zip" uploadRequest.acl = .publicRead uploadRequest.uploadProgress = { (bytesSent, totalBytesSent, totalBytesExpectedToSend) -> Void in DispatchQueue.main.async(execute: { // here you can track your progress let amountUploaded = totalBytesSent let fileSize = totalBytesExpectedToSend print("\(amountUploaded)/\(fileSize)") let progress = (CGFloat(amountUploaded) / CGFloat(fileSize))) }) } let transferManager = AWSS3TransferManager.default() transferManager.upload(uploadRequest).continueWith(block: { (task: AWSTask) -> Any? in if let error = task.error { self.delegate.errorInUpload(uploadState: self.uploadState) print("Upload failed with error: (\(error.localizedDescription))") } if task.result != nil { let url = AWSS3.default().configuration.endpoint.url print("Uploaded to:\(String(describing: url))") } return nil }) }
{ "language": "en", "url": "https://stackoverflow.com/questions/65808501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can we find the IRR of cash flows in a Dataframe? I can easily find the NPV if items in a dataframe using the code below. But how can I get the IRR of the same items? import numpy_financial as npf import pandas as pd # Intitialise data of lists data = [{'Month': '2020-01-01', 'Expense':1000, 'Revenue':5000, 'Building':'Stadium'}, {'Month': '2020-02-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'}, {'Month': '2020-03-01', 'Expense':7000, 'Revenue':5000, 'Building':'Stadium'}, {'Month': '2020-04-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'}, {'Month': '2020-01-01', 'Expense':5000, 'Revenue':6000, 'Building':'Casino'}, {'Month': '2020-02-01', 'Expense':5000, 'Revenue':4000, 'Building':'Casino'}, {'Month': '2020-03-01', 'Expense':5000, 'Revenue':9000, 'Building':'Casino'}, {'Month': '2020-04-01', 'Expense':6000, 'Revenue':10000, 'Building':'Casino'}] df = pd.DataFrame(data) df df.groupby("Building")["Revenue"].apply(lambda x: npf.npv(rate=0.1, values=x)) Result: Building Casino 24587.528174 Stadium 15773.854245 I tried to find the IRR, like this. df.groupby("Building")["Revenue"].apply(lambda x: npf.irr(values=x)) It calculates only NAN. Result: Building Casino NaN Stadium NaN Documentation: https://numpy.org/numpy-financial/latest/irr.html A: You could combine apply() with irr(). What you try to find is the interest rate, where the NPV is 0. However, as you only have positive revenues and no initial investment (neg. sign), it can not be. Please check out the formula used in the docs. You might want to also consider the expenses? I've edited your example to demonstrate a working solution. Update: I added large initial payments and passed the delta between expenses and revenue to irr(). import numpy_financial as npf import pandas as pd data = [{'Month': '2020-01-01', 'Expense':100000, 'Revenue':5000, 'Building':'Stadium'}, {'Month': '2020-02-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'}, {'Month': '2020-03-01', 'Expense':7000, 'Revenue':5000, 'Building':'Stadium'}, {'Month': '2020-04-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'}, {'Month': '2020-01-01', 'Expense':500000, 'Revenue':6000, 'Building':'Casino'}, {'Month': '2020-02-01', 'Expense':5000, 'Revenue':4000, 'Building':'Casino'}, {'Month': '2020-03-01', 'Expense':5000, 'Revenue':9000, 'Building':'Casino'}, {'Month': '2020-04-01', 'Expense':6000, 'Revenue':10000, 'Building':'Casino'}] df = pd.DataFrame(data) irr = df.groupby('Building')[['Revenue','Expense']].apply(lambda x: npf.irr(x['Revenue'] - x['Expense'])) print(irr) Output: Building Casino -0.786486 Stadium -0.809623 dtype: float64 A: While I am no expert on Financial Analysis, I believe this question requires more explanation and assessment than what has been presented. So, with all due respect to @KarelZ's response which in fact produces an answer for the stated data, I think from a financial analysis standpoint it is not of much value. As defined Internal Rate of Return (IRR) is a metric used in financial analysis to estimate the profitability of potential investments. IRR is a discount rate that makes the net present value (NPV) of all cash flows equal to zero in a discounted cash flow analysis. The inherent assumptions in this definition are (1) there exists an initial investment and (2) there is a cashflow stream resulting from the investment. As defined Net Present Value (NPV) is the present value of the cash flows at a specified rate of return of your project compared to your initial investment. In practical terms, it's a method of calculating your return on investment, or ROI, for a project or expenditure. While NPV doesn't necessarily imply an initial investment, it does imply that for the calculation to be useful, the true cashflow should be evaluated which implies taking into account the expenses as well as the revenue to be meaningful. In order to compute a valid IRR we need to incorporate the initial investment in the structures and compute the IRR based on differences between Expenses and Revenue. With this in mind, I have modified the original dataset by adding a row to each structure showing the initial investment as an Expense. See below: # Intitialise data of lists data = [{'Month': '2019-12-01', 'Expense':100000, 'Revenue':0, 'Building':'Stadium'}, {'Month': '2020-01-01', 'Expense':1000, 'Revenue':5000, 'Building':'Stadium'}, {'Month': '2020-02-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'}, {'Month': '2020-03-01', 'Expense':7000, 'Revenue':5000, 'Building':'Stadium'}, {'Month': '2020-04-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'}, {'Month': '2019-12-01', 'Expense':150000, 'Revenue':0, 'Building':'Casino'}, {'Month': '2020-01-01', 'Expense':5000, 'Revenue':6000, 'Building':'Casino'}, {'Month': '2020-02-01', 'Expense':5000, 'Revenue':4000, 'Building':'Casino'}, {'Month': '2020-03-01', 'Expense':5000, 'Revenue':9000, 'Building':'Casino'}, {'Month': '2020-04-01', 'Expense':6000, 'Revenue':10000, 'Building':'Casino'}] df = pd.DataFrame(data) This produces the dataframe shown below: Month Expense Revenue Building 0 2019-12-01 100000 0 Stadium 1 2020-01-01 1000 5000 Stadium 2 2020-02-01 3000 4000 Stadium 3 2020-03-01 7000 5000 Stadium 4 2020-04-01 3000 4000 Stadium 5 2019-12-01 150000 0 Casino 6 2020-01-01 5000 6000 Casino 7 2020-02-01 5000 4000 Casino 8 2020-03-01 5000 9000 Casino 9 2020-04-01 6000 10000 Casino To this dataframe I added a CashFlow Column consisting of the difference between expense and revenue as follows: def computeCashFlow(e, r): return r-e df['CashFlow'] = df.apply(lambda row: computeCashFlow(row.Expense, row.Revenue), axis= 1) Which results in the addition of the CashFlow shown below: Month Expense Revenue Building CashFlow 0 2019-12-01 100000 0 Stadium -100000 1 2020-01-01 1000 5000 Stadium 4000 2 2020-02-01 3000 4000 Stadium 1000 3 2020-03-01 7000 5000 Stadium -2000 4 2020-04-01 3000 4000 Stadium 1000 5 2019-12-01 150000 0 Casino -150000 6 2020-01-01 5000 6000 Casino 1000 7 2020-02-01 5000 4000 Casino -1000 8 2020-03-01 5000 9000 Casino 4000 9 2020-04-01 6000 10000 Casino 4000 Using the CashFlow Column you can then compute IRR and NPR as follows: df.groupby("Building")["CashFlow"].apply(lambda x: npf.npv(rate=0.1, values=x)) Building Casino -144180.042347 Stadium -96356.806229 Name: CashFlow, dtype: float64 df.groupby('Building')['CashFlow'].apply(lambda x: npf.irr(x)) Building Casino -0.559380 Stadium -0.720914 Name: CashFlow, dtype: float64 Giving realistic results for NPV and IRR taking into account the original investments
{ "language": "en", "url": "https://stackoverflow.com/questions/71774505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: map function in React-Native I am new to React Native and I am using Typescript for my project. I am difficulty to do mapping in React Native. Below is my code for interface: interface Teacher { name: string; sex: string; age: number; student: Student[]; } interface Student { name: string; sex: string; address: string; } I don't have any problem mapping Teacher's interface but I am having difficulty on how to map Student interface when I use the map function in my code. {Class.map(class => ( <View> {class.student.map(class => ( <Text>{class.name}</Text> ))} {class.student.map(class => ( <Text>{class.sex}</Text> ))} {class.student.map(class => ( <Text>{class.address}</Text> ))} </View> )} When I did my coding like this, I get an error Cannot read property 'map' of undefined in my console. Thank you in advance. A: you can try like this with create nested array. interface Teacher { name: string; sex: string; age: number; student: Student[{ name: string; sex: string; address: string; }]; } {Teacher.map(({name,sex,address,student}) => ( <View> {student.map(student => ( <Text>{student.name}</Text> <Text>{student.sex}</Text> <Text>{student.address}</Text> ))} </View> )}
{ "language": "en", "url": "https://stackoverflow.com/questions/60784800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Build url string using C# I've been trying to build the request url for my json request but been getting a 404 error. This is the code I put together after reading some threads on it. Can anyone help? var apiKey = "123456"; var Query = "some search"; var Location = "San Jose, CA"; var Sort = "1"; var SearchRadius = "100"; var values = HttpUtility.ParseQueryString(string.Empty); values["k"] = apiKey; values["q"] = Query; values["l"] = Location; values["sort"] = Sort; values["radius"] = SearchRadius; string url = "http://api.website.com/api" + values.toString(); This is where I am getting the error. After passing the url on client.DownloadString() var client = new WebClient(); var json = client.DownloadString(url); var search = Json.Decode(json); A: Your code is building an invalid URL: http://api.website.com/apik=123456&q=some+search&l=San+Jose%2c+CA&sort=1&radius=100 Note the /apik=123456 portion. var apiKey = "123456"; var Query = "some search"; var Location = "San Jose, CA"; var Sort = "1"; var SearchRadius = "100"; // Build a List of the querystring parameters (this could optionally also have a .ToLookup(qs => qs.key, qs => qs.value) call) var querystringParams = new [] { new { key = "k", value = apiKey }, new { key = "q", value = Query }, new { key = "l", value = Location }, new { key="sort", value = Sort }, new { key = "radius", value = SearchRadius } }; // format each querystring parameter, and ensure its value is encoded var encodedQueryStringParams = querystringParams.Select (p => string.Format("{0}={1}", p.key, HttpUtility.UrlEncode(p.value))); // Construct a strongly-typed Uri, with the querystring parameters appended var url = new UriBuilder("http://api.website.com/api"); url.Query = string.Join("&", encodedQueryStringParams); This approach will build a valid, strongly-typed Uri instance with UrlEncoded querystring parameters. It can easily be rolled into a helper method if you need to use it in more than one location. A: Use the UriBuilder class. It will ensure the resulting URI is correctly formatted.
{ "language": "en", "url": "https://stackoverflow.com/questions/18452322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Is it possible to copy the default frambuffer to a framebuffer object without showing anything on the screen? If so, I can save the content of the FBO as an image file. Other question: This image will have a resolution related with the screen? Or, it will have the same resolution as the input image that was texturized on the default framebuffer? Was my question clear? A: Copying between framebuffers: glBlitFramebuffer see here https://www.opengl.org/sdk/docs/man3/xhtml/glBlitFramebuffer.xml This image will have a resolution related with the screen? The resolution can be set in the glBlitFramebuffer function. The default framebuffer has the size of your opengl window (can be different than the screen). Is it possible to copy the default frambuffer to a framebuffer object without showing anything on the screen? The image is usually first rendered offscreen and displayed when calling swapBuffers (double buffering). So without calling swapBuffers nothing is shown on the screen. Keep in mind though, that you can render directly into framebuffers objects and you don't have to first render it into the default framebuffer and then copy it over. To do that just call glBindFramebuffer before your actual draw calls.
{ "language": "en", "url": "https://stackoverflow.com/questions/31686577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to insert R text variables into Latex expressions keeping normal formatting I want to create Section headers with a for loop and have managed to do this however the text is stuck in math mode formatting. I've tried using Latex syntax to undo this however it did not work as expected: Code: --- title: "Troubleshooting" author: "Me" output: pdf_document header-includes: - \usepackage{amsmath} --- ```{r} words <- c("plz_work","better_yet","what_is_this") ``` ```{r, results='asis', echo=FALSE} for (i in 1:3) { cat('\\subsection{$',words[i],'$}') } ``` Output: If I use the latex notation to convert it to text formatting nothing changes: ```{r, results='asis', echo=FALSE} for (i in 1:3) { cat('\\subsection{$\text{',words[i],'}$}') } ``` If I escape the "$\text{..}$" again i.e. "$\\text{..}$" then I get an error: ! Missing $ inserted. <inserted text> $ l.283 \subsection{$\text{ plz_work }$} Error: Failed to compile test_delete_is_ok.tex. See test_delete_is_ok.log for more info. Execution halted Adding more escapes doesnt help. If I try to insert this variable without math mode I also get the same error that I just listed: ```{r, results='asis', echo=FALSE} for (i in 1:3) { cat('\\subsection{',words[i],'}') } ``` ! Missing $ inserted. <inserted text> $ l.283 \subsection{ plz_work } Error: Failed to compile test_delete_is_ok.tex. See test_delete_is_ok.log for more info. Execution halted A: As mentioned by Samcarter, when using tex you need to also be aware of any tex-related special meanings. In this instance - the "_" symbol is used in tex math mode for signalling a subscript is about to follow. When passing my R strings that contained "_" into the tex expression it would throw an error as the "_" is reserved for math mode (unless escaped) - this is why I got no error when I enclosed it with $...$ The solution for me was to add in escapes before every tex special character: #original words <- c("plz_work","better_yet","what_is_this") #modified version. Replace collapse with other tex functions if needed words2 <- lapply(strsplit(words,"_"), paste, collapse = '\\_') for (i in 1:3) { cat('\\subsection{',words2[[i]],'}') } The underscores here are a little long for my liking but you can easily replace the 'collapse' argument to something else which you prefer eg. ... collapse ='\\textunderscore ') ... also works
{ "language": "en", "url": "https://stackoverflow.com/questions/56178556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way to erase string completely in VB6? I want to erase confidential string like password, creditcard number from memory. In C#, there is a class named SecureString. But In VB6, I didn't find any solution. Is there a way to erase string completely from memory? A: A SecureString is encrypted while at rest which is more than just providing a way to prevent it remaining in memory. Is there a way to erase string completely from memory? Yes, you need to modify the string in-situ and overwrite its contents. You can do this using mid$() in LHS mode: Dim i As Long For i = 1 To Len(secret) Mid$(secret, i, 1) = "0" Next Or with the ZeroMemory or CopyMemory API: ZeroMemory ByVal StrPtr(secret), LenB(secret) ... CopyMemory ByVal StrPtr(secret), ByVal StrPtr(String$(Len(secret), "0")), LenB(secret) For encryption you could implement the DPAPI CryptProtectData API (which is what SecureString is based on).
{ "language": "en", "url": "https://stackoverflow.com/questions/32622849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remove sections of audio in SoX What's the easiest way to remove the specified sections of a wav file using SoX? Right now I use the trim command to break up the file and then concatenate the parts. However, that seems a little tedious and backwards since trim takes a section of audio and copies it to a new file, so I have to trim the opposite of the the sections that I specify to remove, and then concatenate those. Any help appreciated, thanks! A: This is ugly but... try: sox "|sox in.wav -p trim 0 start" "|sox in.wav -p trim length" out.wav Where start is the the offset of the removing area and length is the number of seconds to remove Example: to remove between 30s and 50s: sox "|sox in.wav -p trim 0 30" "|sox in.wav -p trim 20" out.wav Update -- a better solution: sox in.wav out.wav trim 0 =start =end Example: to remove between 30s and 50s: sox in.wav out.wav trim 0 =30 =50
{ "language": "en", "url": "https://stackoverflow.com/questions/31881106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Trying to print only string data I'm trying to get the for-loop and if statement to just print out string data only. var languages = { english: "Hello!", french: "Bonjour!", notALanguage: 4, spanish: "Hola!" }; // print hello in the 3 different languages for (var x in languages) { if (typeof x === "string") { console.log(languages[x]) } }; A: I believe what you're trying to do is: for (var x in languages) { if (typeof languages[x] === "string") { console.log(languages[x]); } } The way you've currently coded it will print out all the "keys" in the object since the keys are all "strings". A: In object literal terms, english,french,notALanguage, spanish are property. Properties are strings in JavaScript, although when defining the property name inside an object literal you may omit the string delimiters. When looping through property names using a for...in, the property name is a string like for (x in languages) { alert(typeof x); //-> "string" } You need like this var languages = { english: "Hello!", french: "Bonjour!", notALanguage: 4, spanish: "Hola!" }; // print hello in the 3 different languages for (var x in languages) { //console.log(typeof x); //it will print 4 times because all keys are string if (typeof languages[x] === "string") { console.log(languages[x]) } } Demo http://jsfiddle.net/4hxgvr6q/ A: Thanks I actually found the same exact question I had from user :Leahcim posted with the correct answer from post user: Some Guy JavaScript: using typeof to check if string for (var hello in languages) { var value= languages[hello] if (typeof value === "string") { console.log(value) } };
{ "language": "en", "url": "https://stackoverflow.com/questions/33985410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular Bootstrap UI - how to save data from modal directive to controller? I am using Angular Bootstrap UI in my project. I have a directive 'HelpDirective', which is used in different controllers. That directive calls HelpService which opens a modal and after it is closed the data is supposed to still remain in the controller model. But it does not work :( Here is the template: <button type="button" class="btn btn-link" selectedHelp="selectedHelp" help-directive> <span class="fa fa-question"></span> Help </button> Here is my directive: service.directive('helpDirective', ['helpService', function (helpService) { return { restrict: 'A', scope: { selectedHelp : "=" }, link: function (scope, element, attrs) { element.click(function (e) { e.preventDefault(); var modal = helpService.openHelpModal(scope.selectedHelp); modal.result.then(function (selectedHelp) { console.log(selectedHelp); scope.selectedHelp = selectedHelp; }); }); } }; }]); console.log - gives me the right data. But in controller the data is lost.
{ "language": "en", "url": "https://stackoverflow.com/questions/34991186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: find the source of duplicate data in an Ember.js view A while ago I made a chatting app using Socket.io, Redis and Node.js. Recently, a friend forked my repository on Github and implemented the same chat implementation in Ember.js. I figured I'd help along, because a lot of the stuff he added broke a lot of the functionality of my code. I've tried fixing it as much as I can, where I can. The two problems I want to fix though, are duplicate pieces of data. I'm no Ember.js expert - I barely know the framework. There are two issues I'd like to fix: In the user's online list - there are duplicate usernames. When submitting a message, two messages with the same content appear. I've had a look at Redis locally while trying to find the bug and nothing is duplicate in Redis. The code in app.js doesn't have any errors that are obvious enough for me to spot either. Here's a link to the repositories for code reference as they are much too large to add here (live examples are in the README's): https://github.com/declandewet/ember-js-chatapp/ (my fork of his repo) https://github.com/declandewet/chatapp (my repo) A: Moving the current_users.push into the part that cycles through and adds it to redis seemed to fix it.
{ "language": "en", "url": "https://stackoverflow.com/questions/14932594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mongoose Schema TypeScript Error + Index signature for type string is missing I am using inversify in my express API for dependency injection and I am trying to define my schema using typescript 4.9.4 if I downgrade to 4.3.2 the error goes away but if possible I would love to figure this out. Interface export interface UserType { _id?: string email: string password: string } export interface UserModel extends UserType, Omit<Document, '_id'> {} Schema @injectable() export class UserRepository extends GenericRepository<UserType, UserModel> implements UserRepositoryInterface { public constructor(@inject(TYPES.DbClient) dbClient: DbClient) { super( dbClient, 'users', new Schema({ email: { type: String, trim: true, required: true, unique: true, lowercase: true, }, password: { type: String, required: true, }, }), ) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/74974446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using the finance gem in a rails project I am trying to use the "finance" gem for a rails project. I have successfully installed the gem by editing my Gemfile and using "bundle install". I have included the line: application_controller.rb include Finance This allows me access to the finance gem functions in controllers. But, something wonky is going on with my numbers. If you go to the following link you can see a simple example of how to create a Rate object and use it to find amortization: http://rubydoc.info/gems/finance/1.1.2/frames But, in a controller, when I try to set a Rate object to a variable using the code provided: @rate = Rate.new(0.0425, :apr, :duration => 30.years) ...this throws the error "wrong argument type Flt::DecNum (expected scalar Numeric)" What is going on is the value "0.0425" that I'm passing into Rate is apparently a Float/DecNum but it's expecting a Numeric object. If I use the code below to cast the number to a Numeric type, the error is gone but the Rate object created isn't really working properly: @rate = Rate.new(0.0425.to_c, :apr, :duration => 30.years) All in all I just want to be able to use the finance gem in controllers and/or helpers but there seems to be some errors generated because the numbers I'm passing are of the wrong type. Can anyone offer any help? A: Since this question got no attention I wanted to post my solution in case others run across this. So, I ended up not using this gem and just writing the methods myself. The reason being that this gem was written specifically for Ruby, not for Rails. Other users got the same error as I did and the only resolution was to hack actual code in the gem if you were using this on a Rails site. So, the solution, at least for now would be to not use this gem for Rails, only for purely Ruby. The author I believe states this plainly but something I overlooked. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/11479236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does order of constructors / cases / guards / if-then-else matter to performance? I saw this comment in Containers/Data/Set/Base.hs -- [Note: Order of constructors] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- The order of constructors of Set matters when considering performance. -- Currently in GHC 7.0, when type has 2 constructors, a forward conditional -- jump is made when successfully matching second constructor. Successful match -- of first constructor results in the forward jump not taken. -- On GHC 7.0, reordering constructors from Tip | Bin to Bin | Tip -- improves the benchmark by up to 10% on x86. Where else does order have tiny measurable impacts on performance? In particular I wonder about case statements with many options. A: It depends. The order of constructors does, unfortunately, make a difference. This means that the order of the patterns for that type does not. Whether you write foo (Bin x y) = ... foo Tip = ... or foo Tip = ... foo (Bin x y) = ... makes no difference, because they will be reordered by constructor order immediately in the "desugaring" process. The order of matching for multiple patterns is always semantically left-to-right, so the argument order can matter if you use multiple patterns together (you can always get around this with case). But GHC feels very free to reorganize code, sometimes for good and sometimes for ill. For instance, if you write foo :: Int -> Bool foo x = x == 5 || x == 0 || x == 7 || x == 4 GHC will smash it into (essentially) foo = \x -> case x of 0 -> True 4 -> True 5 -> True 7 -> True _ -> False and then do a sort of binary search of these possibilities. This is probably not optimal in many cases at all, and is especially annoying if you happen to know that x==5 is particularly likely. But that's how it is for now, and changing it will make things perform badly in certain situations without someone doing a lot of work.
{ "language": "en", "url": "https://stackoverflow.com/questions/27323911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Local Host is not sending any data Whenever i ran this node server on Port "8000" const http=require('https') const PORT=8000 const server=http.createServer() server.on('request',(req,res)=>{ if (req.url==='friend'){ res.writeHead(200,{ 'Content-Type':'text/plain', }) res.end(JSON.stringify({ id:1, name:'Sir Issac Newton', })) } if (req.url==='foe'){ res.writeHead(200,{ 'Content-Type':'text/plain', }) res.end('The Enemy is Ego Bro') } }) server.listen(PORT,()=>{ console.log(`the respnse is exectued at ${PORT}`) }) i get an error on the Borwser which says: localhost didn’t send any data. ERR_EMPTY_RESPONSE i try to change ports but still it shows this error.Please what should i do and explain me what this error is. Thank you! A: This code has 3 problems. * *You should change const http=require('https') to const http=require('http'). If you want to use HTTPS please see the nodejs document for how to configure the https server *In nodejs HTTP request URL start with / and your condition statement does not work *Cuz request URL does not match with the condition statement server does not respond any things and this error happens. You should change code like that: const http=require('http') const PORT=8000 const server=http.createServer() server.on('request',(req,res)=>{ if (req.url==='/friend'){ res.writeHead(200,{ 'Content-Type':'text/plain', }); res.end(JSON.stringify({ id:1, name:'Sir Issac Newton', })); return; } if (req.url==='/foe'){ res.writeHead(200,{ 'Content-Type':'text/plain', }); res.end('The Enemy is Ego Bro'); return; } res.writeHead(400,{ 'Content-Type':'text/plain', }); res.end('URL not match'); }) server.listen(PORT,()=>{ console.log(`the respnse is exectued at ${PORT}`) })
{ "language": "en", "url": "https://stackoverflow.com/questions/70945369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fix redux-observable Parameter 'action$' implicitly has an 'any' type I am trying to implement TS epic function, but "action$" need to have some implicit type that differs for , i could not find working example of this type of function... I made function that works just fine but i cant fix TS error of ANY type. export const fetchSettingsEpic = action$ => action$.pipe( ofType(types.UPDATE_INITIAL_SETTINGS), mergeMap(action => ajax.getJSON(url).pipe( map((response: Settings) => actions.updateInitialSuccess(response)), catchError(error => of(actions.updateInitialError(error))), ), ), ); The function is pretty simple, but how can I fix "Parameter 'action$' implicitly has an 'any' type." error? IMPORTANT! Dot tell me to turn off "noImplicitAny": true, or don't check this part of code ) A: Don't turn off noImplicityAny. You are right, you shouldn't! What you should do is, declare the type of the parameters, which is ActionsObservable<T>. Where T should be the type of the action. Example: export enum SettingsActionTypes { FETCH: "settings/fetch", FETCH_SUCCESS: "settings/fetchSuccess" } export function fetch(): IFetchAction { return { type: SettingsActionTypes.FETCH }; } export interface IFetchAction { type: SettingsActionTypes.FETCH; } export interface IFetchSuccessAction { type: SettingsActionTypes.FETCH_SUCCESS; } export type SettingsAction = IFetchAction | IFetchSuccessAction; Then in your epics, you can write something like this: import { ActionsObservable, StateObservable } from 'redux-observable'; export const fetchSettingsEpic = (action$: ActionsObservable<SettingsAction>) => action$.ofType(SettingsActionTypes.FETCH).mergeMap(...do your stuff here...) Also, if you need to access state in your epics, you might have to use the second parameter state$ whose type is StatesObservable<T>. Where T is the interface that defines the structure of your entire redux state.
{ "language": "en", "url": "https://stackoverflow.com/questions/54516933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create a record and add an image in database in TYPO3 I use TYPO3 version 10.4.21 and I created an own extension for leaflet. In frontend I can't see a picture. My code in js-file for now: var map = L.map('map', {crs: L.CRS.Simple}); var bounds = [[0,0], [750,1200]]; L.imageOverlay("../Parks/Park.png", bounds).addTo(map); map.fitBounds(bounds); The path for the picture is right, but I can't display the picture "Park.png". Then I thought there is no data in my database. In ext.tables.sql: CREATE TABLE tx_interaktivekarte_domain_model_park ( image int(11) DEFAULT NULL, bgcolor varchar(255) DEFAULT NULL, markers int(11) DEFAULT NULL, icon varchar(255) DEFAULT NULL, iccolor int(11) DEFAULT NULL, pin int(11) DEFAULT NULL, title varchar(255) DEFAULT NULL, marker int(11) unsigned NOT NULL DEFAULT '0' ); CREATE TABLE tx_interaktivekarte_domain_model_marker ( park int(11) unsigned DEFAULT '0' NOT NULL, title varchar(255) DEFAULT NULL, lat varchar(255) DEFAULT NULL, lon varchar(255) DEFAULT NULL, contenthtml text DEFAULT NULL, icon varchar(255) DEFAULT NULL, text text DEFAULT NULL ); How can I add a image in a database? I referred an extension: https://docs.typo3.org/p/onm/int-park/1.0/en-us/Installation/Index.html And there is written "Under any folder, create a db record ‘Park’, add image in it.". Maybe I have to do it same thing in my extension, but I don't know what the text means. What do I have to do to display my picture on leaflet? And is it because of database? I have aright to access into database with phpMyAdmin. Thank you for your help. A: In TYPO3 you should store images as references. TYPO3 provides a File Abstraction Layer which you and your extension should use. That starts with integration in TCA, see: https://docs.typo3.org/m/typo3/reference-tca/10.4/en-us/ColumnsConfig/Type/Inline.html#file-abstraction-layer For the frontend output, you can refer to this part of the documentation: https://docs.typo3.org/m/typo3/reference-coreapi/main/en-us/ApiOverview/Fal/UsingFal/Frontend.html So, two short points: * *Correct integration in backend via TCA and references *Correct integration in frontend via Image ViewHelper and either fetching FileReference object via Extbase or via DataProcessing. A: In TYPO3 files are handled normally by FAL (File Abstraction Layer). This means: you get a record with relevant information of the file. in any record which references a file you have symbolic DB-field (with just a counter in it) and you have MM-records which connects the sys_file records of the file to your record. Your example probably includes special records where files can be referenced. If you develop extensions you can use this manual to get more information about structure of files and records. You also can have a look into the declaration of other records like the extension you gave as example. The currently best example would always be the declaration of the core. For an example how to include files in a record I would suggest the table tt_content and the field media. The important part is the TCA declaration, as this configures the 'magic' how an integer field from the database table is connected to a file.
{ "language": "en", "url": "https://stackoverflow.com/questions/70708141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding multiple columns to excel from TCL I'm trying to add multiple columns to excel from TCL. Here is the code set rows [array size atten] set columns { B} for {set row 1} {$row <= $rows} {incr row} { foreach column $columns { $cells Item $row $column $atten($row) } } ----This data is alone populated in excel set a_rows [array size transmit] set a_columns { C} for {set row 1} {$row <= $a_rows} {incr row} { foreach column $a_columns { $cells Item $row $column $transmit($row) } } $workbook SaveAs Filename {c:\tst.xls} $application Quit Only the first array atten is populated in the excel file, it completely omits the part in the code that adds the transmit array in the excel file. How can this be solved? A: Set both columns in a single foreach loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/9577040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to set encoding of a variable when passing between ASP pages Let's say I have page A, which uses ks_c_5601-1987(Korean) as encoding and page B, using UTF-8 (Korean) as encoding. I need to pass a string variable from A to B that is in Korean. Because two pages use a different encoding, the variable gets jumbled up when B receives it using Request(). How can I encode the string variable in A to UTF-8 when passing it to B? I'm aware that setting both pages as UTF-8 encoding scheme is the most sensible solution here but it unfortunately is not an option here since page A uses several dlls that relies entirely on ks_c_5601-1987 encoding. Edit: After reviewing the answer, I have went ahead and tried the method. This is the code to send the variable mailbox into get_list_center.asp: <!--mail_mail.asp, page in ks_c_5601-1987--> <% dim mailbox = "테스트" Response.CodePage = 65001 'Response.write should now encode the string into UTF-8 %> ... <frame name="get_list_center" scrolling="auto" marginwidth="0" framespacing="0" marginheight="0" frameborder="0" src="get_list_center.asp?mailbox=<%=mailbox%>"> and this is how I'm receiving the variable in get_list_center.asp: <% Session.Codepage=65001 Response.CharSet="UTF-8" response.Write CStr(response.codepage) & "<BR>" response.Write CStr(session.CodePage) & "<BR>" response.Write CStr(response.CharSet) & "<BR>" response.codepage = 949 response.Write mailbox & "<BR>" response.codepage = 65001 response.Write mailbox & "<BR>" %> Here is the result: Both 949 (ks_c_5601-1987) and 65001 (UTF-8) versions of response.write comes out broken. Is there anything else I'm missing? A: I would think that you could get an answer by reading the solution to this question: internal string encoding . By utilizing Reponse.Codepage you can affect how posted variables are interpreted. And as I understand you can then switch back to wichever encoding you like. [Update] Because you are using an iframe it is the browser that handles the encoding when sending the request back to the server. And the browser (as I understand) sends the data in the same encoding as the originating page. So if page A that contains the iframe has the charset=Korean I believe that data is sent using Korean encoding. Is the charset defined in the html tag on page A? If not, add it and then try to use the same in page B. <meta charset="utf-8"> Also, as "테스트" is a string literal that is affected of the FILE-encoding, make sure to save the asp-file in the appropiate encoding.
{ "language": "en", "url": "https://stackoverflow.com/questions/14702226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apache CXF dependencies We are in the process of upgrading our JDK(Tomcat), we upgraded CXF to 3.2.12 from 2.4.0 and we were getting an error which was fixed by adding -Dorg.apache.cxf.stax.allowInsecureParser=1 as an JVM argument based on this CXF web service client: "Cannot create a secure XMLInputFactory" but I don't think its the right way to do. Can anybody suggest any other plausible solutions? javax.xml.ws.soap.SOAPFaultException: Cannot create a secure XMLInputFactory at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:157) at $Proxy38.printString(Unknown Source) at ExampleNmsWebServiceClient.printString(ExampleNmsWebServiceClient.java:29) at ExampleNmsWebServiceClient.main(ExampleNmsWebServiceClient.java:40) Caused by: org.apache.cxf.binding.soap.SoapFault: Cannot create a secure XMLInputFactory at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.unmarshalFault(Soap11FaultInInterceptor.java:84) at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:51) at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:40) at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:272) at org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:113) at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:69) at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:34) at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:272) at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:835) at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1606) at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1502) at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1309) at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56) at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:627) A: You need to add Woodstox to the classpath, see the accepted answer here: https://stackoverflow.com/a/24603135/3745288
{ "language": "en", "url": "https://stackoverflow.com/questions/60403425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using termios in Swift Now that we've reached Swift 2.0, I've decided to convert my, as yet unfinished, OS X app to Swift. Making progress but I've run into some issues with using termios and could use some clarification and advice. The termios struct is treated as a struct in Swift, no surprise there, but what is surprising is that the array of control characters in the struct is now a tuple. I was expecting it to just be an array. As you might imagine it took me a while to figure this out. Working in a Playground if I do: var settings:termios = termios() print(settings) then I get the correct details printed for the struct. In Obj-C to set the control characters you would use, say, cfmakeraw(&settings); settings.c_cc[VMIN] = 1; where VMIN is a #define equal to 16 in termios.h. In Swift I have to do cfmakeraw(&settings) settings.c_cc.16 = 1 which works, but is a bit more opaque. I would prefer to use something along the lines of settings.c_cc.vim = 1 instead, but can't seem to find any documentation describing the Swift "version" of termios. Does anyone know if the tuple has pre-assigned names for it's elements, or if not, is there a way to assign names after the fact? Should I just create my own tuple with named elements and then assign it to settings.c_cc? Interestingly, despite the fact that pre-processor directives are not supposed to work in Swift, if I do print(VMIN) print(VTIME) then the correct values are printed and no compiler errors are produced. I'd be interested in any clarification or comments on that. Is it a bug? The remaining issues have to do with further configuration of the termios. The definition of cfsetspeed is given as func cfsetspeed(_: UnsafeMutablePointer<termios>, _: speed_t) -> Int32 and speed_t is typedef'ed as an unsigned long. In Obj-C we'd do cfsetspeed(&settings, B38400); but since B38400 is a #define in termios.h we can no longer do that. Has Apple set up replacement global constants for things like this in Swift, and if so, can anyone tell me where they are documented. The alternative seems to be to just plug in the raw values and lose readability, or to create my own versions of the constants previously defined in termios.h. I'm happy to go that route if there isn't a better choice. A: Let's start with your second problem, which is easier to solve. B38400 is available in Swift, it just has the wrong type. So you have to convert it explicitly: var settings = termios() cfsetspeed(&settings, speed_t(B38400)) Your first problem has no "nice" solution that I know of. Fixed sized arrays are imported to Swift as tuples, and – as far as I know – you cannot address a tuple element with a variable. However,Swift preserves the memory layout of structures imported from C, as confirmed by Apple engineer Joe Groff:. Therefore you can take the address of the tuple and “rebind” it to a pointer to the element type: var settings = termios() withUnsafeMutablePointer(to: &settings.c_cc) { (tuplePtr) -> Void in tuplePtr.withMemoryRebound(to: cc_t.self, capacity: MemoryLayout.size(ofValue: settings.c_cc)) { $0[Int(VMIN)] = 1 } } (Code updated for Swift 4+.)
{ "language": "en", "url": "https://stackoverflow.com/questions/31465943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Updating UI from another Thread extended Class What I want to do: [Web Scraping with Jsoup] Adding elements to a TableView from an another Thread extended Class. Button click -> start Thread -> Thread add elements to TableView. Files |javafxapplication5 |-->FXMLDocuments.fxml |-->FXMLDocumentController.java |-->JavaFXApplication5.java |-->Scraper.java FXMLDocumentController.java package javafxapplication5; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; public class FXMLDocumentController implements Initializable { Scraper scraper = new Scraper(); @FXML private Label label; @FXML private Button shareButton; @FXML private TextField searchInput; @FXML private Button searchTorrents; @FXML private void handleButtonAction(ActionEvent event) { System.out.println("You clicked me!"); } @FXML private void setMouseEntered(MouseEvent event) { searchTorrents.setStyle("-fx-border-color:blue"); } @FXML private void setMouseLeaved(MouseEvent event) { searchTorrents.setStyle("-fx-border-color:black"); } @FXML private void shareButton(ActionEvent event) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText("Hai cliccato il bottone share"); alert.showAndWait(); } @FXML private void scrapButton(ActionEvent event) { scraper.start(); } @Override public void initialize(URL url, ResourceBundle rb) { // TODO } } Scraper.java package javafxapplication5; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class Scraper extends Thread{ public void run() { Document doc; try { doc = Jsoup.connect("https://www.allkeyshop.com/blog/daily-deals/").get(); Elements gamesNames = doc.select(".search-results-row-game-title"); for (Element element:gamesNames) { //Update TableView } } catch (IOException ex) { Logger.getLogger(TorrentScraper.class.getName()).log(Level.SEVERE, null, ex); } } } I hope is everything clear, if not please answer me with a constructive suggestion. A: Here is an example you can use as a guide. The URL you use does not have a result list. I would suggest you use something like https://www.allkeyshop.com/blog/catalogue/search-game/. It appears, what comes after the hyphen is what is being searched. You may need to do a few complicated searches to see how the URL changes. This example uses Task. In the Task setOnSuccedded updates the TableView. Main import java.io.IOException; import java.util.ArrayList; import java.util.List; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.VBox; import javafx.stage.Stage; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * JavaFX App */ public class App extends Application { @Override public void start(Stage primaryStage) { TableView<JSoupData> tvMain = new TableView(); ObservableList<JSoupData> tableItems = FXCollections.observableArrayList(); tvMain.setItems(tableItems); TableColumn<JSoupData, String> tcTagName = new TableColumn<>("Tag Name"); tcTagName.setCellValueFactory(new PropertyValueFactory<>("tagName")); TableColumn<JSoupData, String> tcText = new TableColumn<>("Text"); tcText.setCellValueFactory(new PropertyValueFactory<>("text")); tvMain.getColumns().add(tcTagName); tvMain.getColumns().add(tcText); TextField tfUrl = new TextField("https://www.allkeyshop.com/blog/catalogue/search-game/"); tfUrl.setPromptText("Enter URL Here!"); Button btnProcess = new Button("Process URL"); btnProcess.setOnAction((t) -> { btnProcess.setDisable(true); Task<List<JSoupData>> task = scrapper(tfUrl.getText()); task.setOnSucceeded((WorkerStateEvent t1) -> { List<JSoupData> tempList = task.getValue(); tableItems.setAll(tempList); btnProcess.setDisable(false); }); Thread thread = new Thread(task); thread.setDaemon(true); thread.start(); }); VBox root = new VBox(tvMain, tfUrl, btnProcess); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(); } public Task<List<JSoupData>> scrapper(String url) { Task<List<JSoupData>> scrapperTask = new Task<List<JSoupData>>() { @Override protected List<JSoupData> call() { List<JSoupData> jSoupDatas = new ArrayList(); try { System.out.println("url: " + url); Document document = Jsoup.connect(url).get(); System.out.println("Title: " + document.title()); Elements gamesNames = document.select(".search-results-row"); System.out.println("search-results-row"); for (Element element : gamesNames) { jSoupDatas.add(new JSoupData(element.tagName(), element.text())); System.out.println("Tag Name: " + element.tagName() + " - Text: " + element.text()); } } catch (IOException e) { System.out.println(e.toString()); } return jSoupDatas; } }; return scrapperTask; } } JSoupData * * @author sedrick (sedj601) */ public class JSoupData { private String tagName; private String text; public JSoupData(String tagName, String text) { this.tagName = tagName; this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTagName() { return tagName; } public void setTagName(String tagName) { this.tagName = tagName; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("JSoupData{tagName=").append(tagName); sb.append(", text=").append(text); sb.append('}'); return sb.toString(); } } A: Usually, Platform.runLater() can be used to execute those updates on the JavaFX application thread. You can get more information from documentation here and an example from here
{ "language": "en", "url": "https://stackoverflow.com/questions/64470319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Apache Wicket application global settings for database connection I wrote small web application with wicket and sql2o. I have several DAO classes where I create new Sql2o instances with hardcoded username and password: Sql2o database = new Sql2o("jdbc:oracle:thin:@127.0.0.1:1521:test", "test", "test"); If I change password I would have to change it everywhere. So my question is where and how to put these settings in wicket so it could be accessed from different classes. Maybe I should use .properties file? A: You can use a .properties file, where you need to type: jdbc.url=jdbc:oracle:thin:@//localhost:1521/your_database jdbc.username=user jdbc.password=password A: The URL should be chaged to one of the following depending on you configurations * *jdbc:oracle:thin:@host:port/service *jdbc:oracle:thin:@host:port:SID (SID - System ID of the Oracle server database instance.) *jdbc:oracle:thin:@myhost:1521:databaseInstance (By default, Oracle Database 10g Express Edition creates one database instance called XE.)
{ "language": "en", "url": "https://stackoverflow.com/questions/21286040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: can I run a command in Tkinter without Button so basically I'm trying to make a command line interface using python and I have text area where commands are being entered. what I wanted to achieve is each command is executing without pressing the button at all( simply on pressing enter) A: You can bind the Enter key to a function with .bind('<Return>', function).
{ "language": "en", "url": "https://stackoverflow.com/questions/60402442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: zend framework project shows blank page without any errors i created a simple project with zf and it works fine, but when i copy it to other pc it just show a blank page without any page or errors ? my zf version is 1.9 and in other pc zf version 1.9 too what do you do about this problem? A: Do you have error reporting enabled on your machine? Make sure, that you have these lines in your php.ini file: error_reporting = E_ALL display_errors = on It will help you to find the problem by showing the error. If it doesn't help, try to put this code in your index.php in public directory ini_set('display_errors', 1); Also make sure, that DocumentRoot points to your Zend project public folder. A: Are the memory limits the same on both servers? I have seen similar results using php (with zend, albeit). When I run out of memory, just a blank white screen is the result. A: This error is caused because your server is running version 4 of PHP, change to version 5 and it will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/2539965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Double buffered ListBox I have a CheckedListBox (WinForms) control (which inherits from ListBox; googling shows that the problem is with ListBox) that is anchored to all four sides of its form. When the form is resized, the ListBox has an ugly flicker. I tried inheriting CheckedListBox and setting DoubleBuffered to true in the ctor (this technique works with other controls, including ListView and DataGridView), but it had no effect. I tried adding the WS_EX_COMPOSITED style to CreateParams, and this helped, but makes the form resize mush more slowly. Is there any other way to prevent this flickering? A: You could check if switching to a ListView Control with checkboxes improves matters. It's not as easy to deal with (but hey, the WinForms ListBox isn't a stroke of genius either), I found that it's resize behavior with DoubleBuffered=true is bearable. Alternatively, you could try to reduce flicker by overriding the parent forms background drawing - either providing a hollow brush, or overriding WM_ERASEBKND by doing nothing and returning TRUE. (that's ok if your control covers the entire client area of the parent form, otherwise you'd need a more complex background drawing method. I've used this successfully in Win32 applications, but I don't know if the Forms control adds some of it's own magic that renders this nonfunctional. A: I was having similar issues albeit with an owner drawn listbox. My solution was to use BufferedGraphics objects. Your mileage may vary with this solution if your list isn't owner drawn, but maybe it will give you some inspiration. I found that TextRenderer had difficulties rendering to the correct location unless I suppled TextFormatFlags.PreserveGraphicsTranslateTransform. The alternative to this was to use P/Invoke to call BitBlt to directly copy pixels between the graphics contexts. I chose this as the lesser of two evils. /// <summary> /// This class is a double-buffered ListBox for owner drawing. /// The double-buffering is accomplished by creating a custom, /// off-screen buffer during painting. /// </summary> public sealed class DoubleBufferedListBox : ListBox { #region Method Overrides /// <summary> /// Override OnTemplateListDrawItem to supply an off-screen buffer to event /// handlers. /// </summary> protected override void OnDrawItem(DrawItemEventArgs e) { BufferedGraphicsContext currentContext = BufferedGraphicsManager.Current; Rectangle newBounds = new Rectangle(0, 0, e.Bounds.Width, e.Bounds.Height); using (BufferedGraphics bufferedGraphics = currentContext.Allocate(e.Graphics, newBounds)) { DrawItemEventArgs newArgs = new DrawItemEventArgs( bufferedGraphics.Graphics, e.Font, newBounds, e.Index, e.State, e.ForeColor, e.BackColor); // Supply the real OnTemplateListDrawItem with the off-screen graphics context base.OnDrawItem(newArgs); // Wrapper around BitBlt GDI.CopyGraphics(e.Graphics, e.Bounds, bufferedGraphics.Graphics, new Point(0, 0)); } } #endregion } The GDI class (suggested by frenchtoast). public static class GDI { private const UInt32 SRCCOPY = 0x00CC0020; [DllImport("gdi32.dll", CallingConvention = CallingConvention.StdCall)] private static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, UInt32 dwRop); public static void CopyGraphics(Graphics g, Rectangle bounds, Graphics bufferedGraphics, Point p) { IntPtr hdc1 = g.GetHdc(); IntPtr hdc2 = bufferedGraphics.GetHdc(); BitBlt(hdc1, bounds.X, bounds.Y, bounds.Width, bounds.Height, hdc2, p.X, p.Y, SRCCOPY); g.ReleaseHdc(hdc1); bufferedGraphics.ReleaseHdc(hdc2); } } A: This used to be handled by sending the WM_SETREDRAW message to the control. const int WM_SETREDRAW = 0x0b; Message m = Message.Create(yourlistbox.Handle, WM_SETREDRAW, (IntPtr) 0, (IntPtr) 0); yourform.DefWndProc(ref m); // do your updating or whatever else causes the flicker Message m = Message.Create(yourlistbox.Handle, WM_SETREDRAW, (IntPtr) 1, (IntPtr) 0); yourform.DefWndProc(ref m); See also: WM_SETREDRAW reference at Microsoft Fixed Link If anyone else has used windows messages under .NET, please update this posting as necessary. A: Although not addressing the specific issue of flickering, a method that is frequently effective for this type of issue is to cache a minimal state of the ListBox items. Then determine whether you need to redraw the ListBox by performing some calculation on each item. Only update the ListBox if at least one item needs to be updated (and of course save this new state in the cache for the next cycle).
{ "language": "en", "url": "https://stackoverflow.com/questions/1131912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Java BigDecimal divide What am I doing wrong here? Pretty sure this is right, I'm able to print the total, but then it breaks on calculating average. public static void main(String[] args) { BigDecimal test1 = new BigDecimal("67"); BigDecimal test2 = new BigDecimal("76"); BigDecimal test3 = new BigDecimal("99"); BigDecimal test_count = new BigDecimal("3"); BigDecimal total = test1.add(test2).add(test3); System.out.println(total); BigDecimal average = total.divide(test_count); System.out.println(average); } Exception thrown: Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. at java.math.BigDecimal.divide(BigDecimal.java:1690) at HelloWorld.main(HelloWorld.java:31) A: The ArithmeticException is thrown because your division leads to a non terminating decimal, if you explicitly provide the method with a rounding mode, this exception will no longer be thrown. So, try this BigDecimal average = total.divide(test_count, RoundingMode.HALF_UP);
{ "language": "en", "url": "https://stackoverflow.com/questions/42616046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any other way to stop persistence of field(which is also a domain class object) in a Grails domain class other than using transient keyword? class ContentA{ String name ContentB[] contentBList } class contentB{ Long typeId String typeName } Both ContentA and ContentB are domain objects which will be populated in respective calls to the restful services we have. org.hibernate.MappingException: Could not determine type for: [Lcom.classes.ContentB;, at table: table_name, for columns: [org.hibernate.mapping.Column(content_b_list) We get the above error when building the application. When we add the ContentB to the static transients{} it is not rendered in the generated json string. We use json calls to interact with service and convert the Domain objects to json strings. Is there any other way to have the ORM stop persisting contentB? We even tried to use CustomMarshaller for generating json string that didn't work out well. A: You need to define the association class ContentA { String name static hasMany = [contentBList: ContentB] } GORM oneToMany
{ "language": "en", "url": "https://stackoverflow.com/questions/27314342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loop over List of ints vs List of Dictionary in Python I want to know why changing a variable in python's for loop changes dictionary element but not list? In another word I want to compare following codes with each other, why the output is different? list1 = [10, 20] for item in list1: item += 1 print(list1) # Output: [10, 20] dict = [{"Age":10}, {"Age":20}] for item in dict: item["Age"] += 1 print(dict) # Output: [{'Age': 11}, {'Age': 21}] A: It doesn't change because in case of list you changed value of int which is immutable in python, so changing item won't affect it's original value in list, while in second case you modified dict object which is mutable, so your change was applied to original object. For example, following code with list will work: list = [{}, {}] for item in list: item['Age'] = 1 print(list) Output: [{'Age': 1}, {'Age': 1}]
{ "language": "en", "url": "https://stackoverflow.com/questions/57544175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I paint / repaint / paintComponents outside of the JViewport in my JScrollpane? I have a class that extends JFrame and pops up a window (frame). I successfully added a jpanel and a jscrollpane that uses that panel. I have a Jbutton on the jpanel that uses actionlistener and will call repaint (or paintComponents, whichever you think is better) every time I click the button. The problem is, what gets painted will get erased when I scroll over the painted material. The JButton stays and doesn't get redrawn, but the stuff that gets painted gets erased. So my question is: How do I paint outside of the JViewport on a JScrollpane's panel? I have been trying in vain, experimenting with the Graphics class methods such as Graphics.setClip() and JViewport.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE)... the setClip() method in fact does the opposite of what I want to do. It limits the paintable area of the chosen component, when in fact I want to expand the area that gets painted - I want to paint (and keep painted) the area outside of the viewport.
{ "language": "en", "url": "https://stackoverflow.com/questions/9382645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php maverick htaccess not parsed on port :8888 I've install a dev environment on my mac running os x maverick and everything works fine excepted url rewriting. To be exact, when I go to localhost on the default port, it works. but when I go to the website folder in terminal and I start apache on the port :8888 using this command: php -S localhost:8888 then the .htaccess is not read. I want to work this way in order to have my server logs in the terminal. What is the problem? This is my httpd.conf file: ServerRoot "/usr" Listen 80 LoadModule authn_file_module libexec/apache2/mod_authn_file.so LoadModule authn_dbm_module libexec/apache2/mod_authn_dbm.so LoadModule authn_anon_module libexec/apache2/mod_authn_anon.so LoadModule authn_dbd_module libexec/apache2/mod_authn_dbd.so LoadModule authn_default_module libexec/apache2/mod_authn_default.so LoadModule authz_host_module libexec/apache2/mod_authz_host.so LoadModule authz_groupfile_module libexec/apache2/mod_authz_groupfile.so LoadModule authz_user_module libexec/apache2/mod_authz_user.so LoadModule authz_dbm_module libexec/apache2/mod_authz_dbm.so LoadModule authz_owner_module libexec/apache2/mod_authz_owner.so LoadModule authz_default_module libexec/apache2/mod_authz_default.so LoadModule auth_basic_module libexec/apache2/mod_auth_basic.so LoadModule auth_digest_module libexec/apache2/mod_auth_digest.so LoadModule cache_module libexec/apache2/mod_cache.so LoadModule disk_cache_module libexec/apache2/mod_disk_cache.so LoadModule mem_cache_module libexec/apache2/mod_mem_cache.so LoadModule dbd_module libexec/apache2/mod_dbd.so LoadModule dumpio_module libexec/apache2/mod_dumpio.so LoadModule reqtimeout_module libexec/apache2/mod_reqtimeout.so LoadModule ext_filter_module libexec/apache2/mod_ext_filter.so LoadModule include_module libexec/apache2/mod_include.so LoadModule filter_module libexec/apache2/mod_filter.so LoadModule substitute_module libexec/apache2/mod_substitute.so LoadModule deflate_module libexec/apache2/mod_deflate.so LoadModule log_config_module libexec/apache2/mod_log_config.so LoadModule log_forensic_module libexec/apache2/mod_log_forensic.so LoadModule logio_module libexec/apache2/mod_logio.so LoadModule env_module libexec/apache2/mod_env.so LoadModule mime_magic_module libexec/apache2/mod_mime_magic.so LoadModule cern_meta_module libexec/apache2/mod_cern_meta.so LoadModule expires_module libexec/apache2/mod_expires.so LoadModule headers_module libexec/apache2/mod_headers.so LoadModule ident_module libexec/apache2/mod_ident.so LoadModule usertrack_module libexec/apache2/mod_usertrack.so #LoadModule unique_id_module libexec/apache2/mod_unique_id.so LoadModule setenvif_module libexec/apache2/mod_setenvif.so LoadModule version_module libexec/apache2/mod_version.so LoadModule proxy_module libexec/apache2/mod_proxy.so LoadModule proxy_connect_module libexec/apache2/mod_proxy_connect.so LoadModule proxy_ftp_module libexec/apache2/mod_proxy_ftp.so LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so LoadModule proxy_scgi_module libexec/apache2/mod_proxy_scgi.so LoadModule proxy_ajp_module libexec/apache2/mod_proxy_ajp.so LoadModule proxy_balancer_module libexec/apache2/mod_proxy_balancer.so LoadModule ssl_module libexec/apache2/mod_ssl.so LoadModule mime_module libexec/apache2/mod_mime.so LoadModule dav_module libexec/apache2/mod_dav.so LoadModule status_module libexec/apache2/mod_status.so LoadModule autoindex_module libexec/apache2/mod_autoindex.so LoadModule asis_module libexec/apache2/mod_asis.so LoadModule info_module libexec/apache2/mod_info.so LoadModule cgi_module libexec/apache2/mod_cgi.so LoadModule dav_fs_module libexec/apache2/mod_dav_fs.so LoadModule vhost_alias_module libexec/apache2/mod_vhost_alias.so LoadModule negotiation_module libexec/apache2/mod_negotiation.so LoadModule dir_module libexec/apache2/mod_dir.so LoadModule imagemap_module libexec/apache2/mod_imagemap.so LoadModule actions_module libexec/apache2/mod_actions.so LoadModule speling_module libexec/apache2/mod_speling.so LoadModule userdir_module libexec/apache2/mod_userdir.so LoadModule alias_module libexec/apache2/mod_alias.so LoadModule rewrite_module libexec/apache2/mod_rewrite.so #LoadModule perl_module libexec/apache2/mod_perl.so LoadModule php5_module libexec/apache2/libphp5.so LoadModule hfs_apple_module libexec/apache2/mod_hfs_apple.so <IfModule !mpm_netware_module> <IfModule !mpm_winnt_module> User _www Group _www </IfModule> </IfModule> ServerAdmin [email protected] DocumentRoot "/Library/WebServer/apachesites" <Directory /> Options FollowSymLinks AllowOverride all Order deny,allow Deny from all </Directory> <Directory "/Library/WebServer/apachesites"> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny Allow from all </Directory> <IfModule dir_module> DirectoryIndex index.html </IfModule> <FilesMatch "^\.([Hh][Tt]|[Dd][Ss]_[Ss])"> Order allow,deny Deny from all Satisfy All </FilesMatch> <Files "rsrc"> Order allow,deny Deny from all Satisfy All </Files> <DirectoryMatch ".*\.\.namedfork"> Order allow,deny Deny from all Satisfy All </DirectoryMatch> ErrorLog "/private/var/log/apache2/error_log" LogLevel warn <IfModule log_config_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> # You need to enable mod_logio.c to use %I and %O LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio </IfModule> CustomLog "/private/var/log/apache2/access_log" common </IfModule> <IfModule alias_module> ScriptAliasMatch ^/cgi-bin/((?!(?i:webobjects)).*$) "/Library/WebServer/CGI-Executables/$1" </IfModule> <IfModule cgid_module> </IfModule> <Directory "/Library/WebServer/CGI-Executables"> AllowOverride None Options None Order allow,deny Allow from all </Directory> DefaultType text/plain <IfModule mime_module> TypesConfig /private/etc/apache2/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz </IfModule> TraceEnable off Include /private/etc/apache2/extra/httpd-mpm.conf Include /private/etc/apache2/extra/httpd-autoindex.conf Include /private/etc/apache2/extra/httpd-languages.conf Include /private/etc/apache2/extra/httpd-userdir.conf Include /private/etc/apache2/extra/httpd-vhosts.conf Include /private/etc/apache2/extra/httpd-manual.conf <IfModule ssl_module> SSLRandomSeed startup builtin SSLRandomSeed connect builtin </IfModule> Include /private/etc/apache2/other/*.conf And this is httpd-vhosts.conf NameVirtualHost *:80 <VirtualHost *:80> DocumentRoot "/Library/WebServer/apachesites" ErrorLog "/private/var/log/apache2/dummy-host.example.com-error_log" CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log" common </VirtualHost> <VirtualHost *:8888> DocumentRoot "/Library/WebServer/apachesites" ErrorLog "/private/var/log/apache2/dummy-host.example.com-error_log" CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log" common </VirtualHost> A: The built-in HTTP server ran by php -S is not Apache, thus there's no .htaccess nor mod_rewrite or any fancy stuff
{ "language": "en", "url": "https://stackoverflow.com/questions/22541727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting ActionBarSherlock Theme for Android app READ UPDATE 2 BELOW FOR THE ANSWER I'm trying to use ActionBarSherlock in my app. I checked out the 4.0.0 release from the project github repo, built it in Netbeans, then copied the library-4.0.0.jar file into my project's lib directory (I'm not using Eclipse). It's just a skeleton activity right now, and it launches just fine in ICS, but when I run it on Gingerbread I get the following exception complaining that I haven't the app theme to Theme.Sherlock (or similar): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arashpayan.prayerbook/com.arashpayan.prayerbook.PrayerBook}: java.lang.IllegalStateException: You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) at android.app.ActivityThread.access$1500(ActivityThread.java:117) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:130) at android.app.ActivityThread.main(ActivityThread.java:3683) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:507) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.IllegalStateException: You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative. at com.actionbarsherlock.internal.ActionBarSherlockCompat.generateLayout(ActionBarSherlockCompat.java:987) at com.actionbarsherlock.internal.ActionBarSherlockCompat.installDecor(ActionBarSherlockCompat.java:899) at com.actionbarsherlock.internal.ActionBarSherlockCompat.setContentView(ActionBarSherlockCompat.java:852) at com.actionbarsherlock.ActionBarSherlock.setContentView(ActionBarSherlock.java:655) at com.actionbarsherlock.app.SherlockFragmentActivity.setContentView(SherlockFragmentActivity.java:316) at com.arashpayan.prayerbook.PrayerBook.onCreate(PrayerBook.java:44) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) ... 11 more The line it complains about (PrayerBook:44) is the call to setContentView. The app just consists of a single activity with an onCreate() method that I call setTheme() from at the top: public void onCreate(Bundle savedInstanceState) { setTheme(com.actionbarsherlock.R.style.Theme_Sherlock); super.onCreate(savedInstanceState); TextView rootTextView = new TextView(this); rootTextView.setText("Hello, world!"); setContentView(rootTextView); getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ActionBar.Tab tab = getSupportActionBar().newTab(); tab.setText("Prayers"); getSupportActionBar().addTab(tab); tab = getSupportActionBar().newTab(); tab.setText("Recents"); getSupportActionBar().addTab(tab); tab = getSupportActionBar().newTab(); tab.setText("Bookmarks"); getSupportActionBar().addTab(tab); } I must be setting the theme incorrectly, but I just don't see how. Can anyone help? UPDATE Below, CommonsWare noted that the theme can be set in the AndroidManifest.xml. I've tried that like so: <application android:label="@string/app_name" android:icon="@drawable/icon" android:theme="@style/Theme.Sherlock"> <activity android:name="PrayerBook" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden|screenLayout|uiMode|mcc|mnc|locale|navigation|fontScale|screenSize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="LanguagesActivity" /> </application> but Ant gives me an error when it tries to build the app: /Users/arash/coding/prayerbook/AndroidManifest.xml:7: error: Error: No resource found that matches the given name (at 'theme' with value '@style/Theme.Sherlock'). UPDATE 2 With CommonsWare's help in his follow up comments, I was able to get it working. I needed to add ActionBarSherlock as a project dependency. To do so, 1) I removed library-4.0.0.jar and android-support-4.0.jar from my project's lib directory. 2) Next, navigate into the library folder inside the root of the ActionBarSherlock directory checked out from github. Type android update project so a build.xml and proguard.cfg file will be created for the library. 3) Finally, cd back into the main project directory and add ABS as a library dependency with android update project --path . --library ../ActionBarSherlock/library The path to the --library in the command will vary according to where you checked out the repo. ActionBarSherlock and my app's project directory were sibling directories. A: Usually, you set your theme in the manifest, as shown in the Android developer documentation (and linked to from the ActionBarSherlock theming page). If you want to use ActionBarSherlock everywhere within your app, this works: <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/Theme.Sherlock"> A: <!--Provides resources--> <dependency> <groupId>com.actionbarsherlock</groupId> <artifactId>library</artifactId> <version>4.1.0</version> <type>apklib</type> </dependency> <!-Provides import links--> <dependency> <groupId>com.actionbarsherlock</groupId> <artifactId>library</artifactId> <version>4.1.0</version> <type>jar</type> <scope>provided</scope> </dependency> The hint is to use type "apklib", that's mean that maven will be using all sources (resources too). Other dependecy to jar file (scope "provided") is used to achieve link to sherlock classes during coding. A: For me this was caused by not using the @style/ prefix. I.e. I had <style name="AppTheme" parent="Theme.Sherlock.Light" /> instead of <style name="AppTheme" parent="@style/Theme.Sherlock.Light" /> Which is kind of weird because I swear the default template value is something like: <style name="AppTheme" parent="android:Theme.Holo.Light" /> A: If you wanna use custom style, I made a template for custom ActionBarSherlock style. Theme is defined in /values/styles.xml file. It is extended from Theme.Sherlock.Light theme. There are many parameters, you can set: icon, logo, divider, title, shadow overlay, action menu buttons, popup menu, action mode background, dropdown list navigation, tab style, display options etc. Almost everything, what you need, to create your custom action bar theme. I use this template in my apps, because it helps me to style action bar very quickly. You can find this template on my GitHub. It is very easy to use. Just copy values and drawable directiories into your project and set android:theme parameter in application element in AndroidManifest.xml: <application ... android:theme="@style/Theme.Example"> Drawables in my template were generated via Android Action Bar Style Generator. I use different naming convention for resources. This simple script renames all resources generated with Android Action Bar Style Generator to my own convention, used in the template. A: Had the same problem. The app crashed altough the theme was set in the manifest. Setting the theme programmatically solved the problem: @Override protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); A: This was happening to me in IntelliJ IDEA. I solved this issue by going to File > Project Structure > Project Settings > Facets > Select actionbarsherlock module in 2nd column > Check the "Library module" checkbox > Apply and OK > Save and Rebuild. UPDATE After further review, my original response may be too specific, and will probably only work in certain cases. This error means that the dependencies have not been properly setup. In IntelliJ IDEA, follow these steps to properly setup actionbarsherlock as a module dependency: * *Download and extract the actionbarsherlock library from the zip (Note: You only need the “actionbarsherlock” folder) *Copy and paste it alongside your Android project *Open your project in IntelliJ *File > Project Structure > Project Settings > Modules > Add (green ‘+’ above second column) > Import Module > Select actionbarsherlock directory in file browser dialog > OK > Create module from existing sources > Next *Uncheck the “test” folder so it is not added to the project and click “Next” *Under the Libraries tab, android-support-v4 should be checked, click “Next” *Under the Modules tab, actionbarsherlock should be checked, click “Next” *If it asks you to Overwrite actionbarsherlock.iml, choose “Overwrite” and then "Finish" (You should be returned to the Modules section of the Project Structure dialog) *Select the actionbarsherlock module from the second colum and under the Dependencies tab in the third column, check “Export” next to the android-support-v4 library *Almost there! *Now select your project module from the second column, and under the Dependencies tab, click the Add button (green ‘+’ on the far right side of the dialog) *Select Module Dependency and choose actionbarsherlock from the dialog that pops up and press “OK” *Now click “Apply” or “OK” to accept the changes That should do the trick. A: This is not an answer for the OP's question, but I'll just describe how I managed to get the same exception as he mentions, in the hopes it may help someone else: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Merlinia.MMessaging_Test/com.Merlinia.MMessaging_Test.TestObjectsActivity}: java.lang.IllegalStateException: You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative. In my case the solution was very simple, although it took me way too long to find it. Everything you read about this exception says "check that you've specified the theme in the manifest.xml file", so I took a quick look at my manifest.xml file, and there it was. So then I tried various other things. Finally, I took a closer look at my manifest.xml file. I'd made the mistake of specifying the theme for the main activity, not for the whole application!
{ "language": "en", "url": "https://stackoverflow.com/questions/9757400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: I have a data structure defined as QMap, how may I sort this by value? I have a randomly generated a list of integers and populated a QMap with these values but i would like to get the QMap sorted by value A: This is a demonstration of how to sort a QMap <int, int> by value and not by key in qt C++. The values of the QMap were extracted and stored in a QList container object, then sorted through the qSort method. The keys were also stored in a QList for themselves. After sorting is complete, the QMap object is then cleared and the Keys and values are then inserted back in the QMap container in ascending order by value. See solution below: #include <QCoreApplication> #include <qalgorithms.h> #include <QMap> #include <QDebug> #include <QList> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QMap <int, int> dataMapList; //QMap <int, int> sorted = new QMap<int, int>(); QList <int> keys; // container to store all keys from QMap container QList<int> values; // container to store all values from QMap container QMap<int, int>::Iterator h; // used to loop/ iterate through QMap // used to iterate through QLists QList<int>::Iterator i; // QList<int>::Iterator j; //inserts to QMap Container dataMapList.insert(1,34); dataMapList.insert(3,2); dataMapList.insert(2,32); dataMapList.insert(14,89); dataMapList.insert(7,23); h=dataMapList.begin(); qDebug()<< "unsorted"; //list out the unsorted values along with their respective keys while(h!=dataMapList.end()){ qDebug() << "[" << h.key()<<"], " <<"[" <<h.value()<<"]" << endl; h++; } values = dataMapList.values(); // pass all values in the QMap to a QList container to store values only keys= dataMapList.keys(); // pass all keys in the QMap to a QList container to store already sorted by default keys qSort(values); // sorts the values in ascending order dataMapList.clear(); // empties the QMap i=values.begin(); j=keys.begin(); // insert back the sorted values and map them to keys in QMap container while(i!=values.end() && j!=keys.end()){ dataMapList.insert(*j, *i); i++; j++; } qDebug() << "sorted" << endl; h=dataMapList.begin(); //the display of the sorted QMap while(h!=dataMapList.end()){ qDebug() << "[" << h.key()<<"], " <<"[" <<h.value()<<"]" << endl; h++; } return a.exec(); } Note: The iterators for the QMap and QList were used to traverse through the containers to access the value and/or keys stored. These also helped with displaying the items in the list (unsorted and sorted). This solution was done in a Qt console application. A: In QMap by default the items are always sorted by key. So, if you iterate over QMap like: QMap<int, int>::const_iterator i = yourQMap.constBegin(); while (i != yourQMap.constEnd()) { cout << i.key() << ": " << i.value() << endl; ++i; } You'll get result sorted by keys. Try to think about transforming your task to fit standard algorithms. Otherwise, you can use this approach to get sorted your titles: QList<int> list = yourQMap.values(); qSort(list.begin(), list.end()); And then, if you need -- get associated keys by calling method QMap::key(const T &value);. A: Another alternative, depending on the exact case, is simply to swap the keys and values around since the keys will be automatically sorted by the QMap. In most cases, the values will not be unique, so just use a QMultiMap instead. For example, let's say we have the following data in a QMap: Key Value --- ----- 1 100 2 87 3 430 4 87 The following piece of code will sort the data by value. QMap<int, int> oldMap; QMultiMap<int, int> newMap; QMapIterator<int, int> it(oldMap); while (it.hasNext()) { it.next(); newMap.insertMulti(it.value(), it.key()); //swap value and key } Our new map now looks like this: Key Value --- ----- 87 4 87 2 100 1 430 3
{ "language": "en", "url": "https://stackoverflow.com/questions/13463698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Converting webpage into HTML I want to convert a webpage into an HTML page programatically.I searched many sites but only providing details like converting into pdf format etc.For my program now I'm saving a page as .html and then extracting the necessary data.Is there any way to convert the webpage to an html page? Can anyone help me?Any help would be appreciated. Well I can explain in detail I am extracting the names of users who like a page which i'm admin of . So I found a link https://www.facebook.com/browse/?type=page_fans&page_id=pageid where i can find the list of users. So for getting it first of all i have to save it as a .html page and then extract necessary data. So here I'm converting it into .html and then extract the data. But what I need is that convert that page into an HTML page using my program. I hope my question is clear now A: Oracle provides the following code snippet for programmatically retrieving an html page here. import java.net.*; import java.io.*; public class URLReader { public static void main(String[] args) throws Exception { URL oracle = new URL("http://www.oracle.com/"); BufferedReader in = new BufferedReader( new InputStreamReader(oracle.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } } Instead of printing to console, you can save the contents to a file by using a FileWriter and BufferedWriter (example from this question): FileWriter fstream = new FileWriter("fileName"); BufferedWriter fbw = new BufferedWriter(fstream); while ((line = in.readLine()) != null) { fbw.write(line + "\n"); } A: Webpages are already HTML, if you want to save a webpage as HTML you can do this via the Firefox > Save Page As menu on Firefox. Or through File menu on other browsers. If you need to download multiple pages in HTML from the same website or from a list of URLs there is a software that will make it easier for you: http://www.httrack.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/23267017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: User Pool allows two users with same email despite configuration Background I'm using aws-amplify to interact with Cognito. So when a user registers with my app, I call Auth.signUp(). I'm passing only username (email) and password to this function. My user pool is configured to allow sign in by email only: The Bug? In my front end code, I accidentally registered an event listener twice, so Auth.signUp() was being called twice (concurrently, or at least in rapid succession) with the same parameters. This resulted in two users being created in my User Pool, with the same email. My understanding of my user pool configuration suggests that this shouldn't be possible. Race Condition? My first thought was that since I'm sending two requests so close together, this may be some sort of unavoidable race condition. If I introduce an artificial pause between the calls (a breakpoint, or a setTimeout, say), everything works as expected. However, even with the requests very tightly spaced, the second request does return the error response I'd expect: { code: 'InvalidParameterException', name: 'InvalidParameterException', message: 'Alias entry already exists for a different username' } Sadly, this response is misleading, because I do get a second (duplicate) user created in my pool with this request. MCVE This is easy to reproduce by exercising Auth.signUp twice concurrently, either in a node script or a browser. This repository contains examples of both. The Question(s) * *Is this a legitimate bug with Cognito? *Is a preSignUp Lambda trigger my only way to defend against this? If so, what would the broad strokes of that implementation look like? A: I talked to AWS, still no fix and no time estimation. A: I sent this to AWS support. They're aware of the issue but have no ETA. Thanks for contacting AWS Premium Support. I understand that you would like to know whether Cognito team is aware of the issue posted here[1]. I checked with Cognito team on our end and YES, they are aware of this issue/bug. Good news is, we already have trouble ticket open with Cognito Team to fix the issue. However, I won't be able to provide an ETA on when this fix will go live as I don't have any visibility into their development/release plans. But, I would like to thank you for your valued contribution in bringing this issue to our attention, I do appreciate it. A: Cognito limits usernames to one user only. However, yes multiple user can share an email.
{ "language": "en", "url": "https://stackoverflow.com/questions/50730759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Programmatic import in Python 3? Say I have a directory foo that contains some .py files. Each of these python files has a class Bar defined. Say there were three .py files called baz.py, qux.py and quux.py - then to get the bar classes I could write: import foo.baz import foo.qux import foo.quux bars = [ foo.baz.Bar, foo.qux.Bar, foo.quux.Bar, ] However, rather than list out all the imports like this and all the Bar names, I want to populate bars programmatically. That is, I want to write some code to populate bars that doesn't change as .py files are added or removed from the foo directory. One way to do this might be to use Path('foo').iterdir() to list the .py files, but then how do I do a programmatic import of a string and name its Bar class? Or is there some totally different approach to achieve this? bars = [] for py_file in the directory foo: import foo.py_file ??? bars.append(foo.py_file.Bar) ??? A: Here is one approach using glob module to match the pathnames of the modules we would like to import and importlib's SourceFileLoader to import. from glob import glob from importlib.machinery import SourceFileLoader modules = glob('foo/*.py') bars = list(map(lambda pathname: SourceFileLoader(".", pathname).load_module().Bar, modules)) A: You can use importlib to import the modules dynamically. But you need to find them first. If you include foo.__init__.py in the source, then then foo.__file__ will be that name. You can use that as the base of your glob, but you need to make sure you don't try to import __init__.py itself. This technique is nice because you don't have to worry about another bit of source importing the same module name but getting a different module in memory. from pathlib import Path import importlib import foo def no_magic(paths): for path in paths: if not path.name.startswith("_"): yield path bars = [] for py in no_magic(Path(foo.__file__).resolve().parent.glob("*.py")): mod = importlib.import_module(f"foo.{py.stem}", foo) bars.append(mod.Bar) print(bars)
{ "language": "en", "url": "https://stackoverflow.com/questions/65260813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to install Kafka inside a docker image? I am working on docker for the first time where I am trying to run my pyspark code on a docker container. This my project structure. My Dockerfile content: from gcr.io/datamechanics/spark:platform-3.1-dm14 ENV PYSPARK_MAJOR_PYTHON_VERSION=3 WORKDIR /opt/application/ RUN wget https://jdbc.postgresql.org/download/postgresql-42.2.5.jar RUN mv postgresql-42.2.5.jar /opt/spark/jars COPY requirements.txt . RUN pip3 install -r requirements.txt COPY main.py . COPY tweepy_kafka_producer.py . COPY kafka_spark.py . docker-compose.yml file content: version: '2' services: spark: image: docker.io/bitnami/spark:3 environment: - SPARK_MODE=master - SPARK_RPC_AUTHENTICATION_ENABLED=no - SPARK_RPC_ENCRYPTION_ENABLED=no - SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no - SPARK_SSL_ENABLED=no ports: - '8080:8080' spark-worker: image: docker.io/bitnami/spark:3 environment: - SPARK_MODE=worker - SPARK_MASTER_URL=spark://spark:7077 - SPARK_WORKER_MEMORY=1G - SPARK_WORKER_CORES=1 - SPARK_RPC_AUTHENTICATION_ENABLED=no - SPARK_RPC_ENCRYPTION_ENABLED=no - SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no - SPARK_SSL_ENABLED=no I am trying to read tweets using tweepy library, send them to Kafka & read data from Kafka using Spark streaming. All this is running fine on my local and I trying to learn how can I run the same on a docker container. To do that, I have created a docker container and installed libraries from my requriements.txt file using below commands: curl -LO https://raw.githubusercontent.com/bitnami/bitnami-docker-spark/master/docker-compose.yml docker build -f Dockerfile -t sparkcontainer . My requirements.txt file contains only four packages: pyspark, kafka, python-kafka & tweepy I started the docker image using the steps below (8558b79243f8 is my docker image name): docker run -i -t 8558b79243f8 /bin/bash I do ls and these are the files I see: 185@f4a100a4ad06:/opt/application$ ls kafka_spark.py main.py requirements.txt tweepy_kafka_producer.py When I try to run the python file that pushes data into a kafka topic: 185@f4a100a4ad06:/opt/application$ python tweepy_kafka_producer.py I see the below error message: Traceback (most recent call last): File "tweepy_kafka_producer.py", line 40, in <module> producer = KafkaProducer(bootstrap_servers='localhost:9092') File "/opt/conda/lib/python3.8/site-packages/kafka/producer/kafka.py", line 381, in __init__ client = KafkaClient(metrics=self._metrics, metric_group_prefix='producer', File "/opt/conda/lib/python3.8/site-packages/kafka/client_async.py", line 244, in __init__ self.config['api_version'] = self.check_version(timeout=check_timeout) File "/opt/conda/lib/python3.8/site-packages/kafka/client_async.py", line 900, in check_version raise Errors.NoBrokersAvailable() kafka.errors.NoBrokersAvailable: NoBrokersAvailable I understand that I have to install Kafka in the docker image. Could anyone let me know how can I configure Kafka inside my docker image ? A: Kafka and Spark are distributed processes; and its a bad practice to use more than one process inside a Docker container. Instead, add more services to your existing Docker Compose file, copied from existing Docker Compose setups from Kafka. My requirements.txt file contains only four packages: pyspark, kafka, python-kafka & tweepy You don't need two Kafka dependencies ; you only need pyspark and tweepy since Spark can write to Kafka on its own. Or you could create a 5th (if counting Zookeeper), for a plain Python container with your producer application that has no Spark dependencies
{ "language": "en", "url": "https://stackoverflow.com/questions/71724263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }