_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d2501
train
Does this work: df['ALL'].str.replace('<0.0001','0.00005').astype('float') 0 0.00005 1 0.00005 2 15.20000 3 0.00005 4 0.03000 5 0.00005 6 0.00005 Name: ALL, dtype: float64
unknown
d2502
train
Works fine for me. What error are you getting? pom.xml <?xml version="1.0"?> <project> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>example</artifactId> <version>1.0</version> <repositories> <!-- Added to get the Atmosphere 1.1.0-SNAPSHOT, can be removed when 1.1.0 is released --> <repository> <id>oss.sonatype.org-snapshot</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <dependencies> <dependency> <groupId>org.atmosphere</groupId> <artifactId>atmosphere-runtime</artifactId> <version>1.1.0-SNAPSHOT</version> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </project> Update $ mvn dependency:tree [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building example 1.0 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ example --- [INFO] org.example:example:jar:1.0 [INFO] \- org.atmosphere:atmosphere-runtime:jar:1.1.0-SNAPSHOT:compile [INFO] +- org.atmosphere:atmosphere-compat-jbossweb:jar:1.1.0-SNAPSHOT:compile [INFO] +- org.atmosphere:atmosphere-compat-tomcat:jar:1.1.0-SNAPSHOT:compile [INFO] +- org.atmosphere:atmosphere-compat-tomcat7:jar:1.1.0-SNAPSHOT:compile [INFO] \- eu.infomas:annotation-detector:jar:3.0.1:compile [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.044s [INFO] Finished at: Mon Apr 29 21:46:45 IST 2013 [INFO] Final Memory: 9M/301M [INFO] ------------------------------------------------------------------------ A: Remove content of $HOME/.m2/repository/org/atmosphere/cpr and try again :)
unknown
d2503
train
The DistributionConfig/Origins/ID field should just be a text name, it doesn't need to reference anything. ie. Set DistributionConfig/Origins/ID to a string e.g. 'MyOriginBucket' Then your CacheBehaviour TargetOriginId is also a string set to 'MyOriginBucket' The only Ref required to your new bucket is in Origins/DomainName. The purpose of the TargetOriginId is to point to the origin ID that you specified in the list of Origins, not point to the bucket name.
unknown
d2504
train
PCM merely means that the value of the original signal is sampled at equidistant points in time. For stereo, there are two sequences of these values. To convert them to mono, you merely take piecewise average of the two sequences. Resampling the signal at lower sampling rate is a little bit more tricky -- you have to filter out high frequencies from the signal so as to prevent alias (spurious low-frequency signal) from being created. A: I agree with avakar and nico, but I'd like to add a little more explanation. Lowering the sample rate of PCM audio is not trivial unless two things are true: * *Your signal only contains significant frequencies lower than 1/2 the new sampling rate (Nyquist rate). In this case you do not need an anti-aliasing filter. *You are downsampling by an integer value. In this case, downampling by N just requires keeping every Nth sample and dropping the rest. If these are true, you can just drop samples at a regular interval to downsample. However, they are both probably not true if you're dealing with anything other than a synthetic signal. To address problem one, you will have to filter the audio samples with a low-pass filter to make sure the resulting signal only contains frequency content up to 1/2 the new sampling rate. If this is not done, high frequencies will not be accurately represented and will alias back into the frequencies that can be properly represented, causing major distortion. Check out the critical frequency section of this wikipedia article for an explanation of aliasing. Specifically, see figure 7 that shows 3 different signals that are indistinguishable by just the samples because the sampling rate is too low. Addressing problem two can be done in multiple ways. Sometimes it is performed in two steps: an upsample followed by a downsample, therefore achieving rational change in the sampling rate. It may also be done using interpolation or other techniques. Basically the problem that must be solved is that the samples of the new signal do not line up in time with samples of the original signal. As you can see, resampling audio can be quite involved, so I would take nico's advice and use an existing library. Getting the filter step right will require you to learn a lot about signal processing and frequency analysis. You won't have to be an expert, but it will take some time. A: I don't think there's really the need of reinventing the wheel (unless you want to do it for your personal learning). For instance you can try to use libsnd
unknown
d2505
train
If you want classpath:resources/application-${spring.profiles.active}.yml to be working, setting system properties before refreshing is the way to go. AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.getEnvironment().getSystemProperties().put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev"); applicationContext.scan("com.sample"); applicationContext.refresh(); A: This should do the trick... final AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(); appContext.getEnvironment().setActiveProfiles( "myProfile" ); appContext.register( com.initech.ReleaserConfig.class ); appContext.refresh();
unknown
d2506
train
The problem actually is with the Health Check Intervals (30 seconds) and Threshold (2 checks) which is too frequent when the Task is just starting up and is unable to respond to the HTTP request. So, I increased the interval and the threshold, and everything is fine now!
unknown
d2507
train
I found solution for my problem as follow using ansible module "expect" https://docs.ansible.com/ansible/latest/collections/ansible/builtin/expect_module.html - name: Change password on initial login delegate_to: 127.0.0.1 become: no expect: command: ssh {{ ansible_ssh_common_args }} {{ user_expert }}@{{ inventory_hostname }} timeout: 20 responses: Password: "{{ user_expert_password }}" UNIX password: "{{ user_expert_password }}" New password: "{{ user_expert_password_new }}" new password: "{{ user_expert_password_new }}" "\\~\\]\\$": exit register: status A: You are looking for the user module, especially the password option. Keep in mind, that the password option needs the hash of the actual password. Check here how to get that it. (It needs to be hashed, otherwise you would have a cleartext password in your playbook or inventory which would be a security risk.) Example: - name: ensure password of default user is changed user: name: yourdefaultuser password: '$6$QkjC8ur2WfMfYGA$ZNUxTGoe5./F0b4GJGrcEA.ff9An473wmPsmU4xv00nSrN4D/Nxk8aKro/E/LlQVkUJLbLL6qk2/Lxw5Oxs2m.' Note that the password hash was generated with mkpasswd --method=sha-512 for the password somerandompassword.
unknown
d2508
train
In an N×N symmetric matrix, every entry above the main diagonal has an equal counterpart below the main diagonal. This means that, aside from the N elements on the main diagonal, all elements come in equal pairs. (Elements on the main diagonal can also come in equal pairs, but they're not required to; the matrix's symmetry isn't affected by, for example, whether a22 = a33 or not.) So, you can simply count how often each distinct value occurs, and see how many of the values occur an odd number of times. If there are N or fewer distinct values that occur an odd number of times, then the main diagonal of an N×N matrix can accommodate the unpaired values, so a symmetric matrix is possible; otherwise, not.
unknown
d2509
train
In sails the easiest place would be to remove them with a policy. RemoveParams.js module.exports = function(req, res, next) { if(req.query._dc) delete req.query._dc // ect .... next(); }; Alternate method using undocumented req.options. I have not used this, but it would seem to work and was recommended in the comments. module.exports = function(req, res, next) { req.options.values.blacklist = ['_dc'] // or req.options.values.blacklist.push('_dc') ?? next(); }; If you so choose you could also add your own middleware to replace / remove them as well.
unknown
d2510
train
A quick experiment with Chrome’s inspector shows that this only happens when the page is reloaded, not when it is loaded normally. Chrome is just trying to refresh its cache. Think about it — if you set Expires and Max-Age to several decades, are you asking the browser to cache that resource and never check to see if it gets updated? It’s caching the resource when it can, but when the page needs to be refreshed it wants to make sure that the entire page is refreshed. Other browsers surely do it too (although some have an option for the number of hours to wait before refreshing). Thanks to modern browsers and servers, refreshing a large number of icons won’t be as slow as you think — requests are pipelined to eliminate multiple round-trip delays, and the entire purpose of the If-Modified-Since header is to allow the server to compare timestamps and return a "Not Modified" status code. This will happen for every resource the page needs, but the browser will be able to make all the requests at once and verify that none of them have changed. That said, there are a few things you can do to make this easier: * *In Chrome’s inspector, use the resources tab to see how they are being loaded. If there are no request headers, the resource was loaded directly from the cache. If you see 304 Not Modified, the resource was refreshed but did not need to be downloaded again. If you see 200 OK, it was downloaded again. *In Chrome’s inspector, use the audits tab to see what it thinks about the cacheability of your resources, just in case some of the cache headers aren’t optimal. *All of those If-Modified-Since requests and 304 responses can add up, even though they only consist of headers. Combine your images into sprites to reduce the number of requests. A: Modern browsers are getting more complex and intelligent with their caching behaviour. Have a read through http://blogs.msdn.com/b/ie/archive/2010/07/14/caching-improvements-in-internet-explorer-9.aspx for some examples and more detail. As Florian says, don't fight it :-) A: Have you checked the request headers? "‘Cache-Control’ is always set to ‘max-age=0′, no matter if you press enter, f5 or ctrl+f5. Except if you start Chrome and enter the url and press enter." http://techblog.tilllate.com/2008/11/14/clientside-cache-control/ A: With chrome it matters whether you're refreshing a page or simply visiting it. When you refresh, chrome will ping the server for each file regardless of whether or not they are already cached. If the file hasn't been modified you should see a 304 Not Modified response. If the file has been modified you'll see a 200 OK response instead. When not refreshing, cached files will have a 200 OK status but if you look in the size/content column of the network panel you'll see (from cache). A: Google Chrome will ignore the Expires header if it's not a valid date by the RFC. For instance, it always requires days to be specified as double-digits. 1st of May should be set as "01 May" (not "1 May") and so on. Firefox accepts them, this misleads the user that the problem is at the browser (this case, Chrome) and not the header values themselves. So, if you are setting the expire date manually (not using mod_expires or something similar to calculate the actual date) I recommend you to check your static file headers using REDbot. A: That sounds like it's trying to avoid an outdated cache by asking the server whether the images have changed since it last requested them. Sounds like a good thing, not something you would like to prevent. A: Assuming you are running Apache, you can try explicitly setting up cache lifetimes for certain files types and/or locations in the filesystem. <FilesMatch ".(jpg|jpeg|png|gif)$"> Header set Cache-Control "max-age=604800, public" # 7 days </FilesMatch> or something like ExpiresByType image/jpeg "access plus 7 days" ExpiresByType image/gif "access plus 7 days" ExpiresByType image/png "access plus 7 days" Typically, I will group types of files by use in a single directory and set lifetimes accordingly. Browsers should not request files at all until this ages have expired, but may not always honor it. You may want/need to futz with Last-Modified and ETag headers. There is lots of good info on the web about this.
unknown
d2511
train
well, The problem is your String url_int_details in DetailsActivity just the same as url_act. What can I see in your DetailsActivity is: you use GET method from the "http://10.0.2.2/Scripts/details_intervention.php". And this url is contain a listView as you said but not a detail. So how to solve this problem. You should create new_url_int_details like this: http://10.0.2.2/Scripts/details_intervention.php?id=12 Your url has to contain your item's ID. I made something just like your idea, you can learn more from my project. This is my Detail_Activity: public class FMovieDetailsActivity extends Activity { ArrayList<CinemaItems> cinemaList; String id; TextView tvNameF; TextView tvLengthF; TextView tvIMDbF; TextView tvStartF; TextView tvDescriptionF; TextView tvCatF; TextView tvTrailer; TextView tvLengthTrailer; ListView listView; Button btnTrailer; private Context context; ImageView f_imageTrailer; ImageView f_imageView; private static final String TAG_ID = "id"; private static final String TAG_FUTURE_MOVIE = "future_movie"; private static final String TAG_NAME_F = "movienameF"; private static final String TAG_DESCRIPTION_F = "descriptionF"; private static final String TAG_IMDB_F = "imdbF"; private static final String TAG_LENGTH_F = "lengthF"; private static final String TAG_CAT = "cat_name"; private static final String TAG_IMAGE_F = "m_imageF"; private static final String TAG_SUCCESS_F = "success"; private static final String TAG_START_F = "startdateF"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.moviedetails); cinemaList = new ArrayList<CinemaItems>(); Intent i = getIntent(); id = i.getStringExtra(TAG_ID); new JSONAsyncTask().execute(); tvNameF = (TextView) findViewById(R.id.tvMovieName); tvLengthF = (TextView) findViewById(R.id.tvLength); tvIMDbF = (TextView) findViewById(R.id.tvIMdb); tvStartF = (TextView) findViewById(R.id.tvStartDate); tvDescriptionF = (TextView) findViewById(R.id.tvDescription); tvCatF = (TextView) findViewById(R.id.tvCategory); f_imageView = (ImageView) findViewById(R.id.imageMovieDetail); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } class JSONAsyncTask extends AsyncTask<String, String, String> { ProgressDialog dialog; @Override protected void onPreExecute() { super.onPreExecute(); dialog = new ProgressDialog(FMovieDetailsActivity.this); dialog.setMessage("Loading, please wait"); dialog.setTitle("Connecting server"); dialog.show(); dialog.setCancelable(false); } @Override protected String doInBackground(String... urls) { try { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(TAG_ID, id)); Log.i("show parse id", id); String paramString = URLEncodedUtils.format(params, "utf-8"); //this is your problem, You lack of this url String url = ServicesConfig.SERVICES_HOST + ServicesConfig.SERVICES_GET_FUTURE_DETAILS + "?" + paramString; Log.i("show url", url); HttpGet httpget = new HttpGet(url); HttpClient httpClient = new DefaultHttpClient(); HttpResponse respone = httpClient.execute(httpget); HttpEntity entity = respone.getEntity(); return EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String respone) { try { JSONObject jsono = new JSONObject(respone); int success = jsono.optInt(TAG_SUCCESS_F, 0); if (success == 1) { JSONObject jsonObject = jsono.getJSONObject(TAG_FUTURE_MOVIE); tvNameF.setText(jsonObject.optString(TAG_NAME_F)); tvIMDbF.setText("IMDb: " + jsonObject.optString(TAG_IMDB_F)); tvLengthF.setText("Duration: " + jsonObject.optString(TAG_LENGTH_F)); tvStartF.setText("Start: " + jsonObject.optString(TAG_START_F)); tvDescriptionF.setText(jsonObject.optString(TAG_DESCRIPTION_F)); tvCatF.setText(jsonObject.optString(TAG_CAT)); Picasso.with(context).load(ServicesConfig.SERVICES_HOST + jsonObject.optString(TAG_IMAGE_F)).fit() .into(f_imageView); } else { Toast.makeText(getBaseContext(), "Unable to fetch data from server", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } dialog.dismiss(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); return true; } return super.onOptionsItemSelected(item); } } This is my php file: <?php $response = array(); require_once __DIR__ . '/db_connect.php'; $db = new DB_CONNECT(); if (isset($_GET["id"])) { $id = $_GET['id']; $result = mysql_query("SELECT m.*, c.cat_name FROM future_movie as m inner join category as c on m.cat_id = c.cat_id WHERE m.id = $id"); $img = "test_cinema/images/product/"; if (!empty($result)) { if (mysql_num_rows($result) > 0) { $result = mysql_fetch_array($result); $movie = array(); $movie["id"] = $result["id"]; $movie["movienameF"] = $result["movienameF"]; $movie["descriptionF"] = $result["descriptionF"]; $movie["imdbF"] = $result["imdbF"]; $movie["lengthF"] = $result["lengthF"]; $movie["startdateF"] = $result["startdateF"]; $movie["cat_name"] = $result["cat_name"]; $movie["m_imageF"] = $img.$result["m_imageF"]; $response["success"] = 1; $response["future_movie"] = $movie; echo json_encode($response); } else { $response["success"] = 0; $response["message"] = "No movie found"; echo json_encode($response); } } else { $response["success"] = 0; $response["message"] = "No movie found"; echo json_encode($response); }} else { $response["success"] = 0; $response["message"] = "Required field(s) is missing"; echo json_encode($response);}?>
unknown
d2512
train
Are you using a mac? OS X has a system-wide preference which Firefox honors (Chrome does not) that changes the behavior of the tab key in windows and dialogs. It is probably set to tab only to text boxes -- skipping anchor tags. Search System Preferences for "full keyboard access" and you'll find it, or refer to the screenshot below: . Set to "All Controls" to make Firefox behave like Chrome on OSX.
unknown
d2513
train
Ages later, I know but I believe you are hitting this: ASP.Net Core Logging and DebugView.exe I spent 3 hours on this one today and feel your paint TL;DR: Debugger.IsAttached is checked within Microsoft.Extensions.Logging.Debug.
unknown
d2514
train
I’m not sure if it is a recent addition, but the Datadog public API supports configuring Log Archives: https://docs.datadoghq.com/api/latest/logs-archives/ You can also use tools like Terraform to configure them: https://registry.terraform.io/providers/DataDog/datadog/latest/docs/resources/logs_archive (it uses the Datadog API internally)
unknown
d2515
train
I wouldn't do that. * *A ZIP code can contain two different towns, each with a "#123 Main Street" address. *A ZIP code may cross state lines, which means you don't have enough information for shipping/tax details. *You'll have a very hard time dealing with any customers who live outside of the USA. A: Marcin, There is not a one to one relationship between city and zipcode. A city can have multiple zipcodes. A zipcode can cross city lines. Brian
unknown
d2516
train
You can't, because picklable object's class definitions must reside in an imported module's scope. Just put your class inside module scope and you are good to go. That said, in Python there is very little that can't be achieved with a bit of hacking the insides of the machinery (sys.modules in this case), but I wouldn't recommend that. A: The MyClass definition is local variable for the func function. You cannot directly create an instance of it, but you can map it's functions to a new class, and then to use the new class as it is the original one. Here's an example: def func(params): class MyClass(object): some_param = 100 def __init__(self, *args): print "args:", args def blabla(self): self.x = 123 print self.some_param def getme(self): print self.x func.func_code is the code of the func function, and func.func_code.co_consts[2] contains the bytecode of the MyClass definition: In : func.func_code.co_consts Out: (None, 'MyClass', <code object MyClass at 0x164dcb0, file "<ipython-input-35-f53bebe124be>", line 2>) So we need the bytecode for the MyClass functions: In : eval(func.func_code.co_consts[2]) Out: {'blabla': <function blabla at 0x24689b0>, '__module__': '__main__', 'getme': <function getme at 0x2468938>, 'some_param': 100, '__init__': <function __init__ at 0x219e398>} And finally we create a new class with metaclass, that assigns the MyClass functions to the new class: def map_functions(name, bases, dict): dict.update(eval(func.func_code.co_consts[2])) return type(name, bases, dict) class NewMyClass(object): __metaclass__ = map_functions n = NewMyClass(1, 2, 3, 4, 5) >> args: (1, 2, 3, 4, 5) n.blabla() >> 100 n.getme() >> 123 A: You can work around the pickle requirement that class definitions be importable by including the class definition as a string in the data pickled for the instance and exec()uting it yourself when unpickling by adding a __reduce__() method that passes the class definition to a callable. Here's a trivial example illustrating what I mean: from textwrap import dedent # Scaffolding definition = dedent(''' class MyClass(object): def __init__(self, attribute): self.attribute = attribute def __repr__(self): return '{}({!r})'.format(self.__class__.__name__, self.attribute) def __reduce__(self): return instantiator, (definition, self.attribute) ''') def instantiator(class_def, init_arg): """ Create class and return an instance of it. """ exec(class_def) TheClass = locals()['MyClass'] return TheClass(init_arg) # Sample usage import pickle from io import BytesIO stream = BytesIO() # use a memory-backed file for testing obj = instantiator(definition, 'Foo') # create instance of class from definition print('obj: {}'.format(obj)) pickle.dump(obj, stream) stream.seek(0) # rewind obj2 = pickle.load(stream) print('obj2: {}'.format(obj2)) Output: obj: MyClass('Foo') obj2: MyClass('Foo') Obviously it's inefficient to include the class definition string with every class instance pickled, so that redundancy may make it impractical, depending on the the number of class instances involved. A: This is somewhat tough to do because the way Pickle does with objects from user defined classes by default is to create a new instance of the class - using the object's __class__.__name__ attribute to retrieve its type in the object's original module. Which means: pickling and unpickling only works (by default) for classes that have well defined names in the module they are defined. When one defines a class inside a function, usulay there won't be a module level (i.e. global) variable holding the name of each class that was created inside the function. The behavior for pickle and npickle can be customized through the __getstate__ and __setstate__ methods on the class - check the docs - but even them, doing it right for dynamic class can be tricky , but I managed to create a working implementation of it for another S.O. question - -check my answer here: Pickle a dynamically parameterized sub-class
unknown
d2517
train
I'd recommend you to not to use Realm before you have an authenticated user, you can show some login view to handle authentication and show your other view controller after user is authenticated. // LogInViewController ... func logIn() { SyncUser.authenticate(with: credential, server: serverURL) { user, error in if let user = user { Realm.Configuration.defaultConfiguration = Realm.Configuration( syncConfiguration: (user, syncURL) ) // Show your table view controller or use `try! Realm()` } else { // Present error } } } Please check also RealmTasks example here: https://github.com/realm/RealmTasks
unknown
d2518
train
I can give you some steps to check and follow and a sample project in github: * *Check in persistence.xml <persistence-unit name="testPersistenceUnit" transaction-type="JTA"> ... <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode> <properties> ... <property name="hibernate.cache.use_second_level_cache" value="true"/> <property name="hibernate.cache.use_query_cache" value="true"/> <property name="hibernate.cache.region_prefix" value="hibernate.test"/><!-- Optional --> <!-- Use Infinispan second level cache provider --> <property name="hibernate.cache.region.factory_class" value="org.infinispan.hibernate.cache.v53.InfinispanRegionFactory"/> <!-- Optional: Initialize a caches (for standalone mode / test purpouse) --> <property name="hibernate.cache.infinispan.cfg" value="META-INF/infinispan-configs-local.xml"/> ... </properties> </persistence> PS: "org.infinispan.hibernate.cache.v53.InfinispanRegionFactory" package depends on your maven dependencies and Hibernate version. *If you want to use JCache interceptors. Add to beans.xml: <interceptors> <class>org.infinispan.jcache.annotation.InjectedCacheResultInterceptor</class> <class>org.infinispan.jcache.annotation.InjectedCachePutInterceptor</class> <class>org.infinispan.jcache.annotation.InjectedCacheRemoveEntryInterceptor</class> <class>org.infinispan.jcache.annotation.InjectedCacheRemoveAllInterceptor</class> </interceptors> PS. Take in mind, that Infinispan have a variant without "Injected" in the name of the Interceptors for environments where the cache manager is not injected in a managed environment. *Check that your cache is configured (in your application server) or your cdi producer. Eg. @ApplicationScoped public class CacheConfigProducer { @Produces public Configuration defaultCacheConfiguration() { return new ConfigurationBuilder().simpleCache(false).customInterceptors().addInterceptor() .interceptor(new TestInfinispanCacheInterceptor()).position(Position.FIRST).expiration().lifespan(60000l) .build(); } } *Add to your repository your hints like you are adding: @Eager public interface CacheableReadWriteRepository extends ReadWriteRepository<CacheableEntity, Integer>{ @QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true")}) List<CacheableEntity> findByValue(Integer value); } *Take care to add @Cacheable to your entity You have this project with Spring Data JPA and CDI integration (spring-data-jpa with cdi). It has tests with JCache, Hibernate 2nd level cache and query cache. I hope it helps.
unknown
d2519
train
Create a new table called Dependencies. It should have two ID fields (both are Foreign Keys): Project1ID and Project2ID. You can include whatever other columns in this table you feel are relevant. Create one record in the new table for each dependency between one project and another. A: Hope this is self-explanatory.
unknown
d2520
train
Based on the error snippet shared during the artifact download from the Artifactory application, it looks like there is a connectivity issue from the client(your computer) to Artifactory. You can validate the connectivity using the telnet from your computer to connect to the Artifactory IP/port. Also, you can validate the Artifactory request logs to check whether the request is reaching the application or not.
unknown
d2521
train
I solved the problem in this way in pom.xml I excluded xnio-api (as in the question) <dependency> <groupId>org.wildfly</groupId> <artifactId>wildfly-jms-client-bom</artifactId> <version>10.1.0.Final</version> <type>pom</type> <exclusions> <exclusion> <groupId>org.jboss.xnio</groupId> <artifactId>xnio-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.wildfly</groupId> <artifactId>wildfly-naming-client</artifactId> <version>1.0.15.Final</version> <exclusions> <exclusion> <groupId>org.jboss.xnio</groupId> <artifactId>xnio-api</artifactId> </exclusion> </exclusions> </dependency> Then I created jboss-deployment-structure.xml under webapp/WEB-INF folder, with this content <jboss-deployment-structure> <ear-subdeployments-isolated>true</ear-subdeployments-isolated> <deployment> <dependencies> <module name="org.jboss.xnio" /> </dependencies> </deployment> </jboss-deployment-structure> now the WAR is deployed with no problems Hope this help
unknown
d2522
train
Use DiscardOldestPolicy : A handler for rejected tasks that discards the oldest unhandled request and then retries execute, unless the executor is shut down, in which case the task is discarded. and BlockingQueue with fixed capacity: int fixedThreadNumber = 10; int idleSeconds = 10; BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(10); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( fixedThreadNumber, fixedThreadNumber, idleSeconds, TimeUnit.SECONDS, blockingQueue, new ThreadPoolExecutor.DiscardOldestPolicy()); ExecutorService executor = threadPoolExecutor;
unknown
d2523
train
I guess you are not following the named route documentation properly. Your route: Route::get('Apply1/show1/{id}', function ($id) { return 'User '.$id; }); According to the documentation, you need to add name at the end of the route. That means, you should add it like this.. Route::get('Apply1/show1/{id}', function ($id) { return 'User '.$id; })->name('Apply1.show1'); // you had not written this In this way, you will get your desired result.
unknown
d2524
train
I think you have overly complicated your code, You are using angular and I believe its not a good practice to access DOM elements using document.getElementById(). For your code to work, you will need to ensure that the view has loaded before you can access the DOM elements. You need to move your code to the AfterViewInit life cycle hook. Below is how I would refactor the code <th *ngFor="let column of columns;" <ng-container *ngIf="column?.sortable"> <span [class.sorting_asc]="column?.sortable" (click)="sortArray(column?.field)"></span> </ng-container> </th> We simply bind to [class.sorting_asc]="column?.sortable" and let angular apply the classes for us
unknown
d2525
train
According the documentation of the method that you are using, you need to send a list of tags, so change the string by a list like this: client = SoftLayer.Client() mgr = SoftLayer.VSManager(client) for vsi in mgr.list_instances(tags = ['mytag']): print (vsi['hostname']) Regards
unknown
d2526
train
You should use parenthesis with link_to arguments. Ruby except a : but instead he find @entry.user.nickname. rewrite your ternary operator like that : boolean_output ? link_to(arguments,arguments) : "something else" A: Try this: <%= @entry.user.present? ? (link_to @entry.user.nickname, account_path(:user_id=>@entry.user,:key=>"check" ), :"data-ajax" => false) : "123ish" %>
unknown
d2527
train
The solution is to use res['myParam'] and res['operation'] It should look like this: this.activatedRoute.data.subscribe(res => { const myAttribute = res['myParam']; });
unknown
d2528
train
There is a LSL module for Python called pylsl. You should be able to incorporate this into your game loop. The following code was adapted from this example: from pylsl import StreamInlet, resolve_stream import pygame # first resolve an EEG stream on the lab network streams = resolve_stream('type', 'EEG') # create a new inlet to read from the stream inlet = StreamInlet(streams[0]) # Pygame setup pygame.init() size = width, height = 320, 240 screen = pygame.display.set_mode(size) samples = [] while True: # get a new sample (you can also omit the timestamp part if you're not # interested in it) # Get a sample from the inlet stream sample, timestamp = inlet.pull_sample() samples.push(sample) #TODO: interpolate streamed samples and update game objects accordingly. # You'll probably need to keep a few samples to interpolate this data. #TODO: draw game ... pygame.display.flip() A: Adding another possibility: engineers from the Foundation Campus Biotech Geneva have created a library using LSL for an online paradigm using EEG, called NeuroDecode. It relies on pylsl and offers a higher-level implementation. On my fork version, I dropped the (old) decoding functionalities in favor of improvements to the low-level functionalities, e.g. signal acquisition/visualization. https://github.com/mscheltienne/NeuroDecode
unknown
d2529
train
If you don't know what extern means, please find a book to learn C from. It simply means 'defined somewhere else, but used here'. The environ global variable is unique amongst POSIX global variables in that it is not declared in any header. It is like the argv array to the program, an array of character pointers each of which points at an environment variable in the name=value format. The list is terminated by a null pointer, just like argv is. There is no count for the environment, though. for (var = environ; *var != NULL; ++var) printf("%s\n", *var); So, on the first iteration, var points at the first environment variable; then it is incremented to the next, until the value *var (a char *) is NULL, indicating the end of the list. That loop could also be written as: char **var = environ; while (*var != 0) puts(*var++); A: From wikipedia http://en.wikipedia.org/wiki/External_variable: Definition, declaration and the extern keyword To understand how external variables relate to the extern keyword, it is necessary to know the difference between defining and declaring a variable. When a variable is defined, the compiler allocates memory for that variable and possibly also initializes its contents to some value. When a variable is declared, the compiler requires that the variable be defined elsewhere. The declaration informs the compiler that a variable by that name and type exists, but the compiler need not allocate memory for it since it is allocated elsewhere. The extern keyword means "declare without defining". In other words, it is a way to explicitly declare a variable, or to force a declaration without a definition. It is also possible to explicitly define a variable, i.e. to force a definition. It is done by assigning an initialization value to a variable. If neither the extern keyword nor an initialization value are present, the statement can be either a declaration or a definition. It is up to the compiler to analyse the modules of the program and decide. A variable must be defined once in one of the modules of the program. If there is no definition or more than one, an error is produced, possibly in the linking stage. A variable may be declared many times, as long as the declarations are consistent with each other and with the definition (something which header files facilitate greatly). It may be declared in many modules, including the module where it was defined, and even many times in the same module. But it is usually pointless to declare it more than once in a module. An external variable may also be declared inside a function. In this case the extern keyword must be used, otherwise the compiler will consider it a definition of a local variable, which has a different scope, lifetime and initial value. This declaration will only be visible inside the function instead of throughout the function's module. The extern keyword applied to a function prototype does absolutely nothing (the extern keyword applied to a function definition is, of course, non-sensical). A function prototype is always a declaration and never a definition. Also, in ANSI C, a function is always external, but some compiler extensions and newer C standards allow a function to be defined inside a function. An external variable must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it; this states the type of the variable. The declaration may be an explicit extern statement or may be implicit from context. ... You should note that we are using the words definition and declaration carefully when we refer to external variables in this section. Definition refers to the place where the variable is created or assigned storage; declaration refers to places where the nature of the variable is stated but no storage is allocated. —The C Programming Language Scope, lifetime and the static keyword An external variable can be accessed by all the functions in all the modules of a program. It is a global variable. For a function to be able to use the variable, a declaration or the definition of the external variable must lie before the function definition in the source code. Or there must be a declaration of the variable, with the keyword extern, inside the function. The static keyword (static and extern are mutually exclusive), applied to the definition of an external variable, changes this a bit: the variable can only be accessed by the functions in the same module where it was defined. But it is possible for a function in the same module to pass a reference (pointer) of the variable to another function in another module. In this case, even though the function is in another module, it can read and modify the contents of the variable—it just cannot refer to it by name. It is also possible to use the static keyword on the definition of a local variable. Without the static keyword, the variable is automatically allocated when the function is called and released when the function exits (thus the name "automatic variable"). Its value is not retained between function calls. With the static keyword, the variable is allocated when the program starts and released when the program ends. Its value is not lost between function calls. The variable is still local, since it can only be accessed by name inside the function that defined it. But a reference (pointer) to it can be passed to another function, allowing it to read and modify the contents of the variable (again without referring to it by name). External variables are allocated and initialized when the program starts, and the memory is only released when the program ends. Their lifetime is the same as the program's. If the initialization is not done explicitly, external (static or not) and local static variables are initialized to zero. Local automatic variables are uninitialized, i.e. contain "trash" values. The static keyword applied to a function definition prevents the function from being called by name from outside its module (it remains possible to pass a function pointer out of the module and use that to invoke the function). Example (C programming language) File 1: int GlobalVariable; // implicit definition void SomeFunction(); // function prototype (declaration) int main() { GlobalVariable = 1; SomeFunction(); return 0; } File 2: extern int GlobalVariable; // explicit declaration void SomeFunction() { // function header (definition) ++GlobalVariable; } In this example, the variable GlobalVariable is defined in File 1. In order to utilize the same variable in File 2, it must be declared. Regardless of the number of files, a global variable is only defined once, however, it must be declared in any file outside of the one containing the definition. If the program is in several source files, and a variable is defined in file1 and used in file2 and file3, then extern declarations are needed in file2 and file3 to connect the occurrences of the variable. The usual practice is to collect extern declarations of variables and functions in a separate file, historically called a header, that is included by #include at the front of each source file. The suffix .h is conventional for header names. A: Extern defines a variable or a function that can be used from other files... I highly advise reading some of the many articles available on the Internet on C programming: https://www.google.ca/search?client=opera&rls=en&q=learn+c&sourceid=opera&ie=utf-8&oe=utf-8&channel=suggest A: extern char **environ; the variable environ comes from your library which you will link. That variable saved the system environment variables of your current linux system. That's why you can do so.
unknown
d2530
train
I would solve this using CSS instead. like this fiddle Example html: <div class=tab-bottom> <div class=tab-bottom-content> Test </div> </div> CSS: .tab-bottom{ border: 1px SOLID #F00; /* For display purpose */ width: 200px; height: 200px; } .tab-bottom.tab-bottom-content{ display: none; } .tab-bottom:hover .tab-bottom-content{ display: block; } There is no need for JavaScript or jQuery here :) A: You should initially hide .tab-bottom-content using display: none like following. .tab-bottom-content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: none } And the use following jQuery. You missed the . before tab-bottom-content $(".tab-bottom").mouseover(function(event){ $(this).find(".tab-bottom-content").show(300); }).mouseleave(function(e) { $(this).find(".tab-bottom-content").hide(300); }); A: You need '.' in this .find("tab-bottom-content") $(".tab-bottom").on('mouseover',function(event){ $(this).find(".tab-bottom-content").show(300); }); $('.tab-bottom').on('mouseleave', function(e) { $(this).find(".tab-bottom-content").hide(300); }); Here is the pen You must also add CSS .tab-bottom-content { display:none; } or inline style to hide the 'tab-bottom-content' content first A: You can set the opacity of the tab-bottom-content to 0 and then change it to 1 in its :hover pseudo-selector class so that the text appears when you hover over the tab-bottom-content div. You may even want to add a transition so that the opacity changes smoothly. Do this, .tab-bottom-content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 1px solid black; opacity: 0; transition: opacity .4s ease-in; } .tab-bottom-content:hover { opacity: 1 } Check it out https://jsfiddle.net/5s1fv2a9/
unknown
d2531
train
You don't normally get a MethodNotAllowedException from an invalid CSRF token. I normally get a 419 response from CSRF issues. However, assuming the CSRF token is the problem you could move your route from web.php to api.php. Be aware this adds the prefix api/ to the URL. The middleware that checks the CSRF token is applied in your Kernel to all routes in web.php but not to those is api.php You could verify whether the CSRF check is really the problem by looking in your App\Http\Kernel file and commenting out \App\Http\Middleware\VerifyCsrfToken::class from: protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; If your route then works it is CSRF and you can move the route to the API routes file and hit it at api/pay/finish with the api prefix. If not then I suggest you look at what's calling your route and check the correct http method is being called. Is it definitely sending a POST request? Do you have the _method input specified in your form that Laravel checks for POST requests to mutate them to PUT or PATCH for its edit routes?
unknown
d2532
train
Microsoft released a new tool a few weeks ago called mssql-scripter that's the command line version of the "Generate Scripts" wizard in SSMS. It's a Python-based, open source command line tool and you can find the official announcement here. Essentially, the scripter allows you to generate a T-SQL script for your database/database object as a .sql file. You can generate the file and then execute it. This might be a nice solution for you to generate the schema of your db (schema is the default option). Here's a quick usage example to get you started: $ pip install mssql-scripter # script the database schema and data piped to a file. $ mssql-scripter -S localhost -d AdventureWorks -U sa > ./adventureworks.sql More usage examples are on our GitHub page here: https://github.com/Microsoft/sql-xplat-cli/blob/dev/doc/usage_guide.md A: From this answer, there appear to be tools called SMOScript and ScriptDB that can do that. If you find a way without third party tools please share :)
unknown
d2533
train
Make sure that you actually have a route to the internet from your EC2 instance. That typically means either a public IP or a route to a NAT instance/gateway, and an Internet Gateway in your VPC. It may be that the userdata script begins to run before connectivity has been established. You may need to verify that the instance has outbound network access before your script runs yum update, for example: #!/bin/bash echo "launch script.." until ping -c1 www.google.com &>/dev/null; do echo "Waiting for network ..." sleep 1 done yum update -y # other things here There are other options to wait for the network (here and here). Also note that user data scripts are executed as the root user, so you do not need sudo.
unknown
d2534
train
Your CompareTo implementation is definitely not going to work here. You return 0 when two objects are equal (which is good), but if they are not equal, you always return -1. This means that the first one is smaller than the last one. However, this is not going to work. If you have objects a and b, then your comparison is saying that a < b and b < a (which is breaking the requirements on the ordering relation). The F# set requires the objects to be orderable, because it keeps the data in a balanced tree (where smaller elements are on the left and greater are on the right) - so with CompareTo that always returns -1, it ends up creating a tree that makes no sense. Why do you want to implement custom comparison for the type? I suppose you're doing that to only consider some of the fields and ignore some others. There is actually a nice trick you can do in this case, which is to create a tuple with the fields you're interested and call the built-in hash and compare functions on them. For example: compare (x.Id, x.Name, x.Bars.Head.Name) (y.Id, y.Name, y.Bars.Head.Name) This will use default F# comparison on the tuples, which is a correctly defined ordering relation.
unknown
d2535
train
The easiest way is to use a dependency tied to your value. keyDep = new Deps.Dependency() Template.foo.events 'click #link': -> localStorage.setItem 'key', 'different' keyDep.changed() Template.foo.key = -> keyDep.depend() return localStorage.getItem 'key'
unknown
d2536
train
Do as below: product["product"].each do |prod| puts prod[:title] end A: product["product"].each { |p| puts p[:title] }
unknown
d2537
train
Your file contain the characters '0' and '5'. Note that the ASCII code for '0' is 48. You are reading the values of the bytes, not the number represented. If you had an 'A' in the file, you would have the byte 65. Your approach works for manually converting numeric characters into a number (although you might one some extra checking, it will break if it doesn't contain two numbers). Or you could use a function like atoi() which converts a numeric string into the number.
unknown
d2538
train
Use formData to upload file. HTML: <input type="file" id="filechooser"> Javascript Code function uploadFile() { var blobFile = $('#filechooser').files[0]; var formData = new FormData(); formData.append("fileToUpload", blobFile); $.ajax({ url: "upload.php", type: "POST", data: formData, processData: false, contentType: false, success: function(response) { // .. do something }, error: function(jqXHR, textStatus, errorMessage) { console.log(errorMessage); // Optional } }); } Compatibility: http://caniuse.com/xhr2
unknown
d2539
train
With NI, it's "RTFMs" When programming NI devices, you usually need two manuals. * *NI-DAQmx Help (for the programming part) *the device specification (for the device part) You need both because the NI-DAQmx API supports every DAQ device NI makes, but not every device has the same capabilities. "Capabilities" includes more than how many channels of each kind, but also the timing and triggering subsystems as well as internal signal routing. A DAQmx application that runs with one device is not guaranteed to run with another because the application might use the API in a way the second device cannot support. Finally, on the documentation front, any given NI DAQ device typically belongs to family of related devices and these families also have a manual called User Guide. These User Guides act as a bridge between the API and device spec, helping you understand how the device responds to commands. For the 6002, the family is "Low-Cost DAQ USB Device". Analog trigger for analog output on NI 6002 Your determination is correct that writeLED.triggers.start_trigger.cfg_anlg_edge_start_trig(V_PIN,trigger_level = 0) is possible, just not for the USB 6002. This line is asking the analog output subsystem to use an analog edge trigger, but the analog output subsystem for the 6002 only has these trigger capabilities: * *software *PFI 0 *PFI 1 For this device, you're only option is the software trigger because the PFI lines are digital triggers and their trigger level is specified to be between 0.8 V and 2.3 V. Change your Python program to detect a zero-crossing from the analog input stream and, when it does, make it call stop() and then start() on the AO task. The reason for the stop-start sequence is retriggering: you want to light the LED for each zero crossing, but a task cannot be restarted unless it has either been stopped (by the API or by completing its task) or configured for retriggering. Because the 6002 is in the low-cost family, this hardware feature isn't available, so you must use the API to stop the AO task or wait for the AO generation to complete before restarting the pulse for the LED 6002 AO Specification A: Software triggering is not real-time, you will have non-deterministic delay before the led turns on. This depends on your program, interfaces, usb latencies, pc performances... Otherwise, you can use a comparator (like lm393) to trigger a digital input (PFI0 or PFI1). Though it's just an LED, it is probably not critical if the delay varies within milliseconds.
unknown
d2540
train
Try this : it("Should login user", () => { loginService.login("[email protected]", "123456").subscribe(value => { let loggedIn = loginService.loggedIn(); expect(loggedIn).toBe(true); done(); }); })
unknown
d2541
train
you can use the follow commands: adb shell cat /sys/class/net/wlan0/address #mac address adb get-serialno #serial number adb shell cat /data/misc/wifi/*.conf #wifi passward
unknown
d2542
train
The reason for that is probably due to the fact that the appended elements do not have their CSS rules applied yet and are not counting towards the total height. Try using a delay (like settimeout) to make things work right. var h = $("#otherid").delay(300).outerHeight(); A: Instead: id='#otherid' try: id='otherid' $("#someid").append("<ul id='otherid'><li>something</li></ul>"); var h = $("#otherid").outerHeight();
unknown
d2543
train
I think that you need to do an array for your select : <select name="countries[]" multiple> And then deal with the array in your php code. A: PHP determines if form data should be presented as a string or an array based on the name of the field, not the number of times it appears. Append [] to the name attribute in the HTML.
unknown
d2544
train
What kind of data you are receiving in data.countryList? Can u post that data? I hope there is no attr property named list for dropdown. List property provided by Struts. You can compose the data for dropdown like <option value="1">India</option> <option value="2">United States</option> <option value="3">United Kingdom</option> and if you are sending new list you can do fill the countryList like, $('#pqr').html(composed_country_list); Else you are updating counrty means you can append the data to dropdown like, $('#pqr').append(composed_country_list); Let me know if this helps.. A: The following code worked for me //JSP <s:select list="{}" name="fightId" id="pqr"></s:select> Script File $(document).ready(function() { $("#capacity").change(function() { var capacity = $("#capacity").val(); $.getJSON('CheckUserAction.action', { capacity : capacity }, function(data) { countryListItem = data.countryList; }); return false; }); }); var pqr = $('#pqr'); pqr.find('option').remove(); pqr.append('<option value=-1>--Select--</option>'); for(var i = 0; i < countryListItem .length; i++) { var opt = document.createElement('option'); opt.innerHTML = countryListItem [i]; opt.value = countryListItem [i]; pqr.append(opt); } Used javascript to populate the list by creating option attribute. The struts select tag actually generates this kind of HTML internally.
unknown
d2545
train
Could you let me know why that solution not fit for your problem? seems is ok to get the username. however, maybe you can try this <?php $url = parse_url('http://localhost:3001/users/yourname',PHP_URL_PATH); $url = str_replace("/users/","",$url); echo $url; ?> A: You can use: $url_path = parse_url('http://localhost:3001/users/a13/abc',PHP_URL_PATH); $url = preg_replace("/\/(?:[^\/]*\/)*/","",$url_path); echo $url; output: abc demo: https://regex101.com/r/19x7ut/1/ or this regex: \/(?:[^\/\s]*\/)* demo: https://regex101.com/r/19x7ut/3/ both should work fine.
unknown
d2546
train
You can try to make it an object with $myObject = json_decode($responseJSON); and you can take value with echo $myObject['articles'][0]->title; with foreach: foreach($myObject['articles'] as $key => $value) { echo $value->title . ", " . $value->slug . "<br>"; }
unknown
d2547
train
NLog is thread-safe, so you can safely reuse your logger. You can make it Singleton.
unknown
d2548
train
As Sven suggested, https://stackoverflow.com/questions/4742877/center-align-div-in-internet-explorer likely holds your answer. Either you've got non-valid HTML that is putting IE7 in quirks mode, or you're missing the doctype. A: Try this <style type="text/css"> body, html { font-family:helvetica,arial,sans-serif; font-size:90%; } div.outer { display: block; margin:0 auto; width:970px; height:630px; position:relative; } </style> A: Use code with proper doc type. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
unknown
d2549
train
The structure for SMSReturned is missing some elements. Try this: public class WLAuth { public string userid { get; set; } public string password { get; set; } } public class SMSReturned { public WLAuth wlauth { get; set; } public string Ident { get; set; } public string identtype { get; set; } public string message { get; set; } public string userid { get; set; } public string password { get; set; } } and this: public IHttpActionResult ReceiveSMSData(SMSReturned data) { Debug.WriteLine(data.wlauth.userid); Debug.WriteLine(data.wlauth.password); Debug.WriteLine(data.Ident); Debug.WriteLine(data.identtype); Debug.WriteLine(data.message); return Ok(); }
unknown
d2550
train
Sharing an H2 database As of Corda 3, each node spins up its own H2 database by default. However, you can point multiple nodes to a single, stand-alone H2 database as follows: * *Start a standalone H2 instance (e.g. java -jar ./h2/bin/h2-1.4.196.jar -webAllowOthers -tcpAllowOthers) *In the node.conf node configuration file, set dataSource.url = "jdbc:h2:tcp://localhost:9092/~/nodeUniqueDatabaseName", where nodeUniqueDatabaseName is unique to that node For each nodeUniqueDatabaseName, H2 will create a file nodeUniqueDatabaseName.mv.db in the user's home directory. You can also set a specific absolute path as well (e.g. dataSource.url = "jdbc:h2:tcp://localhost:9092/~/Users/szymonsztuka/IdeaProjects/corda3/nodeUniqueDatabaseName"). This will create a database file under Users/szymonsztuka/IdeaProjects/corda3/. Note that this approach is not secure since the h2 server is started with -webAllowOthers -tcpAllowOthers, meaning that anyone can log in and modify the database. Maintaining data across node builds The H2 database is discarded when re-running deployNodes, because you are considered to be creating an entirely new set of nodes. If you only want to make changes to the installed CorDapps, you can shut down the node, update its CorDapps (by creating the new CorDapp JARs as described here and copying the CorDapp JARs into its cordapps folder) and restart the node. The new CorDapps will be installed, but the old node data will still be present.
unknown
d2551
train
I would write a custom fact. Facts are executed on the client. Eg: logback/manifests/init.pp file { '/etc/logback.xml': content => template('logback/logback.xml.erb') } logback/templates/logback.xml.erb ... <pattern>VERSION: <%= scope.lookupvar('::my_app_version') %></pattern> ... logback/lib/facter/my_app_version.rb Facter.add('my_app_version') do setcode do begin File.read('/etc/app.version') rescue nil end end end Hope that helps. I think in Puppet < 3.0 you will have to set "pluginsync = true" in puppet.conf to get this to work.
unknown
d2552
train
It is impossible to do so in a pure regex. Regexen cannot match nested parentheses, which the full RFC spec requires. (The latest RFC on this matter is RFC5322, only released a few months ago.) Full validation of email addresses requires something along the lines of a CFG, and there are a few more things to be wary of; for example, email addresses can contain '\0', the null character... so you can't use any of C's normal string functions on them. I actually feel a bit weird answering a question with a link to something I've written, but as it so happens, I have one I prepared earlier: a short and (as far as I can tell) fully-compliant validator, in Haskell; you can see the source code here. I imagine the code could be easily ported to any similar parsing library (perhaps C++’s Boost.Spirit), or just as easily hooked into from another language (Haskell has a very simple way for C to use Haskell code, and everything can use C bindings...) There are also extensive test cases in the source code (I didn't export them from the module), which are due to Dominic Sayers, who has his own version of an RFC-compliant parser in PHP. (Several of the tests fail, but they are more strict than RFC5322 specifies, so I'm fine with that at the moment.) A: That was asked here a couple of weeks ago. What it comes down to is, there are many legal addresses that an easy regex won't match. It takes a truly insane regex to match the majority of legal addresses. And even then, a syntactically legal address doesn't guarantee the existence of an account behind it - take [email protected], for example. A: Not to mention that Chinese/Arabic domain names are to be allowed in the near future. Everyone has to change the email regex used, because those characters are surely not to be covered by [a-z]/i nor \w. They will all fail. After all, best way to validate the email address is still to actually send an email to the address in question to validate the address. If the email address is part of user authentication (register/login/etc), then you can perfectly combine it with the user activation system. I.e. send an email with a link with an unique activation key to the specified email address and only allow login when the user has activated the newly created account using the link in the email. If the purpose of the regex is just to quickly inform the user in the UI that the specified email address doesn't look like in the right format, best is still to check if it matches basically the following regex: ([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+) Simple as that. Why on earth would you care about the characters used in the name and domain? A: Unfortunately, it's not a regex, but... The right way to validate an email address is to send it a message and see if the user replies. If you really, really want to verify that an address is syntactically-valid/RFC-compliant, then a regex is still unlikely to be the right tool for the job. You could most likely create a parser in fewer characters than the length of a regex with a similar level of RFC compliance and the parser would probably run faster to boot. Even with a perfect test of RFC compliance, [email protected] is perfectly-formed and refers to an existing domain, so you're not going to know whether the address you're given is actually valid or not unless you send it a message. A: General advice is don't It's probably worth a simple check that they entered "[email protected]" just to check they put the email in the right box. Beyond that most of the official regex allow for so many obscure cases that they have a huge false positive rate (they will allow technically legal but extremely unlikely entries) A: From http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html : The grammar described in RFC 822 is suprisingly complex. Implementing validation with regular expressions somewhat pushes the limits of what it is sensible to do with regular expressions, although Perl copes well: (?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t] )+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?: \r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:( ?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\0 31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\ ](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+ (?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?: (?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z |(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n) ?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\ r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n) ?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t] )*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])* )(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t] )+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*) *:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+ |\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r \n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?: \r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t ]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031 ]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\]( ?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(? :(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(? :\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(? :(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)? [ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]| \\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<> @,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|" (?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t] )*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\ ".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(? :[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[ \]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000- \031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|( ?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,; :\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([ ^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\" .\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\ ]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\ [\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\ r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\] |\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \0 00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\ .|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@, ;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(? :[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])* (?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\". \[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[ ^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\] ]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*( ?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\ ".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:( ?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[ \["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t ])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t ])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(? :\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+| \Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?: [^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\ ]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n) ?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[" ()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n) ?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<> @,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@, ;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t] )*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\ ".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)? (?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\". \[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?: \r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[ "()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t]) *))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]) +|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\ .(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z |(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:( ?:\r\n)?[ \t])*))*)?;\s*) A: This regular expression complies with the grammar described in RFC 2822, it's very long, but the grammar described in the RFC is complex... A: If you're using Perl, I believe the Regex::Common module would be the one you want to use, and in particular, Regex::Common::Email::Address. A: I had to recently build some RSS feeds, and part of that included going over the Xml schema, including the items for Webmaster and ManagingEditor, both of which are defined as an e-mail address matching this pattern: ([a-zA-Z0-9_\-])([a-zA-Z0-9_\-\.]*)@(\[((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}|((([a-zA-Z0-9\-]+)\.)+))([a-zA-Z]{2,}|(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\])
unknown
d2553
train
As you noticed, private and protected properties of a class C do not appear as part of keyof C. This is usually desirable behavior, since most attempts to index into a class with a private/protected property will cause a compile error. There is a suggestion at microsoft/TypeScript#22677 to allow mapping a type to a version where the private/protected properties are public, which would give you a way to do this... but this feature has not been implemented as of TypeScript 4.9. So this doesn't work: namespace Privates { export class A { private x: string = "a"; public y: number = 1; private keys: Array<keyof A> = ["x", "y"]; // Error } var keys: Array<keyof A> = ["x", "y"]; // Error } const privateA = new Privates.A(); privateA.y; // number privateA.x; // error: it's private privateA.keys; // error: it's private But maybe you don't actually need the properties to be private, so much as not visible to outside users of the class. You can use a module/namespace to export only the facets of your class that you want, like this: namespace NotExported { class _A { x: string = "a"; y: number = 1; keys: Array<keyof _A> = ["x", "y"]; // okay } export interface A extends Omit<_A, "x" | "keys"> {} export const A: new () => A = _A; var keys: Array<keyof _A> = ["x", "y"]; // okay } const notExportedA = new NotExported.A(); notExportedA.y; // number notExportedA.x; // error: property does not exist notExportedA.keys; // error: property does not exist In NotExported, the class constructor _A and the corresponding type _A are not directly exported. Internally, keyof _A contains both the "x" and "y" keys. What we do export is a constructor A and a corresponding type A that omits the x property (and keys property) from _A. So you get the internal behavior you desire, while the external behavior of NotExported.A is similar to that of Privates.A. Instead of x and keys being inaccessible due to private violation, they are inaccessible because they are not part of the exported A type. I actually prefer the latter method of not exporting implementation details rather than exposing the existence of private properties, since private properties actually have a lot of impact on how the corresponding classes can be used. That is, private is about access control, not about encapsulation. Link to code
unknown
d2554
train
Because in your callback for setTimeout, this is the Window object, not your component instance. You can fix this by using an arrow function, which binds this to the context in which the function was declared: ngOnInit(){ this.ls = "dddd" setTimeout(() => { this.name = "helllllll" }, 3000); } A: You need to implement the interface OnChanges to get the name reference and do the change in the var name this function its executed after ngInit and ngOnChanges its triggered when you are using @Input() decorator demo ngOnChanges(changes: any): void { this.ls = "dddd" setTimeout(() => { this.name = "helllllll" }, 3000); } A: Use Observable: // Create observable const myObservable = new Observable((observer) => { setInterval(() => observer.next({ name: 'John Doe', time: new Date().toString() }), 3000); }) // Subscribe to the observable myObservable.subscribe((x: any) => { this.name = `${x.name}, Time: ${x.time}`; }); https://stackblitz.com/edit/angular-ce3x4v
unknown
d2555
train
You cannot do it using DataTriggers. DataTriggers are for Data-Based scenarios, so if you are using DataBinding, then use them. Recommended approach : Assign a name to your Popup. And use Behaviors. <Button ...> <Button.Style> <Style TargetType="Button"> <Style.Triggers> <Trigger Property="IsFocused" Value="True"> <Setter Property="Background" Value="Red"/> </Trigger> </Style.Triggers> </Style> </Button.Style> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <i:Interaction.Behaviors> <ei:ConditionBehavior> <ei:ConditionalExpression> <ei:ComparisonCondition LeftOperand="{Binding IsFocused, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" RightOperand="True"/> </ei:ConditionalExpression> </ei:ConditionBehavior> </i:Interaction.Behaviors> <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="IsOpen" Value="True"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> To use Blend assemblies : Add reference to System.Windows.Interactivity and Microsoft.Expression.Interactions and following namespaces : xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" To revert back old Background of the source Button : <Button> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <i:Interaction.Behaviors> <ei:ConditionBehavior> <ei:ConditionalExpression> <ei:ComparisonCondition LeftOperand="{Binding IsFocused, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" RightOperand="True"/> </ei:ConditionalExpression> </ei:ConditionBehavior> </i:Interaction.Behaviors> <!-- Store Button's old Background --> <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="Tag" Value="{Binding Background, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}"/> <!-- Change Button's Background --> <ei:ChangePropertyAction PropertyName="Background" Value="Purple"/> <!-- Open Popup --> <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="IsOpen" Value="True"/> <!-- Save this Button, Popup will use it to revert back its old Background --> <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="PlacementTarget" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> <Popup x:Name="Popup1" Placement="Mouse" StaysOpen="False"> <i:Interaction.Triggers> <i:EventTrigger EventName="Closed"> <ei:ChangePropertyAction TargetObject="{Binding PlacementTarget, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Popup}}" PropertyName="Background" Value="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Popup}}" /> </i:EventTrigger> </i:Interaction.Triggers> <Grid> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" Text="Welcome to Popup Screen"/> </Grid> </Popup> A: I tried to achieve what you asking for without using DataTrigger. This is simple style trigger for changing background: <Style TargetType="Button"> <Style.Triggers> <Trigger Property="Button.IsFocused" Value="True"> <Setter Property="Button.Background" Value="Red" /> </Trigger> </Style.Triggers> </Style> Each your button can handle Click event: <Button Content="One" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Click="Button_Click" /> ... And we need to take your Popup somehow. I just named it: <Popup Name="popup" Placement="Mouse" StaysOpen="False"> ... Click event is simple: private void Button_Click(object sender, RoutedEventArgs e) { var button = sender as Button; if (popup.IsOpen) { popup.IsOpen = false; } popup.PlacementTarget = button; popup.IsOpen = true; } So it works like you want.
unknown
d2556
train
You can use this code to do what you want. Pretty much you're just simulating a client when you do this by writing a HTTP request to a page and then processing the response headers that it sends back. This is also how you would build a proxy server, but that is sort of what you're doing. Let me know if you need any help. // // OPEN SOCKET TO SERVER // $_socket = @fsockopen($host, $port, $err_no, $err_str, 30); // // SET REQUEST HEADERS // $_request_headers = '... CONSTRUCT FULL HEADERS HERE ...'; fwrite($_socket, $_request_headers); // // PROCESS RESPONSE HEADERS // $_response_headers = $_response_keys = array(); $line = fgets($_socket, 8192); while (strspn($line, "\r\n") !== strlen($line)) { @list($name, $value) = explode(':', $line, 2); $name = trim($name); $_response_headers[strtolower($name)][] = trim($value); $_response_keys[strtolower($name)] = $name; $line = fgets($_socket, 8192); } sscanf(current($_response_keys), '%s %s', $_http_version, $_response_code); if (isset($_response_headers['set-cookie'])) { // DO WHAT YOU WANT HERE } For reference, you can find similar code in PHProxy that goes into much more detail. It will create headers for you, process response headers, and more. If you find that this example doesn't do everything you need, you should reference that software.
unknown
d2557
train
Turns out that I to use out.println("message") instead of out.write("message") when I post to this server. So I have updated my method like so @Override protected String doInBackground(String... params) { String comment = params[0]; String response = null; Socket socket = null; try { socket = new Socket("www.regisscis.net", 8080); if (socket.isConnected()) { PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); Log.i(TAG_STRING, "Calling Write"); out.println(comment); String resposeFromServer = in.readLine(); out.close(); in.close(); response = resposeFromServer; socket.close(); } else { Log.i(TAG_STRING, "Socket is not connected"); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return response; }
unknown
d2558
train
This is possible via configuring VirtualBox (if you are using it). There are more than one way to do it, but take a look at this tutorial
unknown
d2559
train
In your vuex store, the state parameter in your getter only has access to local state. You can't access the auth state the way you tried. In a vuex module, a getter gets 4 arguments, namely local state, local getters, root state and root getters. So if you would rewrite your getters like this it would probably work: export const getters = { isAuthenticated(state, getters, rootState) { return rootState.auth.loggedIn }, loggedInUser(state, getters, rootState) { return rootState.auth.user }} } But I still think it is a bit redundant doing it like that. I would replace isAuthenticated with this.$auth.loggedIn in your default layout. The nuxt-auth module globally injects the $auth instance, meaning that you can access it anywhere using this.$auth. A: I had same problem after authorizing user and redirect user to the home page. After many tries and doing many works, the right config of auth in nuxt.config.js seemed like this: auth: { strategies: { local: { scheme: 'refresh', token: { property: 'access_token', tokenType: false, maxAge: 60 * 60 }, refreshToken: { property: 'refresh_token', data: '', maxAge: 60 * 60 }, endpoints: { login: { url: 'url/of/token', method: 'urlMethod' }, refresh: { url: 'url/of/refreshToken', method: 'urlMethod' }, logout: false, user: false } } }, cookie: false, redirect: { login: '/login/page', logout: '/login/page', callback: false, home: '/home/page' } }, Note that I didn't have any refreshToken property, but I should set it as empty string in config to be able to work with nuxt/auth! Hope I could help
unknown
d2560
train
Your problem has nothing to do with ternary operator, but with PHP output to javascript. The safest way is: var foo = <?php echo json_encode($foo); ?> || null ; The json_encode() function makes sure that the variable is echoed in a form that JS understands. A: You need to return a falsy value from php. Your code was almost correct. It was only missing the quotes around it. var foo = '<?php echo $foo; ?>' || null; console.log('foo', foo); // null This is because when $foo is empty, it will be var foo = '' || null; and since '' is falsy in Javascript, it will return null.
unknown
d2561
train
The solution you outlined is one possible option, and it seems to me like a good start. Discussing in comments, I’d disagree that it is a “dirty” solution because you are actually using built-in components, namely the OAuth2TokenCustomizer and UserDetailsService. The built-in components in Spring Security are designed to allow you to integrate your authorization rules and requirements into the framework, which you are attempting to do. If you have a working solution for doing that, I would say that you have something to build on, and you can always improve it later or experiment with other ways if needed. Another option would be to only include a roles claim (e.g. "roles": ["ROLE_ADMIN"]) in the access token, and perform the authority mapping in the resource server. This has the benefit of always being up to date, but the downside of scalability as it requires many resource servers to query the database where role to authority mappings are stored. If this is of interest, you would use a JwtGrantedAuthoritiesMapper from spring-security-oauth2-resource-server on the resource server side. I would also recommend opaque tokens instead of JWTs if immediate revocation is needed. Similar support exists if using opaque tokens instead, though it would be better to customize claims on the authz server in this case.
unknown
d2562
train
You misunderstood Activity lifecycle. onDestroy() is NOT called when your activity is dismissed. And dismissing it (i.e. by starting another activity) does NOT equal destroying activity (however you may enforce destroy of activity, by calling finish() - and then your onDestroy() method will be invoked). You may want to move your code to onPause() and onResume() respectively or maybe you shall use IntentService instead, if you dot require any UI for the task. A: I propose to use Android Service for such kind of tasks http://developer.android.com/reference/android/app/Service.html .
unknown
d2563
train
Your code is showing something you dont want, the loop instead the timeline, and it's showing , not one timeline but many of them . Change your code to: <% data = @projects.pluck(:hospital,:construction_start,:construction_end) %> <%= timeline data %> This should only create one timeline with all the data about the hospitals of all projects you passed from the controller . Note that this will only work on Rails 4+. If you have Rails 3 you will have to override the pluck method (it's not hard actually)
unknown
d2564
train
Which version of crystal reports runtime you are using on server and on local system? Runtime should be 32bit. You need to setup those two properties. Report.PrintOptions.NoPrinter = false; Report.PrintOptions.PrinterName = <printername>; And printer should be available in network via this name. If you are using IIS then application pool also need access to printer. In app pool advanced settings you need to switch boolean prop "Enable 32-bit apps" to true. If this still does not help you can try change Identity to "LocalService" in those advanced settings.
unknown
d2565
train
What about using viewport height and viewport width? I've created an example in this JSFiddle. body, html { margin: 0; padding: 0; } div { width: 100vw; height: 100vh; } .one { background-color: blue; } .two { background-color: green; } .three { background-color: yellow; } <div class="one"></div> <div class="two"></div> <div class="three"></div> A: If you want to make div to occupy entire space use vw and vh because making div alone height:100% and width:100% would not do it without using viewport units check this snippet div{ width: 100%; height:100%; background:red; } html,body{ height:100%; width:100%; } <div ></div> but making html and body to have height and width is a bad idea so to skip it use view port units check this with viewport unist div { width: 100vw; height: 100vh; background: red; } <div></div> Hope it helps A: Older browsers such as IE7 and 8 could be supported without using visual height and width units by using a single absolutely positioned container with inner divs inheriting height and width property values. CSS body { margin: 0px; /* optional */ } #box { position:absolute; height: 100%; min-width: 100%; } .page { padding: 5px; /* optional */ height: inherit; } HTML <body> <div id="box"> <div class="page" style="background-color: red"> <div style="width:25em; background-color: gray">25em</div> </div> <div class="page" style="background-color: green">2</div> <div class="page" style="background-color: white">3</div> </div> </body> Update: the width property of the container has been replaced by a min-width property, introduced in IE7, to fix an ugly horizontal scrolling issue. Supplying width for inner div elements was removed as being unnecessary. A: Simply change the top: value for each one. The first one would be 0, the second 100%, the third 200%, and so on. Here's a working example: <div style="width: 100%; height: 100%; position: absolute; top: 0; left: 0;background:red;"></div> <div style="width: 100%; height: 100%; position: absolute; top: 100%; left: 0; background:blue;"></div> <div style="width: 100%; height: 100%; position: absolute; top: 200%; left: 0; background:green;"></div>
unknown
d2566
train
To avoid SQL injection attacks, to make formatting of query strings easier, and to make handling of blob data possible, all databases support parameters. In Python, it would look like this: id = 1 text = "blah ..." cursor.execute("INSERT INTO mytable(id, content) VALUES(?, ?)", (id, text)) A: The data type to use depends on the overall size of the input. Text would be my first choice. for more on sqlite3 datatypes see http://www.sqlite.org/datatype3.html I would recommend you Sanitize the input, only allow necessary markup. Encode the content so it's safe to insert into the database. If security is a serious concern this processing should be done server side. It won't hurt to put some of this processing load to javascript this will reduce the work done at the server. Tho it would still catch user(s) trying to circumvent the feature. A: I'm not into python, but doesn't your DB driver take care of it already? Otherwise, you have to replace escape those characters manually. Take a look at this thread: How to string format SQL IN clause with Python
unknown
d2567
train
Here's the basic idea: $(document).ready(function(){ $(".button").click(function(){ var t=$(this); $.ajax({url:"liked_button.php",success:function(result){ t.replaceWith("<button type='button' id='button_pressed'>Liked</button>") }}); }); }); Your other issue is that you use id overly much. Replace all looped uses of id (including in the code I gave you) with class, or else your code won't work. A: HTML IDs (such as your like_system) must be unique. Your update selector is finding the first one every time. Try something like: $(".button").click(function(){ var clicked = $(this); $.ajax({url:"liked_button.php",success:function(result){ clicked.closest('div').html(result); }}); }); And either remove the like_system ID, or replace it with a class if you need to style it, etc.
unknown
d2568
train
I got very helpful comments by Rene and Ben. and based on i have solved my issues.. --------------------------- CREATING TABLE -------------------------- create table tbl_location( id int constraint id_pk primary key, unit_code char(2) not null, plot_id number(15) not null, season_cntrl number(2), Ryot_code varchar2(9), share_or_perc_val number(2) not null, plot_no varchar2(18) not null, total_area decimal(5,5), a1 varchar2(15), b1 varchar2(15), a2 varchar2(15), b2 varchar2(15), a3 varchar2(15), b3 varchar2(15), a4 varchar2(15), b4 varchar2(15), location sdo_geometry ); --------------------------- CREATING SEQUENCE FOR ID --------------------------- create sequence location_sequence start with 1 increment by 1 nocache nocycle; / --- createing a trigger for auto-incrementation of ID ------------------------------ Create or replace trigger id_increment before insert on tbl_location for each row begin select location_sequence.nextval into :new.id from dual; end; for column location data update tbl_location set location = SDO_GEOMETRY(2003,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( '80.16181','27.8682866666666','80.1616516666666','27.8681266666666','80.161215','27.867975','80.1613933333333','27.8685933333333','80.16181','27.8682866666666' )) where id =2; update tbl_location set location = SDO_GEOMETRY(2003,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( '80.1538483333333','27.88376','80.15354','27.8841166666666','80.1529499999999','27.8834933333333','80.1532','27.8832566666666','80.1538483333333','27.88376' )) where id =3; To get plots (polygon) which are intersecting each other select a.id as id1, b.id as id2,a.unit_code, a.ryot_code,a.share_or_perc_val, sdo_geom.sdo_intersection(a.location, b.location, 0.005) location, a.plot_no, a.total_area from tbl_location a Inner Join tbl_location b on a.id < b.id and sdo_geom.sdo_intersection(a.location, b.location,0.005) is not null ; A: Well, you can just call the SDO_GEOM.SDO_AREA() on the result of the SDO_GEOM.SDO_INTERSECTION() function. However that will not give you meaningful results: your geometries are (so it seems) in geodetic WGS84 coordinates (i.e. in decimal degrees), but you load them without specifying any coordinate system. As a result, any area calculation will return a result in square degrees, a meaningless and unusable result. You should load your two geometries like this: update tbl_location set location = SDO_GEOMETRY(2003,4326,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( 80.16181,27.8682866666666,80.1616516666666,27.8681266666666,80.161215,27.867975,80.1613933333333,27.8685933333333,80.16181,27.8682866666666 )) where id =2; update tbl_location set location = SDO_GEOMETRY(2003,4326,NULL,SDO_ELEM_INFO_ARRAY(1,1003,1),SDO_ORDINATE_ARRAY( 80.1538483333333,27.88376,80.15354,27.8841166666666,80.1529499999999,27.8834933333333,80.1532,27.8832566666666,80.1538483333333,27.88376 )) where id =3; Finally your approach only works because you only play with two geometries. As soon as you start dealing with real data, the query will perform very badly: it requires computing the intersection between each shape and all the others. For a set of 10,000 shapes, that means 100,000,000 computations (well actually 99,990,000 since you avoid intersecting a geometry with itself). The proper approach is to detect the shapes that intersect by taking advantage of spatial indexing. The appropriate approach is to use the SDO_JOIN() procedure for that. A: There is a much more simple way to do that. Your Problem seems to use the SDO_GEOM.RELATE function. This function Returns the relationship between two or more Polygons. In the following example all relations to the other polygons in your table are shown to the polygon with the 1 SELECT c.id, SDO_GEOM.RELATE(c.polygon, 'determine', c_b.polygon, 0.005) relationship FROM my_polygon_table c, my_polygon_talbe c_b WHERE c_b.id = 1; The result is one of the opsibile relationships: ANYINTERACT; CONTAINS; COVEREDBY; COVERS; DISJOINT; EQUAL; INSIDE; ON; OVERLAPBDYDISJOINT; OVERLAPBDYINTERSECT; TOUCH; Care also about the Right Keyword: If you pass the DETERMINE keyword in mask, the function returns the one relationship keyword that best matches the geometries. If you pass the ANYINTERACT keyword in mask, the function returns TRUE if the two geometries are not disjoint.
unknown
d2569
train
If your application communicates with backend server you can simulate network traffic coming from hundreds of applications using i.e. Apache JMeter by following next simple steps: * *Record your application traffic (one or several scenarios) using JMeter's built-in proxy server * *disable cellular data on device and enable WiFi *make sure that host running JMeter and mobile device are on same network/subnet *start JMeter's proxy server *configure your mobile device to use JMeter as a proxy *click all buttons, touch actions, etc. *Add virtual users *Run the test If your application connects with the backend over HTTPS you may use 3rd-party tool like ProxyDroid to set up SSL proxy. You will also need to install JMeter's self-signed certificate ApacheJMeterTemporaryRootCA.crt which is being generated in JMeter's /bin folder when you start proxy server. The easiest way to install it on the device is to send it by email. See Load Testing Mobile Apps. But Made Easy guide for more detailed instructions. If you application doesn't use backend - it doesn't make sense to load test it at all. A: I can achieve this using JUnit Parallel test with selendroid download ParallelTest folder from github https://github.com/gworksmobi/Grace Reference : https://testingbot.com/support/getting-started/parallel-junit.html (this link is for selenium I am just modified to selendroid) Steps: * *Download folder from github *Add supporting selendroid jar to eclipse (http://selendroid.io/setup.html) *Create project. *Create the exact ditto class into your project as per github download folder *Now make the changes as per your application in JUnitParallel.java Description of class : JUnitParallel.java -> have business logic of testing Parallelized.java -> provide multi thread support
unknown
d2570
train
try to use: lotus auth create-token --perm read I guess you should change your token to use those perms
unknown
d2571
train
Try $(".update_day[data-id='90']").val(day); if value is stored in variable day_id $(".update_day[data-id='" + day_id + "']").val(day); Attribute equals selector
unknown
d2572
train
Something like this should get you started (sorry not readdly familiar with python): class DemoFrame(wx.Frame): def __init__(self): self.tab_num = 1 wx.Frame.__init__(self, None, wx.ID_ANY, "Notebook", size=(600,400)) panel = wx.Panel(self) with open( "test.txt", "r" as file: self.tab_num = file.read() self.notebook = wx.Notebook(panel) for tab in [1..self.tab_num]: name = "Page " + str(tab) tab = TabPanel(self.notebook, 1) self.notebook.AddPage(tab, name) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.notebook, 1, wx.ALL|wx.EXPAND, 5) btn = wx.Button(panel, label="Add Page") btn.Bind(wx.EVT_BUTTON, self.addPage) sizer.Add(btn) panel.SetSizer(sizer) self.Layout() self.Show() def addPage(self, event): self.tab_num += 1 new_tab = TabPanel(self.notebook, self.tab_num) self.notebook.AddPage(new_tab, "Page %s" % self.tab_num) tabs.append(self.tab_num) print() with open('test.txt','a+') as file: file.write(str(self.tab_num)) file.write('\n') if __name__ == "__main__": app = wx.App(False) frame = DemoFrame() app.MainLoop()
unknown
d2573
train
the error point you to this: transactions[0].item_list.items[0].sku This filed seems to be required i think it just need to put sku in item array so let's do it: try to add: $item->setSKU("CODEHERE"); after $item->setCurrency("USD");
unknown
d2574
train
"Does not work how I think it should" and "incorrect" are, not always the same thing. Given the input aba and the pattern (ab|a)/ab it makes a certain amount of sense for the (ab|a) to match greedily, and then for the /ab constraint to be applied separately. You're thinking that it should work like this regular expression: (ab|a)(ab) with the constraint that the part matched by (ab) is not consumed. That's probably better because it removes some limitations, but since there weren't any external requirements for what lex should do at the time it was written, you cannot call either behavior correct or incorrect. The naive way has the merit that adding a trailing context doesn't change the meaning of a token, but simply adds a totally separate constraint about what may follow it. But that does lead to limitations/surprises: {IDENT} /* original code */ {IDENT}/ab /* ident, only when followed by ab */ Oops, it won't work because "ab" is swallowed into IDENT precisely because its meaning was not changed by the trailing context. That turns into a limitation, but maybe it's a limitation that the author was willing to live with in exchange for simplicity. (What is the use case for making it more contextual, anyway?) How about the other way? That could have surprises also: {IDENT}/ab /* input is bracadabra:123 */ Say the user wants this not to match because bracadabra is not an identifier followed by (or ending in) ab. But {IDENT}/ab will match bracad and then, leaving abra:123 in the input. A user could have expectations which are foiled no matter how you pin down the semantics. lex is now standardized by The Single Unix specification, which says this: r/x The regular expression r shall be matched only if it is followed by an occurrence of regular expression x ( x is the instance of trailing context, further defined below). The token returned in yytext shall only match r. If the trailing portion of r matches the beginning of x, the result is unspecified. The r expression cannot include further trailing context or the '$' (match-end-of-line) operator; x cannot include the '^' (match-beginning-of-line) operator, nor trailing context, nor the '$' operator. That is, only one occurrence of trailing context is allowed in a lex regular expression, and the '^' operator only can be used at the beginning of such an expression. So you can see that there is room for interpretation here. The r and x can be treated as separate regexes, with a match for r computed in the normal way as if it were alone, and then x applied as a special constraint. The spec also has discussion about this very issue (you are in luck): The following examples clarify the differences between lex regular expressions and regular expressions appearing elsewhere in this volume of IEEE Std 1003.1-2001. For regular expressions of the form "r/x", the string matching r is always returned; confusion may arise when the beginning of x matches the trailing portion of r. For example, given the regular expression "a*b/cc" and the input "aaabcc", yytext would contain the string "aaab" on this match. But given the regular expression "x*/xy" and the input "xxxy", the token xxx, not xx, is returned by some implementations because xxx matches "x*". In the rule "ab*/bc", the "b*" at the end of r extends r's match into the beginning of the trailing context, so the result is unspecified. If this rule were "ab/bc", however, the rule matches the text "ab" when it is followed by the text "bc". In this latter case, the matching of r cannot extend into the beginning of x, so the result is specified. As you can see there are some limitations in this feature. Unspecified behavior means that there are some choices about what the behavior should be, none of which are more correct than the others (and don't write patterns like that if you want your lex program to be portable). "As you can see, there are some limitations in this feature".
unknown
d2575
train
You need to sort the array in some way, I recommend sorting by key (foo, bar, doz). http://php.net/manual/en/function.ksort.php The order will always be the same when using the same keys. I haven't tested this, but it should work for your code. $a = ["foo" => 1, "bar" => 2, "doz" => 3]; $b = ["doz" => 3, "bar" => 2, "foo" => 1]; ksort($a); ksort($b); print json_encode($a)."\n"; print json_encode($b)."\n"; This will print: {"bar":2,"doz":3,"foo":1} {"bar":2,"doz":3,"foo":1}
unknown
d2576
train
It's probably not entering the If distance(nowAt, i) > maxDistance Then statement where the nextAt variable is set. So nextAt will still be set to its default value 0 when it reaches that line, which is out of range. Have you stepped through it with the debugger and checked that it enters this If statement? If you manually set nextAt to a 1 in the Locals window while debugging, does it work then? If that's the problem, either set an initial value for nextAt outside of the If statement, or ensure that it enters this If statement in its first round in the loop.
unknown
d2577
train
The delete link in your partial has two conditions that are required to be true. The user must be an admin, and the profile must not be their own profile. So if the admin user is the only user, then no delete link will show up. Try creating a second user and see if the delete link shows up for that user.
unknown
d2578
train
return Array.from({length: n}, (_, i) => i); ...saves a few bytes.
unknown
d2579
train
To my understanding, this is not possible directly, as the representation of the configuration is implicitly represented in the solution file (*.sln) and the project file (*.vcproj) by its name and conditions; however, similar to the answer to this question, the project files can be edited manually and similar parts can be factored out using the Import element, which is documented here.
unknown
d2580
train
I think this may help you You Need To Create Some Classes As Given Below class Score implements Serializable { private String label; private String field; private String category; private Integer valueInt; private String value; private Integer rank; private Double percentile; private String displayValue; public Score() { this("", "", "", 0, "", 0, 0.0, ""); } public Score(String label, String field, String category, Integer valueInt, String value, Integer rank, Double percentile, String displayValue) { this.label = label; this.field = field; this.category = category; this.valueInt = valueInt; this.value = value; this.rank = rank; this.percentile = percentile; this.displayValue = displayValue; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getField() { return field; } public void setField(String field) { this.field = field; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Integer getValueInt() { return valueInt; } public void setValueInt(Integer valueInt) { this.valueInt = valueInt; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Integer getRank() { return rank; } public void setRank(Integer rank) { this.rank = rank; } public Double getPercentile() { return percentile; } public void setPercentile(Double percentile) { this.percentile = percentile; } public String getDisplayValue() { return displayValue; } public void setDisplayValue(String displayValue) { this.displayValue = displayValue; } } class TRNRating implements Serializable { private String label; private String field; private String category; private Integer valueInt; private String value; private Integer rank; private Double percentile; private String displayValue; public TRNRating() { this("", "", "", 0, "", 0, 0.0, ""); } public TRNRating(String label, String field, String category, Integer valueInt, String value, Integer rank, Double percentile, String displayValue) { this.label = label; this.field = field; this.category = category; this.valueInt = valueInt; this.value = value; this.rank = rank; this.percentile = percentile; this.displayValue = displayValue; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getField() { return field; } public void setField(String field) { this.field = field; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Integer getValueInt() { return valueInt; } public void setValueInt(Integer valueInt) { this.valueInt = valueInt; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Integer getRank() { return rank; } public void setRank(Integer rank) { this.rank = rank; } public Double getPercentile() { return percentile; } public void setPercentile(Double percentile) { this.percentile = percentile; } public String getDisplayValue() { return displayValue; } public void setDisplayValue(String displayValue) { this.displayValue = displayValue; } } class P2 implements Serializable { private TRNRating trnRating; private Score score; public P2() { this(new TRNRating(), new Score()); } public P2(TRNRating trnRating, Score score) { this.trnRating = trnRating; this.score = score; } public TRNRating getTrnRating() { return trnRating; } public void setTrnRating(TRNRating trnRating) { this.trnRating = trnRating; } public Score getScore() { return score; } public void setScore(Score score) { this.score = score; } } class Stats implements Serializable { private P2 p2; public Stats() { this(new P2()); } public Stats(P2 p2) { this.p2 = p2; } } //You Need To Change Name Of This Class class Response implements Serializable { private String accountId; private Integer platformId; private String platformName; private String platformNameLong; private String epicUserHandle; private Stats stats; public Response() { this("", 0, "", "", "", new Stats()); } public Response(String accountId, Integer platformId, String platformName, String platformNameLong, String epicUserHandle, Stats stats) { this.accountId = accountId; this.platformId = platformId; this.platformName = platformName; this.platformNameLong = platformNameLong; this.epicUserHandle = epicUserHandle; this.stats = stats; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public Integer getPlatformId() { return platformId; } public void setPlatformId(Integer platformId) { this.platformId = platformId; } public String getPlatformName() { return platformName; } public void setPlatformName(String platformName) { this.platformName = platformName; } public String getPlatformNameLong() { return platformNameLong; } public void setPlatformNameLong(String platformNameLong) { this.platformNameLong = platformNameLong; } public String getEpicUserHandle() { return epicUserHandle; } public void setEpicUserHandle(String epicUserHandle) { this.epicUserHandle = epicUserHandle; } public Stats getStats() { return stats; } public void setStats(Stats stats) { this.stats = stats; } } If your response is same as explained in question. Then this will work. //In your code after status check you need to do like this if (myConnection.getResopnseCode() == 200) { BufferedReader br=new BufferedReader(responseBodyReader); String read = null, entireResponse = ""; StringBuffer sb = new StringBuffer(); while((read = br.readLine()) != null) { sb.append(read); } entireResponse = sb.toString(); //You need to change name of response class Response response = new Gson().fromJson(entireResponse , Response.class); }
unknown
d2581
train
specially if you use the client side storage or a cache manifest, you can store much more data Client application storage is different than the Safari's own cache, to which the original poster was referring. We know that in 2.2, Safari can store 19 objects each up to 25K in size. What are the new numbers for 3.0+? The posted link/pdf doesn't seem to have the answer. A: hmm... as far as i'm aware of, the cache size since version 2.2 is much larger. specially if you use the client side storage or a cache manifest, you can store much more data. how to store values clientside can be read here Apple developer Connection PDF version
unknown
d2582
train
I would recommend ffmpeg. There is a python wrapper. http://code.google.com/p/pyffmpeg/ A: Answer: No. There is no single library/solution in python to do video/audio recording simultaneously. You have to implement both separately and merge the audio and video signal in a smart way to end up with a video/audio file. I got a solution for the problem you present. My code addresses your three issues: * *Records video + audio from webcam and microphone simultaneously. *It saves the final video/audio file as .AVI *Un-commenting lines 76, 77 and 78 will make the video to be displayed to screen while recording. My solution uses pyaudio for audio recording, opencv for video recording, and ffmpeg for muxing the two signals. To be able to record both simultaneously, I use multithreading. One thread records video, and a second one the audio. I have uploaded my code to github and also have included all the essential parts it here. https://github.com/JRodrigoF/AVrecordeR Note: opencv is not able to control the fps at which the webcamera does the recording. It is only able to specify in the encoding of the file the desired final fps, but the webcamera usually behaves differently according to specifications and light conditions (I found). So the fps have to be controlled at the level of the code. import cv2 import pyaudio import wave import threading import time import subprocess import os class VideoRecorder(): # Video class based on openCV def __init__(self): self.open = True self.device_index = 0 self.fps = 6 # fps should be the minimum constant rate at which the camera can self.fourcc = "MJPG" # capture images (with no decrease in speed over time; testing is required) self.frameSize = (640,480) # video formats and sizes also depend and vary according to the camera used self.video_filename = "temp_video.avi" self.video_cap = cv2.VideoCapture(self.device_index) self.video_writer = cv2.VideoWriter_fourcc(*self.fourcc) self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, self.frameSize) self.frame_counts = 1 self.start_time = time.time() # Video starts being recorded def record(self): # counter = 1 timer_start = time.time() timer_current = 0 while(self.open==True): ret, video_frame = self.video_cap.read() if (ret==True): self.video_out.write(video_frame) # print str(counter) + " " + str(self.frame_counts) + " frames written " + str(timer_current) self.frame_counts += 1 # counter += 1 # timer_current = time.time() - timer_start time.sleep(0.16) # gray = cv2.cvtColor(video_frame, cv2.COLOR_BGR2GRAY) # cv2.imshow('video_frame', gray) # cv2.waitKey(1) else: break # 0.16 delay -> 6 fps # # Finishes the video recording therefore the thread too def stop(self): if self.open==True: self.open=False self.video_out.release() self.video_cap.release() cv2.destroyAllWindows() else: pass # Launches the video recording function using a thread def start(self): video_thread = threading.Thread(target=self.record) video_thread.start() class AudioRecorder(): # Audio class based on pyAudio and Wave def __init__(self): self.open = True self.rate = 44100 self.frames_per_buffer = 1024 self.channels = 2 self.format = pyaudio.paInt16 self.audio_filename = "temp_audio.wav" self.audio = pyaudio.PyAudio() self.stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate, input=True, frames_per_buffer = self.frames_per_buffer) self.audio_frames = [] # Audio starts being recorded def record(self): self.stream.start_stream() while(self.open == True): data = self.stream.read(self.frames_per_buffer) self.audio_frames.append(data) if self.open==False: break # Finishes the audio recording therefore the thread too def stop(self): if self.open==True: self.open = False self.stream.stop_stream() self.stream.close() self.audio.terminate() waveFile = wave.open(self.audio_filename, 'wb') waveFile.setnchannels(self.channels) waveFile.setsampwidth(self.audio.get_sample_size(self.format)) waveFile.setframerate(self.rate) waveFile.writeframes(b''.join(self.audio_frames)) waveFile.close() pass # Launches the audio recording function using a thread def start(self): audio_thread = threading.Thread(target=self.record) audio_thread.start() def start_AVrecording(filename): global video_thread global audio_thread video_thread = VideoRecorder() audio_thread = AudioRecorder() audio_thread.start() video_thread.start() return filename def start_video_recording(filename): global video_thread video_thread = VideoRecorder() video_thread.start() return filename def start_audio_recording(filename): global audio_thread audio_thread = AudioRecorder() audio_thread.start() return filename def stop_AVrecording(filename): audio_thread.stop() frame_counts = video_thread.frame_counts elapsed_time = time.time() - video_thread.start_time recorded_fps = frame_counts / elapsed_time print "total frames " + str(frame_counts) print "elapsed time " + str(elapsed_time) print "recorded fps " + str(recorded_fps) video_thread.stop() # Makes sure the threads have finished while threading.active_count() > 1: time.sleep(1) # Merging audio and video signal if abs(recorded_fps - 6) >= 0.01: # If the fps rate was higher/lower than expected, re-encode it to the expected print "Re-encoding" cmd = "ffmpeg -r " + str(recorded_fps) + " -i temp_video.avi -pix_fmt yuv420p -r 6 temp_video2.avi" subprocess.call(cmd, shell=True) print "Muxing" cmd = "ffmpeg -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video2.avi -pix_fmt yuv420p " + filename + ".avi" subprocess.call(cmd, shell=True) else: print "Normal recording\nMuxing" cmd = "ffmpeg -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video.avi -pix_fmt yuv420p " + filename + ".avi" subprocess.call(cmd, shell=True) print ".." # Required and wanted processing of final files def file_manager(filename): local_path = os.getcwd() if os.path.exists(str(local_path) + "/temp_audio.wav"): os.remove(str(local_path) + "/temp_audio.wav") if os.path.exists(str(local_path) + "/temp_video.avi"): os.remove(str(local_path) + "/temp_video.avi") if os.path.exists(str(local_path) + "/temp_video2.avi"): os.remove(str(local_path) + "/temp_video2.avi") if os.path.exists(str(local_path) + "/" + filename + ".avi"): os.remove(str(local_path) + "/" + filename + ".avi") A: I've been looking around for a good answer to this, and I think it is GStreamer... The documentation for the python bindings is extremely light, and most of it seemed centered around the old 0.10 version of GStreamer instead of the new 1.X versions, but GStreamer is a extremely powerful, cross-platform multimedia framework that can stream, mux, transcode, and display just about anything. A: I used JRodrigoF's script for a while on a project. However, I noticed that sometimes the threads would hang and it would cause the program to crash. Another issue is that openCV does not capture video frames at a reliable rate and ffmpeg would distort my video when re-encoding. I came up with a new solution that records much more reliably and with much higher quality for my application. It presently only works for Windows because it uses pywinauto and the built-in Windows Camera app. The last bit of the script does some error-checking to confirm the video successfully recorded by checking the timestamp of the name of the video. https://gist.github.com/mjdargen/956cc968864f38bfc4e20c9798c7d670 import pywinauto import time import subprocess import os import datetime def win_record(duration): subprocess.run('start microsoft.windows.camera:', shell=True) # open camera app # focus window by getting handle using title and class name # subprocess call opens camera and gets focus, but this provides alternate way # t, c = 'Camera', 'ApplicationFrameWindow' # handle = pywinauto.findwindows.find_windows(title=t, class_name=c)[0] # # get app and window # app = pywinauto.application.Application().connect(handle=handle) # window = app.window(handle=handle) # window.set_focus() # set focus time.sleep(2) # have to sleep # take control of camera window to take video desktop = pywinauto.Desktop(backend="uia") cam = desktop['Camera'] # cam.print_control_identifiers() # make sure in video mode if cam.child_window(title="Switch to Video mode", auto_id="CaptureButton_1", control_type="Button").exists(): cam.child_window(title="Switch to Video mode", auto_id="CaptureButton_1", control_type="Button").click() time.sleep(1) # start then stop video cam.child_window(title="Take Video", auto_id="CaptureButton_1", control_type="Button").click() time.sleep(duration+2) cam.child_window(title="Stop taking Video", auto_id="CaptureButton_1", control_type="Button").click() # retrieve vids from camera roll and sort dir = 'C:/Users/m/Pictures/Camera Roll' all_contents = list(os.listdir(dir)) vids = [f for f in all_contents if "_Pro.mp4" in f] vids.sort() vid = vids[-1] # get last vid # compute time difference vid_time = vid.replace('WIN_', '').replace('_Pro.mp4', '') vid_time = datetime.datetime.strptime(vid_time, '%Y%m%d_%H_%M_%S') now = datetime.datetime.now() diff = now - vid_time # time different greater than 2 minutes, assume something wrong & quit if diff.seconds > 120: quit() subprocess.run('Taskkill /IM WindowsCamera.exe /F', shell=True) # close camera app print('Recorded successfully!') win_record(2) A: To the questions asked above: Yes the code should also works under Python3. I adjusted it a little bit and now works for python2 and python3 (tested it on windows7 with 2.7 and 3.6, though you need to have ffmpeg installed or the executable ffmpeg.exe at least in the same directory, you can get it here: https://www.ffmpeg.org/download.html ). Of course you also need all the other libraries cv2, numpy, pyaudio, installed like herewith: pip install opencv-python numpy pyaudio You can now run the code directly: #!/usr/bin/env python # -*- coding: utf-8 -*- # VideoRecorder.py from __future__ import print_function, division import numpy as np import cv2 import pyaudio import wave import threading import time import subprocess import os class VideoRecorder(): "Video class based on openCV" def __init__(self, name="temp_video.avi", fourcc="MJPG", sizex=640, sizey=480, camindex=0, fps=30): self.open = True self.device_index = camindex self.fps = fps # fps should be the minimum constant rate at which the camera can self.fourcc = fourcc # capture images (with no decrease in speed over time; testing is required) self.frameSize = (sizex, sizey) # video formats and sizes also depend and vary according to the camera used self.video_filename = name self.video_cap = cv2.VideoCapture(self.device_index) self.video_writer = cv2.VideoWriter_fourcc(*self.fourcc) self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, self.frameSize) self.frame_counts = 1 self.start_time = time.time() def record(self): "Video starts being recorded" # counter = 1 timer_start = time.time() timer_current = 0 while self.open: ret, video_frame = self.video_cap.read() if ret: self.video_out.write(video_frame) # print(str(counter) + " " + str(self.frame_counts) + " frames written " + str(timer_current)) self.frame_counts += 1 # counter += 1 # timer_current = time.time() - timer_start time.sleep(1/self.fps) # gray = cv2.cvtColor(video_frame, cv2.COLOR_BGR2GRAY) # cv2.imshow('video_frame', gray) # cv2.waitKey(1) else: break def stop(self): "Finishes the video recording therefore the thread too" if self.open: self.open=False self.video_out.release() self.video_cap.release() cv2.destroyAllWindows() def start(self): "Launches the video recording function using a thread" video_thread = threading.Thread(target=self.record) video_thread.start() class AudioRecorder(): "Audio class based on pyAudio and Wave" def __init__(self, filename="temp_audio.wav", rate=44100, fpb=1024, channels=2): self.open = True self.rate = rate self.frames_per_buffer = fpb self.channels = channels self.format = pyaudio.paInt16 self.audio_filename = filename self.audio = pyaudio.PyAudio() self.stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate, input=True, frames_per_buffer = self.frames_per_buffer) self.audio_frames = [] def record(self): "Audio starts being recorded" self.stream.start_stream() while self.open: data = self.stream.read(self.frames_per_buffer) self.audio_frames.append(data) if not self.open: break def stop(self): "Finishes the audio recording therefore the thread too" if self.open: self.open = False self.stream.stop_stream() self.stream.close() self.audio.terminate() waveFile = wave.open(self.audio_filename, 'wb') waveFile.setnchannels(self.channels) waveFile.setsampwidth(self.audio.get_sample_size(self.format)) waveFile.setframerate(self.rate) waveFile.writeframes(b''.join(self.audio_frames)) waveFile.close() def start(self): "Launches the audio recording function using a thread" audio_thread = threading.Thread(target=self.record) audio_thread.start() def start_AVrecording(filename="test"): global video_thread global audio_thread video_thread = VideoRecorder() audio_thread = AudioRecorder() audio_thread.start() video_thread.start() return filename def start_video_recording(filename="test"): global video_thread video_thread = VideoRecorder() video_thread.start() return filename def start_audio_recording(filename="test"): global audio_thread audio_thread = AudioRecorder() audio_thread.start() return filename def stop_AVrecording(filename="test"): audio_thread.stop() frame_counts = video_thread.frame_counts elapsed_time = time.time() - video_thread.start_time recorded_fps = frame_counts / elapsed_time print("total frames " + str(frame_counts)) print("elapsed time " + str(elapsed_time)) print("recorded fps " + str(recorded_fps)) video_thread.stop() # Makes sure the threads have finished while threading.active_count() > 1: time.sleep(1) # Merging audio and video signal if abs(recorded_fps - 6) >= 0.01: # If the fps rate was higher/lower than expected, re-encode it to the expected print("Re-encoding") cmd = "ffmpeg -r " + str(recorded_fps) + " -i temp_video.avi -pix_fmt yuv420p -r 6 temp_video2.avi" subprocess.call(cmd, shell=True) print("Muxing") cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video2.avi -pix_fmt yuv420p " + filename + ".avi" subprocess.call(cmd, shell=True) else: print("Normal recording\nMuxing") cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video.avi -pix_fmt yuv420p " + filename + ".avi" subprocess.call(cmd, shell=True) print("..") def file_manager(filename="test"): "Required and wanted processing of final files" local_path = os.getcwd() if os.path.exists(str(local_path) + "/temp_audio.wav"): os.remove(str(local_path) + "/temp_audio.wav") if os.path.exists(str(local_path) + "/temp_video.avi"): os.remove(str(local_path) + "/temp_video.avi") if os.path.exists(str(local_path) + "/temp_video2.avi"): os.remove(str(local_path) + "/temp_video2.avi") # if os.path.exists(str(local_path) + "/" + filename + ".avi"): # os.remove(str(local_path) + "/" + filename + ".avi") if __name__ == '__main__': start_AVrecording() time.sleep(5) stop_AVrecording() file_manager() A: If you notice misalignment between video and audio by the code above, please see my solution below I think the most rated answer above does a great job. However, it did not work perfectly when I was using it,especially when you use a low fps rate (say 10). The main issue is with video recording. In order to properly synchronize video and audio recording with ffmpeg, one has to make sure that cv2.VideoCapture() and cv2.VideoWriter() share exact same FPS, because the recorded video time length is solely determined by fps rate and the number of frames. Following is my suggested update: #!/usr/bin/env python # -*- coding: utf-8 -*- # VideoRecorder.py from __future__ import print_function, division import numpy as np import cv2 import pyaudio import wave import threading import time import subprocess import os import ffmpeg class VideoRecorder(): "Video class based on openCV" def __init__(self, name="temp_video.avi", fourcc="MJPG", sizex=640, sizey=480, camindex=0, fps=30): self.open = True self.device_index = camindex self.fps = fps # fps should be the minimum constant rate at which the camera can self.fourcc = fourcc # capture images (with no decrease in speed over time; testing is required) self.frameSize = (sizex, sizey) # video formats and sizes also depend and vary according to the camera used self.video_filename = name self.video_cap = cv2.VideoCapture(self.device_index) self.video_cap.set(cv2.CAP_PROP_FPS, self.fps) self.video_writer = cv2.VideoWriter_fourcc(*self.fourcc) self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, self.frameSize) self.frame_counts = 1 self.start_time = time.time() def record(self): "Video starts being recorded" # counter = 1 timer_start = time.time() timer_current = 0 while self.open: ret, video_frame = self.video_cap.read() if ret: self.video_out.write(video_frame) # print(str(counter) + " " + str(self.frame_counts) + " frames written " + str(timer_current)) self.frame_counts += 1 # print(self.frame_counts) # counter += 1 # timer_current = time.time() - timer_start # time.sleep(1/self.fps) # gray = cv2.cvtColor(video_frame, cv2.COLOR_BGR2GRAY) # cv2.imshow('video_frame', gray) # cv2.waitKey(1) else: break def stop(self): "Finishes the video recording therefore the thread too" if self.open: self.open=False self.video_out.release() self.video_cap.release() cv2.destroyAllWindows() def start(self): "Launches the video recording function using a thread" video_thread = threading.Thread(target=self.record) video_thread.start() class AudioRecorder(): "Audio class based on pyAudio and Wave" def __init__(self, filename="temp_audio.wav", rate=44100, fpb=1024, channels=2): self.open = True self.rate = rate self.frames_per_buffer = fpb self.channels = channels self.format = pyaudio.paInt16 self.audio_filename = filename self.audio = pyaudio.PyAudio() self.stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate, input=True, frames_per_buffer = self.frames_per_buffer) self.audio_frames = [] def record(self): "Audio starts being recorded" self.stream.start_stream() while self.open: data = self.stream.read(self.frames_per_buffer) self.audio_frames.append(data) if not self.open: break def stop(self): "Finishes the audio recording therefore the thread too" if self.open: self.open = False self.stream.stop_stream() self.stream.close() self.audio.terminate() waveFile = wave.open(self.audio_filename, 'wb') waveFile.setnchannels(self.channels) waveFile.setsampwidth(self.audio.get_sample_size(self.format)) waveFile.setframerate(self.rate) waveFile.writeframes(b''.join(self.audio_frames)) waveFile.close() def start(self): "Launches the audio recording function using a thread" audio_thread = threading.Thread(target=self.record) audio_thread.start() def start_AVrecording(filename="test"): global video_thread global audio_thread video_thread = VideoRecorder() audio_thread = AudioRecorder() audio_thread.start() video_thread.start() return filename def start_video_recording(filename="test"): global video_thread video_thread = VideoRecorder() video_thread.start() return filename def start_audio_recording(filename="test"): global audio_thread audio_thread = AudioRecorder() audio_thread.start() return filename def stop_AVrecording(filename="test"): audio_thread.stop() frame_counts = video_thread.frame_counts elapsed_time = time.time() - video_thread.start_time recorded_fps = frame_counts / elapsed_time print("total frames " + str(frame_counts)) print("elapsed time " + str(elapsed_time)) print("recorded fps " + str(recorded_fps)) video_thread.stop() # Makes sure the threads have finished while threading.active_count() > 1: time.sleep(1) video_stream = ffmpeg.input(video_thread.video_filename) audio_stream = ffmpeg.input(audio_thread.audio_filename) ffmpeg.output(audio_stream, video_stream, 'out.mp4').run(overwrite_output=True) # # Merging audio and video signal # if abs(recorded_fps - 6) >= 0.01: # If the fps rate was higher/lower than expected, re-encode it to the expected # print("Re-encoding") # cmd = "ffmpeg -r " + str(recorded_fps) + " -i temp_video.avi -pix_fmt yuv420p -r 6 temp_video2.avi" # subprocess.call(cmd, shell=True) # print("Muxing") # cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video2.avi -pix_fmt yuv420p " + filename + ".avi" # subprocess.call(cmd, shell=True) # else: # print("Normal recording\nMuxing") # cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video.avi -pix_fmt yuv420p " + filename + ".avi" # subprocess.call(cmd, shell=True) # print("..") def file_manager(filename="test"): "Required and wanted processing of final files" local_path = os.getcwd() if os.path.exists(str(local_path) + "/temp_audio.wav"): os.remove(str(local_path) + "/temp_audio.wav") if os.path.exists(str(local_path) + "/temp_video.avi"): os.remove(str(local_path) + "/temp_video.avi") if os.path.exists(str(local_path) + "/temp_video2.avi"): os.remove(str(local_path) + "/temp_video2.avi") # if os.path.exists(str(local_path) + "/" + filename + ".avi"): # os.remove(str(local_path) + "/" + filename + ".avi") if __name__ == '__main__': start_AVrecording() # try: # while True: # pass # except KeyboardInterrupt: # stop_AVrecording() time.sleep(10) stop_AVrecording() print("finishing recording") file_manager() A: Using everyone's contributions and following the suggestion of Paul I was able to come up with the following code: Recorder.py #!/usr/bin/env python # -*- coding: utf-8 -*- # VideoRecorder.py from __future__ import print_function, division import numpy as np import sys import cv2 import pyaudio import wave import threading import time import subprocess import os import ffmpeg REC_FOLDER = "recordings/" class Recorder(): def __init__(self, filename): self.filename = filename self.video_thread = self.VideoRecorder(self, REC_FOLDER + filename) self.audio_thread = self.AudioRecorder(self, REC_FOLDER + filename) def startRecording(self): self.video_thread.start() self.audio_thread.start() def stopRecording(self): self.video_thread.stop() self.audio_thread.stop() def saveRecording(self): #Save audio / Show video resume self.audio_thread.saveAudio() self.video_thread.showFramesResume() #Merges both streams and writes video_stream = ffmpeg.input(self.video_thread.video_filename) audio_stream = ffmpeg.input(self.audio_thread.audio_filename) while (not os.path.exists(self.audio_thread.audio_filename)): print("waiting for audio file to exit...") stream = ffmpeg.output(video_stream, audio_stream, REC_FOLDER + self.filename +".mp4") try: ffmpeg.run(stream, capture_stdout=True, capture_stderr=True, overwrite_output=True) except ffmpeg.Error as e: print(e.stdout, file=sys.stderr) print(e.stderr, file=sys.stderr) class VideoRecorder(): "Video class based on openCV" def __init__(self, recorder, name, fourcc="MJPG", frameSize=(640,480), camindex=0, fps=15): self.recorder = recorder self.open = True self.duration = 0 self.device_index = camindex self.fps = fps # fps should be the minimum constant rate at which the camera can self.fourcc = fourcc # capture images (with no decrease in speed over time; testing is required) self.video_filename = name + ".avi" # video formats and sizes also depend and vary according to the camera used self.video_cap = cv2.VideoCapture(self.device_index, cv2.CAP_DSHOW) self.video_writer = cv2.VideoWriter_fourcc(*fourcc) self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, frameSize) self.frame_counts = 1 self.start_time = time.time() def record(self): "Video starts being recorded" counter = 1 while self.open: ret, video_frame = self.video_cap.read() if ret: self.video_out.write(video_frame) self.frame_counts += 1 counter += 1 self.duration += 1/self.fps if (video_frame is None): print("I WAS NONEEEEEEEEEEEEEEEEEEEEEE") gray = cv2.cvtColor(video_frame, cv2.COLOR_BGR2GRAY) cv2.imshow('video_frame', gray) cv2.waitKey(1) while(self.duration - self.recorder.audio_thread.duration >= 0.2 and self.recorder.audio_thread.open): time.sleep(0.2) else: break #Release Video self.video_out.release() self.video_cap.release() cv2.destroyAllWindows() self.video_out = None def stop(self): "Finishes the video recording therefore the thread too" self.open=False def start(self): "Launches the video recording function using a thread" self.thread = threading.Thread(target=self.record) self.thread.start() def showFramesResume(self): #Only stop of video has all frames frame_counts = self.frame_counts elapsed_time = time.time() - self.start_time recorded_fps = self.frame_counts / elapsed_time print("total frames " + str(frame_counts)) print("elapsed time " + str(elapsed_time)) print("recorded fps " + str(recorded_fps)) class AudioRecorder(): "Audio class based on pyAudio and Wave" def __init__(self, recorder, filename, rate=44100, fpb=1024, channels=1, audio_index=0): self.recorder = recorder self.open = True self.rate = rate self.duration = 0 self.frames_per_buffer = fpb self.channels = channels self.format = pyaudio.paInt16 self.audio_filename = filename + ".wav" self.audio = pyaudio.PyAudio() self.stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate, input=True, input_device_index=audio_index, frames_per_buffer = self.frames_per_buffer) self.audio_frames = [] def record(self): "Audio starts being recorded" self.stream.start_stream() t_start = time.time_ns() while self.open: try: self.duration += self.frames_per_buffer / self.rate data = self.stream.read(self.frames_per_buffer) self.audio_frames.append(data) except Exception as e: print('\n' + '*'*80) print('PyAudio read exception at %.1fms\n' % ((time.time_ns() - t_start)/10**6)) print(e) print('*'*80 + '\n') while(self.duration - self.recorder.video_thread.duration >= 0.5): time.sleep(0.5) #Closes audio stream self.stream.stop_stream() self.stream.close() self.audio.terminate() def stop(self): "Finishes the audio recording therefore the thread too" self.open = False def start(self): "Launches the audio recording function using a thread" self.thread = threading.Thread(target=self.record) self.thread.start() def saveAudio(self): #Save Audio File waveFile = wave.open(self.audio_filename, 'wb') waveFile.setnchannels(self.channels) waveFile.setsampwidth(self.audio.get_sample_size(self.format)) waveFile.setframerate(self.rate) waveFile.writeframes(b''.join(self.audio_frames)) waveFile.close() Main.py from recorder import Recorder import time recorder = Recorder("test1") recorder.startRecording() time.sleep(240) recorder.stopRecording() recorder.saveRecording() With this solution, the camera and the audio will wait for each other. I also tried the FFmpeg Re-encoding and Muxing and even though it was able to synchronize the audio with video, the video had a massive quality drop. A: You can do offline html,js code to do video with audio recording. Using python lib python webview open that page. It should work fine. A: I was randomly getting "[Errno -9999] Unanticipated host error" while using JRodrigoF's solution and found that it's due to a race condition where an audio stream can be closed just before being read for the last time inside record() of AudioRecorder class. I modified slightly so that all the closing procedures are done after the while loop and added a function list_audio_devices() that shows the list of audio devices to select from. I also added an audio device index as a parameter to choose an audio device. #!/usr/bin/env python # -*- coding: utf-8 -*- # VideoRecorder.py from __future__ import print_function, division import numpy as np import cv2 import pyaudio import wave import threading import time import subprocess import os class VideoRecorder(): "Video class based on openCV" def __init__(self, name="temp_video.avi", fourcc="MJPG", sizex=640, sizey=480, camindex=0, fps=30): self.open = True self.device_index = camindex self.fps = fps # fps should be the minimum constant rate at which the camera can self.fourcc = fourcc # capture images (with no decrease in speed over time; testing is required) self.frameSize = (sizex, sizey) # video formats and sizes also depend and vary according to the camera used self.video_filename = name self.video_cap = cv2.VideoCapture(self.device_index) self.video_writer = cv2.VideoWriter_fourcc(*self.fourcc) self.video_out = cv2.VideoWriter(self.video_filename, self.video_writer, self.fps, self.frameSize) self.frame_counts = 1 self.start_time = time.time() def record(self): "Video starts being recorded" # counter = 1 timer_start = time.time() timer_current = 0 while self.open: ret, video_frame = self.video_cap.read() if ret: self.video_out.write(video_frame) # print(str(counter) + " " + str(self.frame_counts) + " frames written " + str(timer_current)) self.frame_counts += 1 # counter += 1 # timer_current = time.time() - timer_start time.sleep(1/self.fps) # gray = cv2.cvtColor(video_frame, cv2.COLOR_BGR2GRAY) # cv2.imshow('video_frame', gray) # cv2.waitKey(1) else: break def stop(self): "Finishes the video recording therefore the thread too" if self.open: self.open=False self.video_out.release() self.video_cap.release() cv2.destroyAllWindows() def start(self): "Launches the video recording function using a thread" video_thread = threading.Thread(target=self.record) video_thread.start() class AudioRecorder(): "Audio class based on pyAudio and Wave" def __init__(self, filename="temp_audio.wav", rate=44100, fpb=2**12, channels=1, audio_index=0): self.open = True self.rate = rate self.frames_per_buffer = fpb self.channels = channels self.format = pyaudio.paInt16 self.audio_filename = filename self.audio = pyaudio.PyAudio() self.stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate, input=True, input_device_index=audio_index, frames_per_buffer = self.frames_per_buffer) self.audio_frames = [] def record(self): "Audio starts being recorded" self.stream.start_stream() t_start = time.time_ns() while self.open: try: data = self.stream.read(self.frames_per_buffer) self.audio_frames.append(data) except Exception as e: print('\n' + '*'*80) print('PyAudio read exception at %.1fms\n' % ((time.time_ns() - t_start)/10**6)) print(e) print('*'*80 + '\n') time.sleep(0.01) self.stream.stop_stream() self.stream.close() self.audio.terminate() waveFile = wave.open(self.audio_filename, 'wb') waveFile.setnchannels(self.channels) waveFile.setsampwidth(self.audio.get_sample_size(self.format)) waveFile.setframerate(self.rate) waveFile.writeframes(b''.join(self.audio_frames)) waveFile.close() def stop(self): "Finishes the audio recording therefore the thread too" if self.open: self.open = False def start(self): "Launches the audio recording function using a thread" audio_thread = threading.Thread(target=self.record) audio_thread.start() def start_AVrecording(filename="test", audio_index=0, sample_rate=44100): global video_thread global audio_thread video_thread = VideoRecorder() audio_thread = AudioRecorder(audio_index=audio_index, rate=sample_rate) audio_thread.start() video_thread.start() return filename def start_video_recording(filename="test"): global video_thread video_thread = VideoRecorder() video_thread.start() return filename def start_audio_recording(filename="test", audio_index=0, sample_rate=44100): global audio_thread audio_thread = AudioRecorder(audio_index=audio_index, rate=sample_rate) audio_thread.start() return filename def stop_AVrecording(filename="test"): audio_thread.stop() frame_counts = video_thread.frame_counts elapsed_time = time.time() - video_thread.start_time recorded_fps = frame_counts / elapsed_time print("total frames " + str(frame_counts)) print("elapsed time " + str(elapsed_time)) print("recorded fps " + str(recorded_fps)) video_thread.stop() # Makes sure the threads have finished while threading.active_count() > 1: time.sleep(1) # Merging audio and video signal if abs(recorded_fps - 6) >= 0.01: # If the fps rate was higher/lower than expected, re-encode it to the expected print("Re-encoding") cmd = "ffmpeg -r " + str(recorded_fps) + " -i temp_video.avi -pix_fmt yuv420p -r 6 temp_video2.avi" subprocess.call(cmd, shell=True) print("Muxing") cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video2.avi -pix_fmt yuv420p " + filename + ".avi" subprocess.call(cmd, shell=True) else: print("Normal recording\nMuxing") cmd = "ffmpeg -y -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video.avi -pix_fmt yuv420p " + filename + ".avi" subprocess.call(cmd, shell=True) print("..") def file_manager(filename="test"): "Required and wanted processing of final files" local_path = os.getcwd() if os.path.exists(str(local_path) + "/temp_audio.wav"): os.remove(str(local_path) + "/temp_audio.wav") if os.path.exists(str(local_path) + "/temp_video.avi"): os.remove(str(local_path) + "/temp_video.avi") if os.path.exists(str(local_path) + "/temp_video2.avi"): os.remove(str(local_path) + "/temp_video2.avi") # if os.path.exists(str(local_path) + "/" + filename + ".avi"): # os.remove(str(local_path) + "/" + filename + ".avi") def list_audio_devices(name_filter=None): pa = pyaudio.PyAudio() device_index = None sample_rate = None for x in range(pa.get_device_count()): info = pa.get_device_info_by_index(x) print(pa.get_device_info_by_index(x)) if name_filter is not None and name_filter in info['name']: device_index = info['index'] sample_rate = int(info['defaultSampleRate']) break return device_index, sample_rate if __name__ == '__main__': start_AVrecording() time.sleep(5) stop_AVrecording() file_manager()
unknown
d2583
train
There is currently a bug I recommend oyu to "star" it to increase visibility, so it hopefully gets fixed soon. A: Try this: Unable to open Google xlsx spreadsheet / Also Google Drive permission Blocked The same solution logic can solve this problem. [ ]
unknown
d2584
train
Underscore's _.template doesn't do anything to whitespace so you have to arrange the whitespace in your template to match the output you need. Something like this: <a>NAME</a><% if(some_condition) { %> yours <% } else { %> <a class="name" href="/kkk/<%- ID %>"><%= NAME %></a> <% }%> Demo (look in your console): http://jsfiddle.net/ambiguous/gbx3M/ Or the more readable: <a>NAME</a><% if(some_condition) { %> yours <% } else { %> <a class="name" href="/kkk/<%- ID %>"><%= NAME %></a> <% } %> Demo (look in your console): http://jsfiddle.net/ambiguous/xuxLQ/ If you really need no space between the tags at all then I think you're stuck with this: <% if(some_condition) { %><a>NAME</a>yours<% } else { %><a>NAME<a class="name" href="/kkk/<%- ID %>"><%= NAME %></a><% } %> and manually stripping off leading/trailing whitespace: http://jsfiddle.net/ambiguous/LN7eU/ Another option is to use CSS to float and position the elements so that the whitespace becomes irrelevant. If none of those options are good enough then Underscore's (intentionally) simple and minimal templates might not be for you. A: I also found that you can get rid of this unwanted whitespace by tweaking the regular expression that Underscore uses to evaluate javascript code. _.templateSettings.evaluate = /(?:\n\s*<%|<%)([\s\S]+?)%>/g A: I succeeded it by using a forked version of tpl.js: https://github.com/ZeeAgency/requirejs-tpl You can find my version here: https://github.com/GuillaumeCisco/requirejs-tpl/ Basically I add a .replace(/\s\s+/g, '') when I receive the data, allowing me to trim spaces between tags by default.
unknown
d2585
train
It's because you return a tuple, in your case (Class User, integer). You should return a custom class: public class Response { public List<User> Users; public int Count; } .... return (new Response { Users = entitiesList, Count = count});
unknown
d2586
train
Example of using two posted values in a single array: <!-- HTML --> <input name="address[]" type="text" value="111" /> <input name="address[]" type="text" value="222" /> Notice the name attributes. // PHP $address = $_POST['address'][0] . ' ' . $_POST['address'][1]; echo $address; // prints "111 222" UPDATE Before your script loops through the $_POST array, merge the fields, like so: $preformat = $_POST['Home_Address_1']; $preformat .= ' ' . $_POST['Home_Address_2']; $preformat .= ' ' . $_POST['Home_Address_3']; $_POST['Home_Address_3'] = trim($preformat); Then the last Home Address field contains all three. A: Try array_merge()...http://php.net/manual/en/function.array-merge.php A: Try array_merge with shuffle $merged = array_merge($arr1,$arr2); shuffle($merged); with regards Wazzy
unknown
d2587
train
I take it m is a scalar, right? Consider the simple case m=1; you can generalize for other values of m by letting H* = sqrt(m) H and f* = sqrt(m) f and using the solution method given here. So now you're trying to minimise ||A x - b||^2 + ||H x - f||^2. Let A* = [A' | H']' and let b* = [b' | f']' (i.e. stack up A on top of H and b on top of f) and solve the original problem of non-negative linear least squares on ||A* x - b*||^2 with the constraint that all elements of vector x ≥ 0 .
unknown
d2588
train
Your code as it stands sets On Error Resume Next at the end of the first time through the loop, and from that point on ignores any and all errors. That's bad. The general method of using OERN should be Other non error causing code Optionally initialise variables in preparation for error trap On Error Resume Next Execute the instruction that might cause an error On Error GoTo 0 If (test if instruction succeeded) Then Process the result Else Optionally handle the error case End If A: You can always put a conditional check statement based on the error you receive for invalid stocks, if you are getting empty value in myrequest on invalid stock. You can write your logic like below and update price value to 0. If myrequest is Nothing Then 'For Invalid Stocks End or If myrequest.ResponseText = "" Then 'For Invalid Stocks End Let me know if it helps. Otherwise share the JSON response for both valid and invalid stocks. Update: Based on the value of myrequest.ResponseStatus for invalid response, update the <add-condition> condition in If statement according to your requirement. For Each X In rng Dim Json As Object Dim i symbol = X Set myrequest = CreateObject("WinHttp.WinHttpRequest.5.1") myrequest.Open "Get", "http://phisix-api.appspot.com/stocks/" & symbol & ".json" On Error Resume Next myrequest.Send On Error GoTo 0 Debug.Print myrequest.ResponseStatus If <add-condition> Then Set Json = JsonConverter.ParseJson(myrequest.ResponseText) i = Json("stock")(1)("price")("amount") Else i = 0 End If ws.Range(Cells(n, 2), Cells(n, 2)) = i n = n + 1 Next X
unknown
d2589
train
Try this data["column_name"] = data["column_name"].apply(lambda x: x.replace("characters_need_to_replace", "new_characters"))
unknown
d2590
train
You can do client-side postprocessing and enrich result with missing records. Helper function for generating months: static IEnumerable<DateTime> GetMonths(DateTime startDate, DateTime endDate) { startDate = new DateTime(startDate.Year, startDate.Month, 1); endDate = new DateTime(endDate.Year, endDate.Month, 1); while (startDate < endDate) { yield return startDate; startDate = startDate.AddMonths(1); } } Postprocessing: var currentDate = DateTime.Now; var yearAgo = currentDate.AddYears(-1); var months = GetMonths(yearAgo, currentDate); var stats = DashboardStats().ToList(); // left join months to actual data var query = from m in months join s in stats on new { m.Year, m.Month } equals new { s.Year, s.Month } into gj from s in gj.DefaultIfEmpty() select s ?? new DashboardGrouping { Year = m.Year, Month = m.Month, TotalSale = 0 }; var result = query.ToList();
unknown
d2591
train
Slighly nicer version of my above comment: #!perl -T use warnings; use strict; scalar(@ARGV) > 0 or die "Use: $0 <pid>"; my $pid = $ARGV[0]; $pid = oct($pid) if $pid=~/^0/; # support hex and octal PIDs $pid += 0; $pid = abs(int($pid)); # make sure we have a number open(my $maps, "<", "/proc/".$pid."/maps") or die "can't open maps file for pid ".$pid; my $max = 0; my $end = 0; while (<$maps>) { /([0-9a-f]+)-([0-9a-f]+)/; $max = hex ($1) - $end if $max < hex ($1) - $end; $end = hex ($2); } close ($maps); END { print "$max\n"; } A: Probably not exactly what you want, but from inside a process it is possible to do binary search by mmaping without allocating. I.e. mmap(4GB), if that fails mmap(2GB), if that succeeds mmap(3GB), and so on. A: we get out of memory errors. We think it failing to mmap large files because the app's memory space is fragmented. However, one can also get OOM errors while still having lots of free virtual address ranges on paper, for example by sufficient lack of RAM+swap. Furthermore your system and/or program(s) may have overcomitting turned off (sysctl -a), or have swapping inhibited (mlock(2)), or you actually have a very blunt limit on mappings (ulimit -v) — the latter is easy to run in given some distributions set such ulimits one way or another.
unknown
d2592
train
The problem with Firefox and Geckodriver is that it produces so many log entries which are not relevant for most users. To reduce the log entries in your Java program you have following options: * *Use a different Browser e.g. Chrome which produces less log entries. *Redirect the Geckodriver log entries. You can redirect the log entries of Geckodriver with following line to a file: System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"C:\\temp\\logs.txt"); For more information see this link.
unknown
d2593
train
I've no DB2 experience but can't you just cast 'a' & 'd' to the same types. That are large enough to handle both formats, obviously. A: I have used the cast function to convert the columns type into the same type(varchar with a large length).So i used union without problems. When i needed their original type, back again, i used the same cast function(this time i converted the values into float), and i got the result i wanted.
unknown
d2594
train
I assume you hit the issue with SimpleStrategy and multi-dc when using LOCAL_ONE (spark connector default) consistency. It will look for a node in the local DC to make the request to but theres a chance that all the replicas exist in a different DC and wont meet the requirement. (CASSANDRA-12053) If you change your consistency level (input.consistency.level to ONE) I think it will be resolved. You should also really consider using the network topology strategy instead.
unknown
d2595
train
Tomcat 6 does not and will not support Servlet Specification 3.0. You should attempt doing this on Tomcat 7, but I'm not really sure whether this functionality is present in the beta release that is currently available. The functionality is expected to be present in the production release though. You could continue using Apache Commons FileUpload like posted in the other answer, or you could use Glassfish (depending on the current phase and type of your project). A: Check out Apache Commons Fileupload. It gives you a programmatic API to parse a multipart request, and iterate through the parts of it individually. I've used it in the past for straightforward multipart processing and it does the job fine without being overly complicated. A: when we used post method than data are encrypted so we have to used servletfileupload to get requested data and using FileItemIterator we can get all form data. i already answer on this link How to process a form sent Google Web Toolkit in a servlet
unknown
d2596
train
Tried and tested on my Windows box: #include <stdio.h> #include <stdlib.h> #include <io.h> void matrix_output_printf() { for( int i = 0; i < 3; i++ ) { for( int j = 0; j < 3; j++ ) printf( "%d\t", i+j ); printf( "\n" ); } } int main( void ) { int saved = _dup( fileno( stdout ) ); freopen( "file.txt", "w", stdout ); matrix_output_printf(); fclose( stdout ); _dup2( saved, 1 ); printf( "hello\n" ); return 0; } A: If stdout was originally tied to the console, you can reopen the stream to /dev/tty: #include <stdio.h> void matrix_output_printf(void) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("%d\t", i + j); } printf("\n"); } } int main() { freopen("file.txt", "w", stdout); matrix_output_printf(); freopen("/dev/tty", "w", stdout); printf("hello"); return 0; } This should work on most unix systems, such as macOS, but if stdout was redirected to another file or device, reopening it with freopen won't work. You could try and duplicate the system handle with dup() and use fdopen() to open a standard stream after closing stdout, but there is no guarantee that the stream returned by fdopen will be the same as stdout. Using freopen for your purpose is a hack. A much better approach is to rewrite matrix_output_printf to take a FILE * argument for the output stream, or a const char *filename for the name of the file to produce: void matrix_output_printf(const char *filename) { FILE *fp = stdout; if (filename) { fp = fopen(filename, "w"); if (fp == NULL) { /* handle error */ return; } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { fprintf(fp, "%d\t", i + j); } fprintf(fp, "\n"); } if (filename) fclose(fp); } A: Another option: * *Flush the stream *Duplicate stdout's file descriptor before calling the function, duplicate a file descriptor open to the desired file to the stream's original file descriptor value *Call the function *Restore the original stdout descriptor Similar to this: #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> void matrix_output_printf(void){ for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ printf("%d\t", i+j); } printf("\n"); } } int main() { int fd = open("file.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); int savedStdoutFD = dup(fileno(stdout)); fflush(stdout); dup2(fd, STDOUT_FILENO); close(fd); matrix_output_printf(); fflush(stdout); dup2(savedStdoutFD, STDOUT_FILENO); close(savedStdoutFD); printf("hello\n"); return 0; } Note that this code is inherently unsafe to use in a multithreaded process. @chqrlie had the best answer: "A much better approach is to rewrite matrix_output_printf to take a FILE * argument for the output stream, or a const char *filename for the name of the file to produce".
unknown
d2597
train
It looks like you want to make string copy for permutation in these lines w= a[i].empname; a[i].empname=a[k].empname; a[k].empname=w; you can not make string copy in this way in C you have to use strcpy() instead char * strcpy ( char * destination, const char * source ); so you can make the permutation in this way strcpy(w, a[i].empname); strcpy(a[i].empname, a[k].empname); strcpy(a[k].empname, w); A: Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and its value will be the address of the first element in the array. This converted expression is not an lvalue, meaning it may not be the target of an assignment. If you want to copy the contents of one array to another, you'll need to use a library function. For C strings (arrays of char with a terminating 0 value) use strcpy or strncpy. For other array types, use memcpy. So, those lines should be strcpy( w, a[i].empname ); strcpy( a[i].empname, a[k].empname ); strcpy( a[k].empname, a[i].empname );
unknown
d2598
train
No. The query that you have written only returns rows from t1. You cannot multiply rows using a where clause (well, almost never and not in Oracle). One reason for using exists or in is so you don't have to worry about duplicates, the way you would need to worry with a join. A: No - think of exists as a True/False function. True: returns >0 rows; False: returns 0 rows. So it doesn't matter if there are duplicates.
unknown
d2599
train
You can use BigInteger : BigInteger big = new BigInteger("223175087923687075112234402528973166755"); System.out.println(big.toString(16)); Output : a7e5f55e1dbb48b799268e1a6d8618a3
unknown
d2600
train
As noted in Josh Friedlander's comment, in cuDF the object data type is explicitly for strings. In pandas, this is the data type for strings and also arbitrary/mixed data types (such as lists, dicts, arrays, etc.). This can explain this memory behavior in many scenarios, but doesn't explain it if both columns are strings. Assuming both columns are strings, there is still likely to be a difference. In cuDF, string columns are represented as a single allocation of memory for the raw characters, an associated null mask allocation to handle missing values, and an associated allocation to handle row offsets, consistent with the Apache Arrow memory specification. So, it’s likely that whatever is represented in these columns is more efficient in this data structure in cuDF than as the default string data structure in Pandas (which is going to be true essentially all the time). The following example may be helpful: import cudf import pandas as pd Xc = cudf.datasets.randomdata(nrows=1000, dtypes={"id": int, "x": int, "y": int}) Xp = Xc.to_pandas() print(Xp.astype("object").memory_usage(deep=True), "\n") print(Xc.astype("object").memory_usage(deep=True), "\n") print(Xp.astype("string[pyarrow]").memory_usage(deep=True)) Index 128 id 36000 x 36000 y 36000 dtype: int64 id 7487 x 7502 y 7513 Index 0 dtype: int64 Index 128 id 7483 x 7498 y 7509 dtype: int64 Using the Arrow spec string dtype in pandas saves quite a bit of memory and generally matches cuDF.
unknown