content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
Help protect the Great Barrier Reef with TensorFlow on Kaggle Join Challenge tf.contrib.linear_optimizer.SparseFeatureColumn View source on GitHub Represents a sparse feature column. Contains three tensors representing a sparse feature column, they are example indices (int64), feature indices (int64), and feature values (float). Feature weights are optional, and are treated as 1.0f if missing. For example, consider a batch of 4 examples, which contains the following features in a particular SparseFeatureColumn: • Example 0: feature 5, value 1 • Example 1: feature 6, value 1 and feature 10, value 0.5 • Example 2: no features • Example 3: two copies of feature 2, value 1 This SparseFeatureColumn will be represented as follows: <0, 5, 1> <1, 6, 1> <1, 10, 0.5> <3, 2, 1> <3, 2, 1> For a batch of 2 examples below: • Example 0: feature 5 • Example 1: feature 6 is represented by SparseFeatureColumn as: <0, 5, 1> <1, 6, 1> example_indices A 1-D int64 tensor of shape [N]. Also, accepts python lists, or numpy arrays. feature_indices A 1-D int64 tensor of shape [N]. Also, accepts python lists, or numpy arrays. feature_values An optional 1-D tensor float tensor of shape [N]. Also, accepts python lists, or numpy arrays. example_indices The example indices represented as a dense tensor. feature_indices The feature indices represented as a dense tensor. feature_values The feature values represented as a dense tensor.
__label__pos
0.937291
Start Your Project with Us Whatever your project size is, we will handle it well with all the standards fulfilled! We are here to give 100% satisfaction. • Any feature, you ask, we develop • 24x7 support worldwide • Real-time performance dashboard • Complete transparency • Dedicated account manager • Customized solutions to fulfill data scraping goals Careers For job seekers, please visit our Career Page or send your resume to [email protected]. What-Can-Web-Scraping-Do-for-Tenaquip-Grainger-Fastenal-and-Zoro Introduction In today's fast-paced industrial marketplace, businesses need timely and accurate data to stay ahead. Web scraping offers a powerful way to gather critical information about product offerings, pricing, and distributor details from top industrial supply websites like Tenaquip, Grainger, Fastenal, Zoro, Gas and Supply, and Motion. For companies in the industrial sector, having up-to-date data is key to maintaining a competitive edge. By leveraging web scraping, businesses can access and analyze this data efficiently to optimize their pricing strategies and improve overall decision-making. This blog explores how web scraping can unlock the potential of these platforms, focusing on extracting product and pricing information to inform your business strategy. About Tenaquip, Grainger, Fastenal, Gas and Supply, Motion, and Zoro In the competitive world of industrial supply and distribution, businesses need reliable, up-to-date information to make informed decisions. Companies like Tenaquip, Grainger, Fastenal, Gas and Supply, Motion, and Zoro are major players in this sector, providing a wide range of products and services to meet the needs of industries worldwide. Web scraping is an invaluable tool for extracting and analyzing data from these sources, helping businesses stay competitive and informed. Tenaquip Tenaquip Tenaquip is a leading industrial supply distributor based in Canada. Known for its extensive catalog, Tenaquip offers a diverse range of products, including tools, safety equipment, and maintenance supplies. Tenaquip’s vast inventory and commitment to customer service make it a significant player in the industrial sector. Tenaquip data scraping can provide valuable insights into their product offerings, pricing, and inventory levels. By scraping Tenaquip’s website, businesses can track changes in product availability, analyze pricing trends, and benchmark their own offerings against this major distributor. Grainger Grainger Grainger is a global leader in industrial supply distribution, serving businesses across various sectors. With a comprehensive product range that includes safety equipment, maintenance supplies, and industrial tools, Grainger is known for its robust logistics and customer support. Grainger data scraping can be instrumental in gathering real-time data on product details, pricing, and availability. By utilizing web scraping tools to monitor Grainger’s product listings and prices, businesses can gain insights into market trends, optimize their inventory management, and enhance their competitive strategies. Fastenal Fastenal Fastenal is a prominent industrial supply company headquartered in the United States, specializing in fasteners, tools, and safety products. With a vast network of locations and a significant online presence, Fastenal provides businesses with a wide array of industrial solutions. Fastenal data scraping enables businesses to extract detailed information about product offerings, prices, and stock levels. This data can be used to analyze market trends, adjust pricing strategies, and ensure competitive positioning in the industrial supply sector. Gas and Supply Gas-and-Supply Gas and Supply is a regional distributor focusing on industrial gases, welding supplies, and safety equipment. Serving industries that require specialized equipment and materials, Gas and Supply plays a crucial role in maintaining operational efficiency for its clients. Gas and Supply data scraping can help businesses keep track of product listings, pricing changes, and inventory updates. By scraping Gas and Supply’s website, companies can stay informed about the latest product offerings and pricing adjustments, ensuring they remain competitive in their respective markets. Motion Motion Motion is a major distributor of industrial products, including bearings, power transmission components, and maintenance supplies. Known for its extensive inventory and nationwide reach, Motion provides essential products to various industries. Motion data scraping offers businesses access to real-time data on product availability, pricing, and specifications. This information is crucial for optimizing supply chain management, adjusting pricing strategies, and enhancing overall business operations. Zoro Zoro Zoro is an online distributor of industrial supplies, offering a wide range of products from tools to safety equipment. With its user-friendly online platform, Zoro provides businesses with easy access to essential industrial products. Scraping Zoro prices and Zoro product listings scraping allow companies to gather comprehensive data on product offerings and pricing strategies. This data can be used to analyze market trends, optimize purchasing decisions, and ensure competitive pricing. What Can You Scrape from Tenaquip, Grainger, Fastenal, Gas and Supply, Motion, and Zoro? What-Can-You-Scrape-from-Tenaquip-Grainger-Fastenal-Gas-and-Supply-Motion-and-Zoro Web scraping offers valuable insights into product information, pricing, and distributor details from major industrial supply websites such as Tenaquip, Grainger, Fastenal, Gas and Supply, Motion, and Zoro. Here’s a breakdown of what you can extract from these sources: Product Information: Scraping these websites allows you to collect detailed data about the products offered. This includes descriptions, specifications, images (if required), and other relevant attributes. For example, you can extract data on various tools, safety equipment, and maintenance supplies from Grainger and Fastenal, or industrial gases and welding supplies from Gas and Supply. Pricing Data: One of the most critical aspects of web scraping is obtaining up-to-date pricing information. You can track changes in product prices over time, compare pricing across different suppliers, and monitor discounts or promotions. For instance, scraping Zoro prices can help businesses adjust their pricing strategies to remain competitive. Distributor SKU/Item Numbers: Extracting distributor SKU or item numbers is crucial for inventory management and synchronization. This information helps businesses match their internal catalog with the suppliers' listings, ensuring accuracy in orders and stock levels. You can scrape SKU data from Tenaquip data scraping or Fastenal data scraping to streamline your inventory processes. Availability and Stock Levels: Real-time data on product availability and stock levels helps businesses manage their supply chains more effectively. By scraping data from sites like Motion and Gas and Supply, companies can avoid stockouts and optimize their purchasing strategies. By leveraging industrial products web scraping services from these major suppliers, businesses can enhance their operational efficiency, make informed decisions, and stay ahead in the competitive industrial supply market. Why Web Scraping Is Essential for Industrial Supply Companies Why-Web-Scraping-Is-Essential-for-Industrial-Supply-Companies For businesses operating in the industrial supply sector, staying ahead of competitors requires constant monitoring of market trends, product offerings, and pricing strategies. Web scraping offers several advantages, including: Data Collection at Scale: Scraping enables you to collect large volumes of data quickly and efficiently, without the need for manual data entry. This data can then be analyzed to identify trends, optimize pricing, and refine business strategies. Real-Time Price Intelligence: Regular scraping of pricing data allows businesses to stay updated on competitor pricing. This real-time price intelligence can help you adjust your prices dynamically, ensuring you remain competitive while maximizing profits. Product Listings Analysis: Analyzing product listings across multiple competitors helps identify gaps in your own offerings, allowing you to expand your inventory strategically to meet market demand. Competitive Insights: Scraping data from industrial supply websites like Tenaquip, Grainger, Fastenal, Zoro, Gas and Supply, and Motion provides valuable insights into your competitors' strategies. This information can guide your own decision-making, from product development to pricing optimization. Pricing Strategy and Optimization: By leveraging the data collected through web scraping, businesses can implement a more effective pricing strategy. Price optimization is critical in the industrial sector, where margins can be tight, and staying competitive requires constant adjustments based on real-time data. Web Scraping for Tenaquip, Grainger, Fastenal, and Zoro: A Step-by-Step Process Web-Scraping-for-Tenaquip-Grainger-Fastenal-and-Zoro-A-Step-by-Step-Process-01 If you are ready to start scraping data from Tenaquip, Grainger, Fastenal, Zoro, Gas and Supply, and Motion, here’s a step-by-step process to guide you through: Identify Target Data: Determine which data points are most valuable for your business. This could include product descriptions, pricing information, and distributor SKU/item numbers. Choose Web Scraping Tools: Select a web scraping tool or service to automate data extraction. Tools like BeautifulSoup, Scrapy, or Selenium are popular choices, or you can opt for industrial products web scraping services provided by specialized companies. Write Scraping Code: Develop the code that will automate the extraction process. Ensure your scraper can handle dynamic content and pagination, common in large e-commerce websites. The final deliverable should include the written code for the scraping, ensuring you can rerun the process as needed. Extract Data: Run your scraper to extract the desired data. The output should be a structured dataset that can be easily analyzed, such as an Excel file. Analyze and Optimize: Once the data is collected, analyze it to identify trends, optimize pricing strategies, and improve your product offerings. This data-driven approach will help you stay competitive in the market. Leveraging Price Intelligence and AI for Competitive Advantage Leveraging-Price-Intelligence-and-AI-for-Competitive-Advantage-01 The data extracted through web scraping can be further enhanced by integrating price intelligence AI solutions. These AI-driven tools analyze pricing data to provide actionable insights, such as optimal price points, competitor pricing trends, and demand forecasting. By combining web scraping with AI-powered analysis, businesses can automate their pricing strategies, ensuring they remain competitive in a dynamic market. For example, Amazon adjusts its prices every 10 minutes based on competitor data. While your business may not need to operate at such a high frequency, implementing dynamic pricing strategies based on real-time data can significantly increase revenue. According to recent studies, businesses using dynamic pricing have seen up to a 23% increase in revenue. How Web Scraping Services APIs Can Help? If you lack the technical expertise to build your own scraper, web scraping services APIs can simplify the process. These APIs offer ready-to-use solutions for extracting data from various websites, including industrial suppliers like Tenaquip, Grainger, Fastenal, Zoro, Gas and Supply, and Motion. By using a web scraping API, you can focus on analyzing the data and applying it to your business strategy without worrying about the technical details of data extraction. Conclusion: The Power of Web Scraping in Industrial Markets Web scraping is a powerful tool that can transform how businesses in the industrial sector operate. By extracting product information, pricing data, and distributor details from websites like Tenaquip, Grainger, Fastenal, Zoro, Gas and Supply, and Motion, you can gain valuable insights that drive informed decision-making Whether you're looking to optimize your pricing strategy, expand your product offerings, or gain a competitive edge, web scraping offers a scalable and efficient solution. By combining web scraping with AI-driven price intelligence, your business can stay ahead in an ever-changing market. Start leveraging Tenaquip data scraping, Gas and Supply data scraping, Fastenal data scraping, and Motion data scraping today to unlock the full potential of real-time data and elevate your business. Actowiz Solutions can help you harness the power of web scraping and AI-driven insights. Contact us today to discover how our custom web scraping solutions can propel your business to new heights! You can also reach us for all your mobile app scraping , data collection, web scraping service , and instant data scraper service requirements. RECENT BLOGS View More How to Maximize Savings with Cross-Platform Grocery Promotion Scraping? Maximize savings by using cross-platform grocery promotion scraping to compare discounts, track deals, and find the best grocery offers. Web Scraping Instacart: Extract UPC, Brand, Ingredients & More Learn how to web scrape Instacart for detailed food product info including UPC, brand name, category, ingredients, and nutritional data.Enhance your data insights! RESEARCH AND REPORTS View More Review Analysis of McDonald’s in Orlando - A Comparative Study with Burger King Analyzing McDonald’s reviews in Orlando alongside Burger King to uncover customer preferences and satisfaction trends. Actowiz Solutions Growth Report Actowiz Solutions: Empowering Growth Through Innovative Solutions. Discover our latest achievements and milestones in our growth report. Case Studies View More Case Study - Scrape Blinkit Grocery Delivery Data Enhanced Market Insights - Actowiz Solutions Discover how Actowiz Solutions used web scraping to optimize grocery delivery operations for Blinkit. Explore the strategies, challenges, and results achieved in this detailed case study. Case Study - Revolutionizing Medical Price Comparison with Actowiz Solutions Revolutionizing healthcare with Actowiz Solutions' advanced medical data scraping and price comparison, ensuring transparency and cost savings for patients. Infographics View More The Evolution of Web Crawling Web scraping evolved from manual collection to automation, enabling efficient data extraction for strategic insights How to Leverage ChatGPT for Web Scraping? Leverage ChatGPT for web scraping by automating data extraction, generating scraping scripts, and analyzing web content for actionable insights.
__label__pos
0.550064
Commit 87ddb3e4 authored by Jerome Charaoui's avatar Jerome Charaoui move ensure_* package dependency parameters to backupninja::client parent e0e5f239 class backupninja::client ( $ensure_backupninja_version = 'installed', $ensure_rsync_version = 'installed', $ensure_rdiffbackup_version = 'installed', $ensure_debconfutils_version = 'installed', $ensure_hwinfo_version = 'installed', $ensure_duplicity_version = 'installed', $configdir = '/etc/backup.d', $keystore = "${::fileserver}/keys/backupkeys", $keystorefspath = false, ...... ......@@ -39,7 +39,6 @@ # testing debian repositories by the time of this writing. define backupninja::duplicity( $order = 90, $ensure = present, $ensure_duplicity_version = 'installed', # options to the config file $options = false, $nicelevel = false, ......@@ -98,7 +97,7 @@ define backupninja::duplicity( $order = 90, $installkey = true ) { # install client dependencies ensure_resource('package', 'duplicity', {'ensure' => $ensure_duplicity_version}) ensure_resource('package', 'duplicity', {'ensure' => $backupninja::client::ensure_duplicity_version}) case $desthost { false: { err("need to define a destination host for remote backups!") } } case $destdir { false: { err("need to define a destination directory for remote backups!") } } ...... ......@@ -17,14 +17,14 @@ # # define backupninja::maildir( $order = 99, $ensure = present, $ensure_rsync_version = 'installed', $order = 99, $ensure = present, $when = 'everyday at 21:00', $srcdir = false, $destdir = false, $desthost = false, $destuser = false, $destid_file = false, $remove = false, $multiconnection = yes, $keepdaily='4', $keepweekly='2', $keepmonthly='2') { # install client dependencies ensure_resource('package', 'rsync', {'ensure' => $ensure_rsync_version}) ensure_resource('package', 'rsync', {'ensure' => $backupninja::client::ensure_rsync_version}) case $srcdir { false: { err("need to define a source directory to backup!") } } case $destdir { false: { err("need to define a destination directory to backup!") } } ...... ......@@ -16,7 +16,7 @@ # directories. # define backupninja::rdiff( $order = 90, $ensure = present, $ensure_rdiffbackup_version = 'installed', $order = 90, $ensure = present, $user = false, $home = "/home/${user}-${name}", $host = false, $type = 'local', $exclude = [ "/home/*/.gnupg", "/home/*/.local/share/Trash", "/home/*/.Trash", ......@@ -30,7 +30,7 @@ define backupninja::rdiff( $extras = false, $nagios_description = 'backups') { # install client dependencies ensure_resource('package', 'rdiff-backup', {'ensure' => $ensure_rdiffbackup_version}) ensure_resource('package', 'rdiff-backup', {'ensure' => $backupninja::client::ensure_rdiffbackup_version}) $directory = "$home/rdiff-backup/" ...... ......@@ -2,7 +2,7 @@ # Based on backupninja::rdiff define backupninja::rsync( $order = 90, $ensure = present, $ensure_rsync_version = 'installed', $order = 90, $ensure = present, $user = false, $home = false, $host = false, $ssh_dir_manage = true, $ssh_dir = false, $authorized_keys_file = false, $installuser = true, $installkey = true, $key = false, $backuptag = false, ......@@ -31,7 +31,7 @@ define backupninja::rsync( $rm = false, $cp = false, $touch = false, $mv = false, $fsck = false) { # install client dependencies ensure_resource('package', 'rsync', {'ensure' => $ensure_rsync_version}) ensure_resource('package', 'rsync', {'ensure' => $backupninja::client::ensure_rsync_version}) # Right now just local origin with remote destination is supported. $from = 'local' ...... ......@@ -12,8 +12,6 @@ # define backupninja::sys($order = 30, $ensure = present, $ensure_debconfutils_version = 'installed', $ensure_hwinfo_version = 'installed', $parentdir = '/var/backups', $packages = true, $packagesfile = '/var/backups/dpkg-selections.txt', ......@@ -30,8 +28,8 @@ define backupninja::sys($order = 30, # install client dependencies case $operatingsystem { debian,ubuntu: { ensure_resource('package', 'debconf-utils', {'ensure' => $ensure_debconfutils_version}) ensure_resource('package', 'hwinfo', {'ensure' => $ensure_hwinfo_version}) ensure_resource('package', 'debconf-utils', {'ensure' => $backupninja::client::ensure_debconfutils_version}) ensure_resource('package', 'hwinfo', {'ensure' => $backupninja::client::ensure_hwinfo_version}) } default: {} } ...... Markdown is supported 0% or . You are about to add 0 people to the discussion. Proceed with caution. Finish editing this message first! Please register or to comment
__label__pos
0.999727
The Anatomy of Latency Latency is a measure of the time delay experienced in a system. In data communications, latency would be measured as the round-trip delay between sending a packet and receiving response from the destination. In the world of web applications latency is the response time of a web site. In web applications latency is dependent on both the round trip time on the communication link and also the processing time of the application, Hence we could say that latency = 2 * round trip time  + Processing time The round trip time is probably less susceptible to increasing traffic than the processing time taken for handling the increased loads. The processing time of the application is particularly pernicious in that it susceptible to changing traffic. This article tries to analyze why the latency or response times of web applications typically increase with increasing traffic. While the latency increases exponentially as the traffic increases the throughput increases to a point and then finally starts to drop substantially.  The ideal situation for all internet applications is to have the ability to scale horizontally allowing the application to handle increasing traffic by simply adding more commodity servers to the application while maintaining the response times to acceptable limits. However in the real world this never happens. The price of Latency Latency hurts business. Amazon found out that every 100 ms of latency cost them 1% of sales.  Similarly Google realized that a 0.5 second increase in search results dropped the search traffic by 20%. Latency really matters.    Reactions to bad response times in web sites range from minor annoyance to complete frustration and loss of users and business. The cause of processing latency One of the fundamental requirements of scalable systems is that they should be loosely coupled. The application needs to have a modular architecture with well defined interfaces with the other modules.  Ideally, applications which have been designed with fairly efficient processing times of the order of O(logn) or O(nlogn)  will be immune to changing loads but will be impacted by changes in number of data elements  So the algorithms adopted by the applications themselves do not contribute the increasing response times for increase traffic. So finally what really is the performance bottleneck for increasing latencies and decreasing throughput for increased loads? Contention- the culprit One of the culprits behind the deteriorating response is the thread locking and resource contention. Assuming that application has been designed with Reader-Writer locks or message queue based synchronization mechanism then the time spent in waiting for resources to become free, while traffic increases, will result in the degraded performance. Let us assume that the application is read-heavy, write-light and has implemented Reader-Writer synchronization mechanism. Further let us assume that a write-thread locks a resource for 250 ms.  At low loads we could have 4 such threads each locking the resource for 250 ms for a total span of 1s.  Hence in 1s there can be a maximum of 4 threads each of which has executed a write lock for 250 ms for a total of 1s. In this interval all reader threads will be forced to wait. When the traffic load is low the number of reader threads waiting for the lock to be released will be low and will not have much impact but as the traffic increases the number of threads that are waiting for the lock to be released will be increase. Since a write lock takes a finite amount of time to complete processing we cannot go over the 4 write threads in 1 second with the given CPU speed. However as the traffic further increases the number of waiting threads not only increases but also consume CPU and memory. Now this adversely impacts the writer threads which find that they have lesser CPU cycles and less memory and hence take longer times to complete. This downward cycle worsens and hence results in an increase in the response time and a worsening throughput in the application. The solution to this problem is not easy. We need to revisit the areas where the application blocks waiting for something. Locking besides causing threads to wait also adds the overhead of getting scheduled prior to being able to execute again. We need to minimize the time a thread holds a resource before allowing others threads access to it. Find me on Google+ One thought on “The Anatomy of Latency Leave a Reply Fill in your details below or click an icon to log in: WordPress.com Logo You are commenting using your WordPress.com account. Log Out /  Change ) Google photo You are commenting using your Google account. Log Out /  Change ) Twitter picture You are commenting using your Twitter account. Log Out /  Change ) Facebook photo You are commenting using your Facebook account. Log Out /  Change ) Connecting to %s
__label__pos
0.77517
Changeset 233 in svn Ignore: Timestamp: 2006-10-10T00:46:00Z (13 years ago) Author: Xuefer Message: processor: apply reference handling on opcode caching. reverted [196] [199] [220] and refix for #36 Location: trunk Files: 6 edited Legend: Unmodified Added Removed • trunk/processor/head.m4 r230 r233   6262    HashTable zvalptrs; 6363    zend_bool reference; /* enable if to deal with reference */  64    zend_bool have_references; 6465    const xc_entry_t *xce_src; 6566    const xc_entry_t *xce_dst;   261262} 262263/* }}} */ 263 static int xc_hash_static_member_check(xc_processor_t *processor, Bucket *b TSRMLS_DC) /* {{{ */ 264 { 265     const zend_class_entry *src = processor->active_class_entry_src; 266     if (src->parent) { 267         zval **parentzv; 268         if (zend_u_hash_quick_find(CE_STATIC_MEMBERS(src->parent), BUCKET_KEY_TYPE(b), ZSTR(BUCKET_KEY_S(b)), b->nKeyLength, b->h, (void **) &parentzv) == SUCCESS) { 269             zval **zv = (zval **) b->pData; 270             if (*parentzv == *zv) { 271                 return ZEND_HASH_APPLY_REMOVE; 272             } 273         } 274     } 275     return ZEND_HASH_APPLY_KEEP; 276 } 277 /* }}} */ 278 /* fix static members on restore */ 279 static void inherit_static_prop(zval **p) /* {{{ */ 280 { 281     /* already set */ 282 #if 0 283     (*p)->refcount++; 284     (*p)->is_ref = 1; 285 #endif 286 } 287 /* }}} */ 288 static void xc_fix_static_members(xc_processor_t *processor, zend_class_entry *dst TSRMLS_DC) /* {{{ */ 289 { 290     zend_hash_merge(&dst->default_static_members, &dst->parent->default_static_members, (void (*)(void *)) inherit_static_prop, NULL, sizeof(zval *), 0); 291 } 292 /* }}} */ 293 #endif 294 int xc_hash_reset_zval_refcount_applyer(void *pDest TSRMLS_DC) /* {{{ */ 295 { 296     zval **zv = (zval **) pDest; 297     ZVAL_REFCOUNT(*zv) = 1; 298     return ZEND_HASH_APPLY_KEEP; 299 } 300 /* }}} */ 301 static void xc_hash_reset_zval_refcount(HashTable *hash TSRMLS_DC) /* {{{ */ 302 { 303     zend_hash_apply(hash, xc_hash_reset_zval_refcount_applyer TSRMLS_CC); 304 } 305 /* }}} */  264#endif 306265/* {{{ call op_array ctor handler */ 307266extern zend_bool xc_have_op_array_ctor;   320279 321280    memset(&processor, 0, sizeof(processor)); 322     if (src->type == XC_TYPE_VAR) { 323         processor.reference = 1; 324     }  281    processor.reference = 1; 325282 326283    IFASSERT(`xc_stack_init(&processor.allocsizes);')   343300    } 344301    src->size = processor.size;  302    src->have_references = processor.have_references; 345303 346304    IFASSERT(`xc_stack_reverse(&processor.allocsizes);')   394352    memset(&processor, 0, sizeof(processor)); 395353    processor.readonly_protection = readonly_protection; 396   354    if (src->have_references) {  355        processor.reference = 1;  356    }  357  358    if (processor.reference) {  359        zend_hash_init(&processor.zvalptrs, 0, NULL, NULL, 0);  360    } 397361    xc_restore_xc_entry_t(&processor, dst, src TSRMLS_CC);  362    if (processor.reference) {  363        zend_hash_destroy(&processor.zvalptrs);  364    } 398365    return dst; 399366} 400367/* }}} */ 401 /* export: zval *xc_processor_restore_zval(zval *dst, const zval *src TSRMLS_DC); :export {{{ */ 402 zval *xc_processor_restore_zval(zval *dst, const zval *src TSRMLS_DC) {  368/* export: zval *xc_processor_restore_zval(zval *dst, const zval *src, zend_bool have_references TSRMLS_DC); :export {{{ */  369zval *xc_processor_restore_zval(zval *dst, const zval *src, zend_bool have_references TSRMLS_DC) { 403370    xc_processor_t processor; 404371 405372    memset(&processor, 0, sizeof(processor)); 406     processor.reference = 1; 407  408     zend_hash_init(&processor.zvalptrs, 0, NULL, NULL, 0); 409     dnl fprintf(stderr, "mark[%p] = %p\n", src, dst); 410     zend_hash_add(&processor.zvalptrs, (char *)src, sizeof(src), (void*)&dst, sizeof(dst), NULL);  373    processor.reference = have_references;  374  375    if (processor.reference) {  376        zend_hash_init(&processor.zvalptrs, 0, NULL, NULL, 0);  377        dnl fprintf(stderr, "mark[%p] = %p\n", src, dst);  378        zend_hash_add(&processor.zvalptrs, (char *)src, sizeof(src), (void*)&dst, sizeof(dst), NULL);  379    } 411380    xc_restore_zval(&processor, dst, src TSRMLS_CC); 412     zend_hash_destroy(&processor.zvalptrs);  381    if (processor.reference) {  382        zend_hash_destroy(&processor.zvalptrs);  383    } 413384 414385    return dst; • trunk/processor/main.m4 r198 r233   1111define(`m4_errprint', `ONCE(`errprint(`$1 1212')')')  13define(`ZEND_STRS', `($1), (sizeof($1))')  14define(`ZEND_STRL', `($1), (sizeof($1) - 1)') 1315dnl ============ 1416define(`INDENT', `xc_dprint_indent(indent);') • trunk/processor/processor.m4 r231 r233   6767dnl }}} 6868DEF_HASH_TABLE_FUNC(`HashTable_zval_ptr',           `zval_ptr') 69 DEF_HASH_TABLE_FUNC(`HashTable_zval_ptr_static_member_check',  `zval_ptr', , `xc_hash_static_member_check(processor, BUCKET TSRMLS_CC)') 7069#ifdef HAVE_XCACHE_CONSTANT 7170DEF_HASH_TABLE_FUNC(`HashTable_zend_constant',      `zend_constant')   168167                            dnl fprintf(stderr, "*dst is set to %p\n", dst[0]); 169168                        ')  169                        IFCALCSTORE(`processor->have_references = 1;') 170170                        IFSTORE(`assert(xc_is_shm(dst[0]));') 171171                        IFRESTORE(`assert(!xc_is_shm(dst[0]));')   300300 301301    STRUCT(HashTable, default_properties, HashTable_zval_ptr) 302     IFSTORE(`xc_hash_reset_zval_refcount(&dst->default_properties TSRMLS_CC);') 303302    IFCOPY(`dst->builtin_functions = src->builtin_functions;') 304303    DONE(builtin_functions)   306305    STRUCT(HashTable, properties_info, HashTable_zend_property_info) 307306#   ifdef ZEND_ENGINE_2_1 308     STRUCT(HashTable, default_static_members, IFCALCSTORE(HashTable_zval_ptr_static_member_check, HashTable_zval_ptr))  307    STRUCT(HashTable, default_static_members, HashTable_zval_ptr) 309308    IFCOPY(`dst->static_members = &dst->default_static_members;') 310     IFRESTORE(`if (dst->parent) xc_fix_static_members(processor, dst TSRMLS_CC);') 311309    DONE(static_members) 312310#   else 313     STRUCT_P(HashTable, static_members, IFCALCSTORE(HashTable_zval_ptr_static_member_check, HashTable_zval_ptr))  311    STRUCT_P(HashTable, static_members, HashTable_zval_ptr) 314312#   endif 315313    STRUCT(HashTable, constants_table, HashTable_zval_ptr) 316     IFSTORE(`xc_hash_reset_zval_refcount(&dst->constants_table TSRMLS_CC);') 317314 318315    dnl runtime binding: ADD_INTERFACE will deal with it   815812    DONE(data) 816813    dnl }}}  814    DISPATCH(zend_bool, have_references) 817815') 818816dnl }}} • trunk/xcache-test.ini r225 r233   66zend_extension_ts=./modules/xcache.so 77zend_extension=./modules/xcache.so 8 xcache.cacher = On  8xcache.cacher = Off 99xcache.test=1 1010xcache.size = 1M • trunk/xcache.c r230 r233   16731673        if (stored_xce) { 16741674            if (XG(request_time) <= stored_xce->ctime + stored_xce->ttl) { 1675                 xc_processor_restore_zval(return_value, stored_xce->data.var->value TSRMLS_CC);  1675                xc_processor_restore_zval(return_value, stored_xce->data.var->value, stored_xce->have_references TSRMLS_CC); 16761676                /* return */ 16771677                break;   18301830                    fprintf(stderr, "incdec: notlong\n"); 18311831#endif 1832                     xc_processor_restore_zval(&oldzval, stored_xce->data.var->value TSRMLS_CC);  1832                    xc_processor_restore_zval(&oldzval, stored_xce->data.var->value, stored_xce->have_references TSRMLS_CC); 18331833                    convert_to_long(&oldzval); 18341834                    value = Z_LVAL(oldzval); • trunk/xcache.h r212 r233   249249        xc_entry_data_var_t *var; 250250    } data;  251  252    zend_bool  have_references; 251253}; 252254/* }}} */ Note: See TracChangeset for help on using the changeset viewer.
__label__pos
0.988656
PHP 7.0.26 Released fann_create_train_from_callback (PECL fann >= 1.0.0) fann_create_train_from_callbackCreates the training data struct from a user supplied function Description resource fann_create_train_from_callback ( int $num_data , int $num_input , int $num_output , callable $user_function ) Creates the training data struct from a user supplied function. As the training data are numerable (data 1, data 2...), the user must write a function that receives the number of the training data set (input, output) and returns the set. Parameters num_data The number of training data num_input The number of inputs per training data num_output The number of ouputs per training data user_function The user supplied function with following parameters: • num - The number of the training data set • num_input - The number of inputs per training data • num_output - The number of ouputs per training data The function should return an associative array with keys input and output and two array values of input and output. Return Values Returns a train data resource on success, or FALSE on error. Examples Example #1 fann_create_train_from_callback() example <?php function create_train_callback($num_data$num_input$num_output) {     return array(          "input" => array_fill(0$num_input1),          "output" => array_fill(0$num_output1),     ); } $num_data 3; $num_input 2; $num_output 1; $train_data fann_create_train_from_callback($num_data$num_input$num_output"create_train_callback"); if ( $train_data) {      // Do something with $train_data } ?> See Also add a note add a note User Contributed Notes 1 note up 3 geekgirljoy at gmail dot com 1 year ago This code can be used to read training data from MySQL rather than a text file. <?php // MySQL for This Example: /* CREATE TABLE `TrainingSets` (   `ID` int(11) NOT NULL,   `Name` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,   `TrainingData` text COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ALTER TABLE `TrainingSets` ADD PRIMARY KEY (`ID`);   INSERT INTO `TrainingSets` (`ID`, `Name`, `TrainingData`) VALUES(1, 'XOR', '-1 -1\n-1\n-1 1\n1\n1 -1\n1\n1 1\n-1'); ALTER TABLE `TrainingSets` MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; */ // This function calls pulls the TrainingData from MySQL function get_training_data_from_db($id) {     $table_name = "TrainingSets";     $field = "TrainingData";     $connection=mysqli_connect("host","username","password","database"); // change to your DB credentials     $result=mysqli_query($connection,"SELECT $field FROM $table_name");     $data=mysqli_fetch_assoc($result);     mysqli_close($connection);     return $data[$field]; } // This function prepares the newline delimited data to be handed off to FANN /* Example of "newline delimited data" (like XOR in a Plain Text File) stored in MySQL: -1 -1 -1 -1 1 1 1 1 -1 1 -1 1 */ function prepare_data_from_db($training_data) {     $training_data = explode( "\n", $training_data ); // convert training data rows to array     $num_data = count($training_data);         // Sift the data and split inputs and outputs     for($i=0;$i<$num_data;$i++) {       if( $i % 2) { // $training_data[$i] is Output        $training_data['outputs'][] = explode( " ", $training_data[$i]);       }else{ // $training_data[$i] is Input        $training_data['inputs'][] = explode( " ", $training_data[$i]);       }     }     // remove the unsifted data     foreach ($training_data as $key => $value) {         if ( is_numeric($key)) {             unset( $training_data[$key]);         }     }     return $training_data; // returned the prepaired associative array } // This function hands the prepared data over to FANN function create_train_callback($num_data, $num_input, $num_output) {     global $training_data;     global $current_dataset;        $dataset = array("input" => $training_data['inputs'][$current_dataset],                     "output" => $training_data['outputs'][$current_dataset]);     $current_dataset++;     return $dataset; } // Initialize the program variables $record_id = 1; // the 'ID' for the training data in MySQL $current_dataset = 0; $num_input = 2; $num_output = 1; $num_layers = 3; $num_neurons = 3; $desired_error = 0.001; $max_epochs = 500000; $epochs_between_reports = 1000; $training_data = get_training_data_from_db($record_id); // Get the Training Data from MySQL $training_data = prepare_data_from_db($training_data); // Prepare the data $num_data = count($training_data["input"]); // How many sets are there? // Hand the data over to FANN $train_data = fann_create_train_from_callback($num_data, $num_input, $num_output, "create_train_callback"); // Test for $train_data if ($train_data) {         // Create $ann     $ann = fann_create_standard($num_layers, $num_input, $num_neurons, $num_output);     // Test for $ann     if ($ann) {         fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);         fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);         // Train XOR ANN with training data obtainied from MySQL         if (fann_train_on_data($ann, $train_data, $max_epochs, $epochs_between_reports, $desired_error)){            print( 'XOR trained.<br>' . PHP_EOL);            // Test $ann            $input = array(-1, 1);            $calc_out = fann_run($ann, $input);            printf("xor test (%f,%f) -> %f\n", $input[0], $input[1], $calc_out[0]);                       // destore $ann            fann_destroy($ann);         }     } } ?> To Top
__label__pos
0.999571
• R/O • SSH • HTTPS exewrap: Commit Commit MetaInfo Revision39 (tree) Time2017-10-14 18:42:08 Authorhirukawa_ryo Log Message * exewrap 1.2.0 リフレクションを使わずにExewrapClassLoaderをシステムクラスローダーに設定できるようにしました。 Exewrap関連クラスを保持するJARファイルを生成ファイルの末尾に連結するようにしました。 これにより生成ファイルはEXEとしてだけでなくJARとしても扱えるようになりました。 classpathに自身のEXEを指定することで既定のシステムクラスローダーでExewrap関連クラスをロードできるようになったことで -Djava.system.class.loader でExewrapClassLoaderを指定可能となりました。 トレース、JREMIN関連コードを削除しました。 Change Summary Incremental Difference --- exewrap/trunk/exewrap/src/minhook/AUTHORS.txt (revision 38) +++ exewrap/trunk/exewrap/src/minhook/AUTHORS.txt (nonexistent) @@ -1,8 +0,0 @@ 1-Tsuda Kageyu <[email protected]> 2- Creator, maintainer 3- 4-Michael Maltsev <[email protected]> 5- Added "Queue" functions. A lot of bug fixes. 6- 7-Andrey Unis <[email protected]> 8- Rewrote the hook engine in plain C. --- exewrap/trunk/exewrap/src/minhook/include/MinHook.h (revision 38) +++ exewrap/trunk/exewrap/src/minhook/include/MinHook.h (nonexistent) @@ -1,169 +0,0 @@ 1-/* 2- * MinHook - The Minimalistic API Hooking Library for x64/x86 3- * Copyright (C) 2009-2015 Tsuda Kageyu. 4- * All rights reserved. 5- * 6- * Redistribution and use in source and binary forms, with or without 7- * modification, are permitted provided that the following conditions 8- * are met: 9- * 10- * 1. Redistributions of source code must retain the above copyright 11- * notice, this list of conditions and the following disclaimer. 12- * 2. Redistributions in binary form must reproduce the above copyright 13- * notice, this list of conditions and the following disclaimer in the 14- * documentation and/or other materials provided with the distribution. 15- * 16- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18- * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19- * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20- * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27- */ 28- 29-#pragma once 30- 31-#if !(defined _M_IX86) && !(defined _M_X64) 32- #error MinHook supports only x86 and x64 systems. 33-#endif 34- 35-#include <windows.h> 36- 37-// MinHook Error Codes. 38-typedef enum MH_STATUS 39-{ 40- // Unknown error. Should not be returned. 41- MH_UNKNOWN = -1, 42- 43- // Successful. 44- MH_OK = 0, 45- 46- // MinHook is already initialized. 47- MH_ERROR_ALREADY_INITIALIZED, 48- 49- // MinHook is not initialized yet, or already uninitialized. 50- MH_ERROR_NOT_INITIALIZED, 51- 52- // The hook for the specified target function is already created. 53- MH_ERROR_ALREADY_CREATED, 54- 55- // The hook for the specified target function is not created yet. 56- MH_ERROR_NOT_CREATED, 57- 58- // The hook for the specified target function is already enabled. 59- MH_ERROR_ENABLED, 60- 61- // The hook for the specified target function is not enabled yet, or already 62- // disabled. 63- MH_ERROR_DISABLED, 64- 65- // The specified pointer is invalid. It points the address of non-allocated 66- // and/or non-executable region. 67- MH_ERROR_NOT_EXECUTABLE, 68- 69- // The specified target function cannot be hooked. 70- MH_ERROR_UNSUPPORTED_FUNCTION, 71- 72- // Failed to allocate memory. 73- MH_ERROR_MEMORY_ALLOC, 74- 75- // Failed to change the memory protection. 76- MH_ERROR_MEMORY_PROTECT, 77- 78- // The specified module is not loaded. 79- MH_ERROR_MODULE_NOT_FOUND, 80- 81- // The specified function is not found. 82- MH_ERROR_FUNCTION_NOT_FOUND 83-} 84-MH_STATUS; 85- 86-// Can be passed as a parameter to MH_EnableHook, MH_DisableHook, 87-// MH_QueueEnableHook or MH_QueueDisableHook. 88-#define MH_ALL_HOOKS NULL 89- 90-#ifdef __cplusplus 91-extern "C" { 92-#endif 93- 94- // Initialize the MinHook library. You must call this function EXACTLY ONCE 95- // at the beginning of your program. 96- MH_STATUS WINAPI MH_Initialize(VOID); 97- 98- // Uninitialize the MinHook library. You must call this function EXACTLY 99- // ONCE at the end of your program. 100- MH_STATUS WINAPI MH_Uninitialize(VOID); 101- 102- // Creates a Hook for the specified target function, in disabled state. 103- // Parameters: 104- // pTarget [in] A pointer to the target function, which will be 105- // overridden by the detour function. 106- // pDetour [in] A pointer to the detour function, which will override 107- // the target function. 108- // ppOriginal [out] A pointer to the trampoline function, which will be 109- // used to call the original target function. 110- // This parameter can be NULL. 111- MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal); 112- 113- // Creates a Hook for the specified API function, in disabled state. 114- // Parameters: 115- // pszModule [in] A pointer to the loaded module name which contains the 116- // target function. 117- // pszTarget [in] A pointer to the target function name, which will be 118- // overridden by the detour function. 119- // pDetour [in] A pointer to the detour function, which will override 120- // the target function. 121- // ppOriginal [out] A pointer to the trampoline function, which will be 122- // used to call the original target function. 123- // This parameter can be NULL. 124- MH_STATUS WINAPI MH_CreateHookApi( 125- LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal); 126- 127- // Removes an already created hook. 128- // Parameters: 129- // pTarget [in] A pointer to the target function. 130- MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget); 131- 132- // Enables an already created hook. 133- // Parameters: 134- // pTarget [in] A pointer to the target function. 135- // If this parameter is MH_ALL_HOOKS, all created hooks are 136- // enabled in one go. 137- MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget); 138- 139- // Disables an already created hook. 140- // Parameters: 141- // pTarget [in] A pointer to the target function. 142- // If this parameter is MH_ALL_HOOKS, all created hooks are 143- // disabled in one go. 144- MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget); 145- 146- // Queues to enable an already created hook. 147- // Parameters: 148- // pTarget [in] A pointer to the target function. 149- // If this parameter is MH_ALL_HOOKS, all created hooks are 150- // queued to be enabled. 151- MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget); 152- 153- // Queues to disable an already created hook. 154- // Parameters: 155- // pTarget [in] A pointer to the target function. 156- // If this parameter is MH_ALL_HOOKS, all created hooks are 157- // queued to be disabled. 158- MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget); 159- 160- // Applies all queued changes in one go. 161- MH_STATUS WINAPI MH_ApplyQueued(VOID); 162- 163- // Translates the MH_STATUS to its name as a string. 164- const char * WINAPI MH_StatusToString(MH_STATUS status); 165- 166-#ifdef __cplusplus 167-} 168-#endif 169- --- exewrap/trunk/exewrap/src/minhook/src/buffer.h (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/buffer.h (nonexistent) @@ -1,42 +0,0 @@ 1-/* 2- * MinHook - The Minimalistic API Hooking Library for x64/x86 3- * Copyright (C) 2009-2015 Tsuda Kageyu. 4- * All rights reserved. 5- * 6- * Redistribution and use in source and binary forms, with or without 7- * modification, are permitted provided that the following conditions 8- * are met: 9- * 10- * 1. Redistributions of source code must retain the above copyright 11- * notice, this list of conditions and the following disclaimer. 12- * 2. Redistributions in binary form must reproduce the above copyright 13- * notice, this list of conditions and the following disclaimer in the 14- * documentation and/or other materials provided with the distribution. 15- * 16- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18- * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19- * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20- * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27- */ 28- 29-#pragma once 30- 31-// Size of each memory slot. 32-#ifdef _M_X64 33- #define MEMORY_SLOT_SIZE 64 34-#else 35- #define MEMORY_SLOT_SIZE 32 36-#endif 37- 38-VOID InitializeBuffer(VOID); 39-VOID UninitializeBuffer(VOID); 40-LPVOID AllocateBuffer(LPVOID pOrigin); 41-VOID FreeBuffer(LPVOID pBuffer); 42-BOOL IsExecutableAddress(LPVOID pAddress); --- exewrap/trunk/exewrap/src/minhook/src/HDE/table64.h (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/HDE/table64.h (nonexistent) @@ -1,74 +0,0 @@ 1-/* 2- * Hacker Disassembler Engine 64 C 3- * Copyright (c) 2008-2009, Vyacheslav Patkov. 4- * All rights reserved. 5- * 6- */ 7- 8-#define C_NONE 0x00 9-#define C_MODRM 0x01 10-#define C_IMM8 0x02 11-#define C_IMM16 0x04 12-#define C_IMM_P66 0x10 13-#define C_REL8 0x20 14-#define C_REL32 0x40 15-#define C_GROUP 0x80 16-#define C_ERROR 0xff 17- 18-#define PRE_ANY 0x00 19-#define PRE_NONE 0x01 20-#define PRE_F2 0x02 21-#define PRE_F3 0x04 22-#define PRE_66 0x08 23-#define PRE_67 0x10 24-#define PRE_LOCK 0x20 25-#define PRE_SEG 0x40 26-#define PRE_ALL 0xff 27- 28-#define DELTA_OPCODES 0x4a 29-#define DELTA_FPU_REG 0xfd 30-#define DELTA_FPU_MODRM 0x104 31-#define DELTA_PREFIXES 0x13c 32-#define DELTA_OP_LOCK_OK 0x1ae 33-#define DELTA_OP2_LOCK_OK 0x1c6 34-#define DELTA_OP_ONLY_MEM 0x1d8 35-#define DELTA_OP2_ONLY_MEM 0x1e7 36- 37-unsigned char hde64_table[] = { 38- 0xa5,0xaa,0xa5,0xb8,0xa5,0xaa,0xa5,0xaa,0xa5,0xb8,0xa5,0xb8,0xa5,0xb8,0xa5, 39- 0xb8,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xac,0xc0,0xcc,0xc0,0xa1,0xa1, 40- 0xa1,0xa1,0xb1,0xa5,0xa5,0xa6,0xc0,0xc0,0xd7,0xda,0xe0,0xc0,0xe4,0xc0,0xea, 41- 0xea,0xe0,0xe0,0x98,0xc8,0xee,0xf1,0xa5,0xd3,0xa5,0xa5,0xa1,0xea,0x9e,0xc0, 42- 0xc0,0xc2,0xc0,0xe6,0x03,0x7f,0x11,0x7f,0x01,0x7f,0x01,0x3f,0x01,0x01,0xab, 43- 0x8b,0x90,0x64,0x5b,0x5b,0x5b,0x5b,0x5b,0x92,0x5b,0x5b,0x76,0x90,0x92,0x92, 44- 0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x6a,0x73,0x90, 45- 0x5b,0x52,0x52,0x52,0x52,0x5b,0x5b,0x5b,0x5b,0x77,0x7c,0x77,0x85,0x5b,0x5b, 46- 0x70,0x5b,0x7a,0xaf,0x76,0x76,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b, 47- 0x5b,0x5b,0x86,0x01,0x03,0x01,0x04,0x03,0xd5,0x03,0xd5,0x03,0xcc,0x01,0xbc, 48- 0x03,0xf0,0x03,0x03,0x04,0x00,0x50,0x50,0x50,0x50,0xff,0x20,0x20,0x20,0x20, 49- 0x01,0x01,0x01,0x01,0xc4,0x02,0x10,0xff,0xff,0xff,0x01,0x00,0x03,0x11,0xff, 50- 0x03,0xc4,0xc6,0xc8,0x02,0x10,0x00,0xff,0xcc,0x01,0x01,0x01,0x00,0x00,0x00, 51- 0x00,0x01,0x01,0x03,0x01,0xff,0xff,0xc0,0xc2,0x10,0x11,0x02,0x03,0x01,0x01, 52- 0x01,0xff,0xff,0xff,0x00,0x00,0x00,0xff,0x00,0x00,0xff,0xff,0xff,0xff,0x10, 53- 0x10,0x10,0x10,0x02,0x10,0x00,0x00,0xc6,0xc8,0x02,0x02,0x02,0x02,0x06,0x00, 54- 0x04,0x00,0x02,0xff,0x00,0xc0,0xc2,0x01,0x01,0x03,0x03,0x03,0xca,0x40,0x00, 55- 0x0a,0x00,0x04,0x00,0x00,0x00,0x00,0x7f,0x00,0x33,0x01,0x00,0x00,0x00,0x00, 56- 0x00,0x00,0xff,0xbf,0xff,0xff,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0xff,0x00, 57- 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff, 58- 0x00,0x00,0x00,0xbf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x00,0x00, 59- 0xff,0x40,0x40,0x40,0x40,0x41,0x49,0x40,0x40,0x40,0x40,0x4c,0x42,0x40,0x40, 60- 0x40,0x40,0x40,0x40,0x40,0x40,0x4f,0x44,0x53,0x40,0x40,0x40,0x44,0x57,0x43, 61- 0x5c,0x40,0x60,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, 62- 0x40,0x40,0x64,0x66,0x6e,0x6b,0x40,0x40,0x6a,0x46,0x40,0x40,0x44,0x46,0x40, 63- 0x40,0x5b,0x44,0x40,0x40,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x01,0x06, 64- 0x06,0x02,0x06,0x06,0x00,0x06,0x00,0x0a,0x0a,0x00,0x00,0x00,0x02,0x07,0x07, 65- 0x06,0x02,0x0d,0x06,0x06,0x06,0x0e,0x05,0x05,0x02,0x02,0x00,0x00,0x04,0x04, 66- 0x04,0x04,0x05,0x06,0x06,0x06,0x00,0x00,0x00,0x0e,0x00,0x00,0x08,0x00,0x10, 67- 0x00,0x18,0x00,0x20,0x00,0x28,0x00,0x30,0x00,0x80,0x01,0x82,0x01,0x86,0x00, 68- 0xf6,0xcf,0xfe,0x3f,0xab,0x00,0xb0,0x00,0xb1,0x00,0xb3,0x00,0xba,0xf8,0xbb, 69- 0x00,0xc0,0x00,0xc1,0x00,0xc7,0xbf,0x62,0xff,0x00,0x8d,0xff,0x00,0xc4,0xff, 70- 0x00,0xc5,0xff,0x00,0xff,0xff,0xeb,0x01,0xff,0x0e,0x12,0x08,0x00,0x13,0x09, 71- 0x00,0x16,0x08,0x00,0x17,0x09,0x00,0x2b,0x09,0x00,0xae,0xff,0x07,0xb2,0xff, 72- 0x00,0xb4,0xff,0x00,0xb5,0xff,0x00,0xc3,0x01,0x00,0xc7,0xff,0xbf,0xe7,0x08, 73- 0x00,0xf0,0x02,0x00 74-}; --- exewrap/trunk/exewrap/src/minhook/src/HDE/hde32.h (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/HDE/hde32.h (nonexistent) @@ -1,105 +0,0 @@ 1-/* 2- * Hacker Disassembler Engine 32 3- * Copyright (c) 2006-2009, Vyacheslav Patkov. 4- * All rights reserved. 5- * 6- * hde32.h: C/C++ header file 7- * 8- */ 9- 10-#ifndef _HDE32_H_ 11-#define _HDE32_H_ 12- 13-/* stdint.h - C99 standard header 14- * http://en.wikipedia.org/wiki/stdint.h 15- * 16- * if your compiler doesn't contain "stdint.h" header (for 17- * example, Microsoft Visual C++), you can download file: 18- * http://www.azillionmonkeys.com/qed/pstdint.h 19- * and change next line to: 20- * #include "pstdint.h" 21- */ 22-#include "pstdint.h" 23- 24-#define F_MODRM 0x00000001 25-#define F_SIB 0x00000002 26-#define F_IMM8 0x00000004 27-#define F_IMM16 0x00000008 28-#define F_IMM32 0x00000010 29-#define F_DISP8 0x00000020 30-#define F_DISP16 0x00000040 31-#define F_DISP32 0x00000080 32-#define F_RELATIVE 0x00000100 33-#define F_2IMM16 0x00000800 34-#define F_ERROR 0x00001000 35-#define F_ERROR_OPCODE 0x00002000 36-#define F_ERROR_LENGTH 0x00004000 37-#define F_ERROR_LOCK 0x00008000 38-#define F_ERROR_OPERAND 0x00010000 39-#define F_PREFIX_REPNZ 0x01000000 40-#define F_PREFIX_REPX 0x02000000 41-#define F_PREFIX_REP 0x03000000 42-#define F_PREFIX_66 0x04000000 43-#define F_PREFIX_67 0x08000000 44-#define F_PREFIX_LOCK 0x10000000 45-#define F_PREFIX_SEG 0x20000000 46-#define F_PREFIX_ANY 0x3f000000 47- 48-#define PREFIX_SEGMENT_CS 0x2e 49-#define PREFIX_SEGMENT_SS 0x36 50-#define PREFIX_SEGMENT_DS 0x3e 51-#define PREFIX_SEGMENT_ES 0x26 52-#define PREFIX_SEGMENT_FS 0x64 53-#define PREFIX_SEGMENT_GS 0x65 54-#define PREFIX_LOCK 0xf0 55-#define PREFIX_REPNZ 0xf2 56-#define PREFIX_REPX 0xf3 57-#define PREFIX_OPERAND_SIZE 0x66 58-#define PREFIX_ADDRESS_SIZE 0x67 59- 60-#pragma pack(push,1) 61- 62-typedef struct { 63- uint8_t len; 64- uint8_t p_rep; 65- uint8_t p_lock; 66- uint8_t p_seg; 67- uint8_t p_66; 68- uint8_t p_67; 69- uint8_t opcode; 70- uint8_t opcode2; 71- uint8_t modrm; 72- uint8_t modrm_mod; 73- uint8_t modrm_reg; 74- uint8_t modrm_rm; 75- uint8_t sib; 76- uint8_t sib_scale; 77- uint8_t sib_index; 78- uint8_t sib_base; 79- union { 80- uint8_t imm8; 81- uint16_t imm16; 82- uint32_t imm32; 83- } imm; 84- union { 85- uint8_t disp8; 86- uint16_t disp16; 87- uint32_t disp32; 88- } disp; 89- uint32_t flags; 90-} hde32s; 91- 92-#pragma pack(pop) 93- 94-#ifdef __cplusplus 95-extern "C" { 96-#endif 97- 98-/* __cdecl */ 99-unsigned int hde32_disasm(const void *code, hde32s *hs); 100- 101-#ifdef __cplusplus 102-} 103-#endif 104- 105-#endif /* _HDE32_H_ */ --- exewrap/trunk/exewrap/src/minhook/src/HDE/pstdint.h (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/HDE/pstdint.h (nonexistent) @@ -1,39 +0,0 @@ 1-/* 2- * MinHook - The Minimalistic API Hooking Library for x64/x86 3- * Copyright (C) 2009-2015 Tsuda Kageyu. All rights reserved. 4- * 5- * Redistribution and use in source and binary forms, with or without 6- * modification, are permitted provided that the following conditions 7- * are met: 8- * 9- * 1. Redistributions of source code must retain the above copyright 10- * notice, this list of conditions and the following disclaimer. 11- * 2. Redistributions in binary form must reproduce the above copyright 12- * notice, this list of conditions and the following disclaimer in the 13- * documentation and/or other materials provided with the distribution. 14- * 15- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR 16- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 17- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 18- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 19- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 20- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 21- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 22- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 24- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25- */ 26- 27-#pragma once 28- 29-#include <windows.h> 30- 31-// Integer types for HDE. 32-typedef INT8 int8_t; 33-typedef INT16 int16_t; 34-typedef INT32 int32_t; 35-typedef INT64 int64_t; 36-typedef UINT8 uint8_t; 37-typedef UINT16 uint16_t; 38-typedef UINT32 uint32_t; 39-typedef UINT64 uint64_t; --- exewrap/trunk/exewrap/src/minhook/src/HDE/hde64.c (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/HDE/hde64.c (nonexistent) @@ -1,333 +0,0 @@ 1-/* 2- * Hacker Disassembler Engine 64 C 3- * Copyright (c) 2008-2009, Vyacheslav Patkov. 4- * All rights reserved. 5- * 6- */ 7- 8-#include "hde64.h" 9-#include "table64.h" 10- 11-unsigned int hde64_disasm(const void *code, hde64s *hs) 12-{ 13- uint8_t x, c, *p = (uint8_t *)code, cflags, opcode, pref = 0; 14- uint8_t *ht = hde64_table, m_mod, m_reg, m_rm, disp_size = 0; 15- uint8_t op64 = 0; 16- 17- // Avoid using memset to reduce the footprint. 18-#ifndef _MSC_VER 19- memset((LPBYTE)hs, 0, sizeof(hde64s)); 20-#else 21- __stosb((LPBYTE)hs, 0, sizeof(hde64s)); 22-#endif 23- 24- for (x = 16; x; x--) 25- switch (c = *p++) { 26- case 0xf3: 27- hs->p_rep = c; 28- pref |= PRE_F3; 29- break; 30- case 0xf2: 31- hs->p_rep = c; 32- pref |= PRE_F2; 33- break; 34- case 0xf0: 35- hs->p_lock = c; 36- pref |= PRE_LOCK; 37- break; 38- case 0x26: case 0x2e: case 0x36: 39- case 0x3e: case 0x64: case 0x65: 40- hs->p_seg = c; 41- pref |= PRE_SEG; 42- break; 43- case 0x66: 44- hs->p_66 = c; 45- pref |= PRE_66; 46- break; 47- case 0x67: 48- hs->p_67 = c; 49- pref |= PRE_67; 50- break; 51- default: 52- goto pref_done; 53- } 54- pref_done: 55- 56- hs->flags = (uint32_t)pref << 23; 57- 58- if (!pref) 59- pref |= PRE_NONE; 60- 61- if ((c & 0xf0) == 0x40) { 62- hs->flags |= F_PREFIX_REX; 63- if ((hs->rex_w = (c & 0xf) >> 3) && (*p & 0xf8) == 0xb8) 64- op64++; 65- hs->rex_r = (c & 7) >> 2; 66- hs->rex_x = (c & 3) >> 1; 67- hs->rex_b = c & 1; 68- if (((c = *p++) & 0xf0) == 0x40) { 69- opcode = c; 70- goto error_opcode; 71- } 72- } 73- 74- if ((hs->opcode = c) == 0x0f) { 75- hs->opcode2 = c = *p++; 76- ht += DELTA_OPCODES; 77- } else if (c >= 0xa0 && c <= 0xa3) { 78- op64++; 79- if (pref & PRE_67) 80- pref |= PRE_66; 81- else 82- pref &= ~PRE_66; 83- } 84- 85- opcode = c; 86- cflags = ht[ht[opcode / 4] + (opcode % 4)]; 87- 88- if (cflags == C_ERROR) { 89- error_opcode: 90- hs->flags |= F_ERROR | F_ERROR_OPCODE; 91- cflags = 0; 92- if ((opcode & -3) == 0x24) 93- cflags++; 94- } 95- 96- x = 0; 97- if (cflags & C_GROUP) { 98- uint16_t t; 99- t = *(uint16_t *)(ht + (cflags & 0x7f)); 100- cflags = (uint8_t)t; 101- x = (uint8_t)(t >> 8); 102- } 103- 104- if (hs->opcode2) { 105- ht = hde64_table + DELTA_PREFIXES; 106- if (ht[ht[opcode / 4] + (opcode % 4)] & pref) 107- hs->flags |= F_ERROR | F_ERROR_OPCODE; 108- } 109- 110- if (cflags & C_MODRM) { 111- hs->flags |= F_MODRM; 112- hs->modrm = c = *p++; 113- hs->modrm_mod = m_mod = c >> 6; 114- hs->modrm_rm = m_rm = c & 7; 115- hs->modrm_reg = m_reg = (c & 0x3f) >> 3; 116- 117- if (x && ((x << m_reg) & 0x80)) 118- hs->flags |= F_ERROR | F_ERROR_OPCODE; 119- 120- if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) { 121- uint8_t t = opcode - 0xd9; 122- if (m_mod == 3) { 123- ht = hde64_table + DELTA_FPU_MODRM + t*8; 124- t = ht[m_reg] << m_rm; 125- } else { 126- ht = hde64_table + DELTA_FPU_REG; 127- t = ht[t] << m_reg; 128- } 129- if (t & 0x80) 130- hs->flags |= F_ERROR | F_ERROR_OPCODE; 131- } 132- 133- if (pref & PRE_LOCK) { 134- if (m_mod == 3) { 135- hs->flags |= F_ERROR | F_ERROR_LOCK; 136- } else { 137- uint8_t *table_end, op = opcode; 138- if (hs->opcode2) { 139- ht = hde64_table + DELTA_OP2_LOCK_OK; 140- table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK; 141- } else { 142- ht = hde64_table + DELTA_OP_LOCK_OK; 143- table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK; 144- op &= -2; 145- } 146- for (; ht != table_end; ht++) 147- if (*ht++ == op) { 148- if (!((*ht << m_reg) & 0x80)) 149- goto no_lock_error; 150- else 151- break; 152- } 153- hs->flags |= F_ERROR | F_ERROR_LOCK; 154- no_lock_error: 155- ; 156- } 157- } 158- 159- if (hs->opcode2) { 160- switch (opcode) { 161- case 0x20: case 0x22: 162- m_mod = 3; 163- if (m_reg > 4 || m_reg == 1) 164- goto error_operand; 165- else 166- goto no_error_operand; 167- case 0x21: case 0x23: 168- m_mod = 3; 169- if (m_reg == 4 || m_reg == 5) 170- goto error_operand; 171- else 172- goto no_error_operand; 173- } 174- } else { 175- switch (opcode) { 176- case 0x8c: 177- if (m_reg > 5) 178- goto error_operand; 179- else 180- goto no_error_operand; 181- case 0x8e: 182- if (m_reg == 1 || m_reg > 5) 183- goto error_operand; 184- else 185- goto no_error_operand; 186- } 187- } 188- 189- if (m_mod == 3) { 190- uint8_t *table_end; 191- if (hs->opcode2) { 192- ht = hde64_table + DELTA_OP2_ONLY_MEM; 193- table_end = ht + sizeof(hde64_table) - DELTA_OP2_ONLY_MEM; 194- } else { 195- ht = hde64_table + DELTA_OP_ONLY_MEM; 196- table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM; 197- } 198- for (; ht != table_end; ht += 2) 199- if (*ht++ == opcode) { 200- if (*ht++ & pref && !((*ht << m_reg) & 0x80)) 201- goto error_operand; 202- else 203- break; 204- } 205- goto no_error_operand; 206- } else if (hs->opcode2) { 207- switch (opcode) { 208- case 0x50: case 0xd7: case 0xf7: 209- if (pref & (PRE_NONE | PRE_66)) 210- goto error_operand; 211- break; 212- case 0xd6: 213- if (pref & (PRE_F2 | PRE_F3)) 214- goto error_operand; 215- break; 216- case 0xc5: 217- goto error_operand; 218- } 219- goto no_error_operand; 220- } else 221- goto no_error_operand; 222- 223- error_operand: 224- hs->flags |= F_ERROR | F_ERROR_OPERAND; 225- no_error_operand: 226- 227- c = *p++; 228- if (m_reg <= 1) { 229- if (opcode == 0xf6) 230- cflags |= C_IMM8; 231- else if (opcode == 0xf7) 232- cflags |= C_IMM_P66; 233- } 234- 235- switch (m_mod) { 236- case 0: 237- if (pref & PRE_67) { 238- if (m_rm == 6) 239- disp_size = 2; 240- } else 241- if (m_rm == 5) 242- disp_size = 4; 243- break; 244- case 1: 245- disp_size = 1; 246- break; 247- case 2: 248- disp_size = 2; 249- if (!(pref & PRE_67)) 250- disp_size <<= 1; 251- } 252- 253- if (m_mod != 3 && m_rm == 4) { 254- hs->flags |= F_SIB; 255- p++; 256- hs->sib = c; 257- hs->sib_scale = c >> 6; 258- hs->sib_index = (c & 0x3f) >> 3; 259- if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1)) 260- disp_size = 4; 261- } 262- 263- p--; 264- switch (disp_size) { 265- case 1: 266- hs->flags |= F_DISP8; 267- hs->disp.disp8 = *p; 268- break; 269- case 2: 270- hs->flags |= F_DISP16; 271- hs->disp.disp16 = *(uint16_t *)p; 272- break; 273- case 4: 274- hs->flags |= F_DISP32; 275- hs->disp.disp32 = *(uint32_t *)p; 276- } 277- p += disp_size; 278- } else if (pref & PRE_LOCK) 279- hs->flags |= F_ERROR | F_ERROR_LOCK; 280- 281- if (cflags & C_IMM_P66) { 282- if (cflags & C_REL32) { 283- if (pref & PRE_66) { 284- hs->flags |= F_IMM16 | F_RELATIVE; 285- hs->imm.imm16 = *(uint16_t *)p; 286- p += 2; 287- goto disasm_done; 288- } 289- goto rel32_ok; 290- } 291- if (op64) { 292- hs->flags |= F_IMM64; 293- hs->imm.imm64 = *(uint64_t *)p; 294- p += 8; 295- } else if (!(pref & PRE_66)) { 296- hs->flags |= F_IMM32; 297- hs->imm.imm32 = *(uint32_t *)p; 298- p += 4; 299- } else 300- goto imm16_ok; 301- } 302- 303- 304- if (cflags & C_IMM16) { 305- imm16_ok: 306- hs->flags |= F_IMM16; 307- hs->imm.imm16 = *(uint16_t *)p; 308- p += 2; 309- } 310- if (cflags & C_IMM8) { 311- hs->flags |= F_IMM8; 312- hs->imm.imm8 = *p++; 313- } 314- 315- if (cflags & C_REL32) { 316- rel32_ok: 317- hs->flags |= F_IMM32 | F_RELATIVE; 318- hs->imm.imm32 = *(uint32_t *)p; 319- p += 4; 320- } else if (cflags & C_REL8) { 321- hs->flags |= F_IMM8 | F_RELATIVE; 322- hs->imm.imm8 = *p++; 323- } 324- 325- disasm_done: 326- 327- if ((hs->len = (uint8_t)(p-(uint8_t *)code)) > 15) { 328- hs->flags |= F_ERROR | F_ERROR_LENGTH; 329- hs->len = 15; 330- } 331- 332- return (unsigned int)hs->len; 333-} --- exewrap/trunk/exewrap/src/minhook/src/HDE/hde64.h (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/HDE/hde64.h (nonexistent) @@ -1,112 +0,0 @@ 1-/* 2- * Hacker Disassembler Engine 64 3- * Copyright (c) 2008-2009, Vyacheslav Patkov. 4- * All rights reserved. 5- * 6- * hde64.h: C/C++ header file 7- * 8- */ 9- 10-#ifndef _HDE64_H_ 11-#define _HDE64_H_ 12- 13-/* stdint.h - C99 standard header 14- * http://en.wikipedia.org/wiki/stdint.h 15- * 16- * if your compiler doesn't contain "stdint.h" header (for 17- * example, Microsoft Visual C++), you can download file: 18- * http://www.azillionmonkeys.com/qed/pstdint.h 19- * and change next line to: 20- * #include "pstdint.h" 21- */ 22-#include "pstdint.h" 23- 24-#define F_MODRM 0x00000001 25-#define F_SIB 0x00000002 26-#define F_IMM8 0x00000004 27-#define F_IMM16 0x00000008 28-#define F_IMM32 0x00000010 29-#define F_IMM64 0x00000020 30-#define F_DISP8 0x00000040 31-#define F_DISP16 0x00000080 32-#define F_DISP32 0x00000100 33-#define F_RELATIVE 0x00000200 34-#define F_ERROR 0x00001000 35-#define F_ERROR_OPCODE 0x00002000 36-#define F_ERROR_LENGTH 0x00004000 37-#define F_ERROR_LOCK 0x00008000 38-#define F_ERROR_OPERAND 0x00010000 39-#define F_PREFIX_REPNZ 0x01000000 40-#define F_PREFIX_REPX 0x02000000 41-#define F_PREFIX_REP 0x03000000 42-#define F_PREFIX_66 0x04000000 43-#define F_PREFIX_67 0x08000000 44-#define F_PREFIX_LOCK 0x10000000 45-#define F_PREFIX_SEG 0x20000000 46-#define F_PREFIX_REX 0x40000000 47-#define F_PREFIX_ANY 0x7f000000 48- 49-#define PREFIX_SEGMENT_CS 0x2e 50-#define PREFIX_SEGMENT_SS 0x36 51-#define PREFIX_SEGMENT_DS 0x3e 52-#define PREFIX_SEGMENT_ES 0x26 53-#define PREFIX_SEGMENT_FS 0x64 54-#define PREFIX_SEGMENT_GS 0x65 55-#define PREFIX_LOCK 0xf0 56-#define PREFIX_REPNZ 0xf2 57-#define PREFIX_REPX 0xf3 58-#define PREFIX_OPERAND_SIZE 0x66 59-#define PREFIX_ADDRESS_SIZE 0x67 60- 61-#pragma pack(push,1) 62- 63-typedef struct { 64- uint8_t len; 65- uint8_t p_rep; 66- uint8_t p_lock; 67- uint8_t p_seg; 68- uint8_t p_66; 69- uint8_t p_67; 70- uint8_t rex; 71- uint8_t rex_w; 72- uint8_t rex_r; 73- uint8_t rex_x; 74- uint8_t rex_b; 75- uint8_t opcode; 76- uint8_t opcode2; 77- uint8_t modrm; 78- uint8_t modrm_mod; 79- uint8_t modrm_reg; 80- uint8_t modrm_rm; 81- uint8_t sib; 82- uint8_t sib_scale; 83- uint8_t sib_index; 84- uint8_t sib_base; 85- union { 86- uint8_t imm8; 87- uint16_t imm16; 88- uint32_t imm32; 89- uint64_t imm64; 90- } imm; 91- union { 92- uint8_t disp8; 93- uint16_t disp16; 94- uint32_t disp32; 95- } disp; 96- uint32_t flags; 97-} hde64s; 98- 99-#pragma pack(pop) 100- 101-#ifdef __cplusplus 102-extern "C" { 103-#endif 104- 105-/* __cdecl */ 106-unsigned int hde64_disasm(const void *code, hde64s *hs); 107- 108-#ifdef __cplusplus 109-} 110-#endif 111- 112-#endif /* _HDE64_H_ */ --- exewrap/trunk/exewrap/src/minhook/src/HDE/table32.h (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/HDE/table32.h (nonexistent) @@ -1,73 +0,0 @@ 1-/* 2- * Hacker Disassembler Engine 32 C 3- * Copyright (c) 2008-2009, Vyacheslav Patkov. 4- * All rights reserved. 5- * 6- */ 7- 8-#define C_NONE 0x00 9-#define C_MODRM 0x01 10-#define C_IMM8 0x02 11-#define C_IMM16 0x04 12-#define C_IMM_P66 0x10 13-#define C_REL8 0x20 14-#define C_REL32 0x40 15-#define C_GROUP 0x80 16-#define C_ERROR 0xff 17- 18-#define PRE_ANY 0x00 19-#define PRE_NONE 0x01 20-#define PRE_F2 0x02 21-#define PRE_F3 0x04 22-#define PRE_66 0x08 23-#define PRE_67 0x10 24-#define PRE_LOCK 0x20 25-#define PRE_SEG 0x40 26-#define PRE_ALL 0xff 27- 28-#define DELTA_OPCODES 0x4a 29-#define DELTA_FPU_REG 0xf1 30-#define DELTA_FPU_MODRM 0xf8 31-#define DELTA_PREFIXES 0x130 32-#define DELTA_OP_LOCK_OK 0x1a1 33-#define DELTA_OP2_LOCK_OK 0x1b9 34-#define DELTA_OP_ONLY_MEM 0x1cb 35-#define DELTA_OP2_ONLY_MEM 0x1da 36- 37-unsigned char hde32_table[] = { 38- 0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3, 39- 0xa8,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xac,0xaa,0xb2,0xaa,0x9f,0x9f, 40- 0x9f,0x9f,0xb5,0xa3,0xa3,0xa4,0xaa,0xaa,0xba,0xaa,0x96,0xaa,0xa8,0xaa,0xc3, 41- 0xc3,0x96,0x96,0xb7,0xae,0xd6,0xbd,0xa3,0xc5,0xa3,0xa3,0x9f,0xc3,0x9c,0xaa, 42- 0xaa,0xac,0xaa,0xbf,0x03,0x7f,0x11,0x7f,0x01,0x7f,0x01,0x3f,0x01,0x01,0x90, 43- 0x82,0x7d,0x97,0x59,0x59,0x59,0x59,0x59,0x7f,0x59,0x59,0x60,0x7d,0x7f,0x7f, 44- 0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x9a,0x88,0x7d, 45- 0x59,0x50,0x50,0x50,0x50,0x59,0x59,0x59,0x59,0x61,0x94,0x61,0x9e,0x59,0x59, 46- 0x85,0x59,0x92,0xa3,0x60,0x60,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59, 47- 0x59,0x59,0x9f,0x01,0x03,0x01,0x04,0x03,0xd5,0x03,0xcc,0x01,0xbc,0x03,0xf0, 48- 0x10,0x10,0x10,0x10,0x50,0x50,0x50,0x50,0x14,0x20,0x20,0x20,0x20,0x01,0x01, 49- 0x01,0x01,0xc4,0x02,0x10,0x00,0x00,0x00,0x00,0x01,0x01,0xc0,0xc2,0x10,0x11, 50- 0x02,0x03,0x11,0x03,0x03,0x04,0x00,0x00,0x14,0x00,0x02,0x00,0x00,0xc6,0xc8, 51- 0x02,0x02,0x02,0x02,0x00,0x00,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0xff,0xca, 52- 0x01,0x01,0x01,0x00,0x06,0x00,0x04,0x00,0xc0,0xc2,0x01,0x01,0x03,0x01,0xff, 53- 0xff,0x01,0x00,0x03,0xc4,0xc4,0xc6,0x03,0x01,0x01,0x01,0xff,0x03,0x03,0x03, 54- 0xc8,0x40,0x00,0x0a,0x00,0x04,0x00,0x00,0x00,0x00,0x7f,0x00,0x33,0x01,0x00, 55- 0x00,0x00,0x00,0x00,0x00,0xff,0xbf,0xff,0xff,0x00,0x00,0x00,0x00,0x07,0x00, 56- 0x00,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 57- 0x00,0xff,0xff,0x00,0x00,0x00,0xbf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 58- 0x7f,0x00,0x00,0xff,0x4a,0x4a,0x4a,0x4a,0x4b,0x52,0x4a,0x4a,0x4a,0x4a,0x4f, 59- 0x4c,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x55,0x45,0x40,0x4a,0x4a,0x4a, 60- 0x45,0x59,0x4d,0x46,0x4a,0x5d,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a, 61- 0x4a,0x4a,0x4a,0x4a,0x4a,0x61,0x63,0x67,0x4e,0x4a,0x4a,0x6b,0x6d,0x4a,0x4a, 62- 0x45,0x6d,0x4a,0x4a,0x44,0x45,0x4a,0x4a,0x00,0x00,0x00,0x02,0x0d,0x06,0x06, 63- 0x06,0x06,0x0e,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x00,0x06,0x06,0x02,0x06, 64- 0x00,0x0a,0x0a,0x07,0x07,0x06,0x02,0x05,0x05,0x02,0x02,0x00,0x00,0x04,0x04, 65- 0x04,0x04,0x00,0x00,0x00,0x0e,0x05,0x06,0x06,0x06,0x01,0x06,0x00,0x00,0x08, 66- 0x00,0x10,0x00,0x18,0x00,0x20,0x00,0x28,0x00,0x30,0x00,0x80,0x01,0x82,0x01, 67- 0x86,0x00,0xf6,0xcf,0xfe,0x3f,0xab,0x00,0xb0,0x00,0xb1,0x00,0xb3,0x00,0xba, 68- 0xf8,0xbb,0x00,0xc0,0x00,0xc1,0x00,0xc7,0xbf,0x62,0xff,0x00,0x8d,0xff,0x00, 69- 0xc4,0xff,0x00,0xc5,0xff,0x00,0xff,0xff,0xeb,0x01,0xff,0x0e,0x12,0x08,0x00, 70- 0x13,0x09,0x00,0x16,0x08,0x00,0x17,0x09,0x00,0x2b,0x09,0x00,0xae,0xff,0x07, 71- 0xb2,0xff,0x00,0xb4,0xff,0x00,0xb5,0xff,0x00,0xc3,0x01,0x00,0xc7,0xff,0xbf, 72- 0xe7,0x08,0x00,0xf0,0x02,0x00 73-}; --- exewrap/trunk/exewrap/src/minhook/src/HDE/hde32.c (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/HDE/hde32.c (nonexistent) @@ -1,322 +0,0 @@ 1-/* 2- * Hacker Disassembler Engine 32 C 3- * Copyright (c) 2008-2009, Vyacheslav Patkov. 4- * All rights reserved. 5- * 6- */ 7- 8-#include "hde32.h" 9-#include "table32.h" 10- 11-unsigned int hde32_disasm(const void *code, hde32s *hs) 12-{ 13- uint8_t x, c, *p = (uint8_t *)code, cflags, opcode, pref = 0; 14- uint8_t *ht = hde32_table, m_mod, m_reg, m_rm, disp_size = 0; 15- 16- // Avoid using memset to reduce the footprint. 17-#ifndef _MSC_VER 18- memset((LPBYTE)hs, 0, sizeof(hde32s)); 19-#else 20- __stosb((LPBYTE)hs, 0, sizeof(hde32s)); 21-#endif 22- 23- for (x = 16; x; x--) 24- switch (c = *p++) { 25- case 0xf3: 26- hs->p_rep = c; 27- pref |= PRE_F3; 28- break; 29- case 0xf2: 30- hs->p_rep = c; 31- pref |= PRE_F2; 32- break; 33- case 0xf0: 34- hs->p_lock = c; 35- pref |= PRE_LOCK; 36- break; 37- case 0x26: case 0x2e: case 0x36: 38- case 0x3e: case 0x64: case 0x65: 39- hs->p_seg = c; 40- pref |= PRE_SEG; 41- break; 42- case 0x66: 43- hs->p_66 = c; 44- pref |= PRE_66; 45- break; 46- case 0x67: 47- hs->p_67 = c; 48- pref |= PRE_67; 49- break; 50- default: 51- goto pref_done; 52- } 53- pref_done: 54- 55- hs->flags = (uint32_t)pref << 23; 56- 57- if (!pref) 58- pref |= PRE_NONE; 59- 60- if ((hs->opcode = c) == 0x0f) { 61- hs->opcode2 = c = *p++; 62- ht += DELTA_OPCODES; 63- } else if (c >= 0xa0 && c <= 0xa3) { 64- if (pref & PRE_67) 65- pref |= PRE_66; 66- else 67- pref &= ~PRE_66; 68- } 69- 70- opcode = c; 71- cflags = ht[ht[opcode / 4] + (opcode % 4)]; 72- 73- if (cflags == C_ERROR) { 74- hs->flags |= F_ERROR | F_ERROR_OPCODE; 75- cflags = 0; 76- if ((opcode & -3) == 0x24) 77- cflags++; 78- } 79- 80- x = 0; 81- if (cflags & C_GROUP) { 82- uint16_t t; 83- t = *(uint16_t *)(ht + (cflags & 0x7f)); 84- cflags = (uint8_t)t; 85- x = (uint8_t)(t >> 8); 86- } 87- 88- if (hs->opcode2) { 89- ht = hde32_table + DELTA_PREFIXES; 90- if (ht[ht[opcode / 4] + (opcode % 4)] & pref) 91- hs->flags |= F_ERROR | F_ERROR_OPCODE; 92- } 93- 94- if (cflags & C_MODRM) { 95- hs->flags |= F_MODRM; 96- hs->modrm = c = *p++; 97- hs->modrm_mod = m_mod = c >> 6; 98- hs->modrm_rm = m_rm = c & 7; 99- hs->modrm_reg = m_reg = (c & 0x3f) >> 3; 100- 101- if (x && ((x << m_reg) & 0x80)) 102- hs->flags |= F_ERROR | F_ERROR_OPCODE; 103- 104- if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) { 105- uint8_t t = opcode - 0xd9; 106- if (m_mod == 3) { 107- ht = hde32_table + DELTA_FPU_MODRM + t*8; 108- t = ht[m_reg] << m_rm; 109- } else { 110- ht = hde32_table + DELTA_FPU_REG; 111- t = ht[t] << m_reg; 112- } 113- if (t & 0x80) 114- hs->flags |= F_ERROR | F_ERROR_OPCODE; 115- } 116- 117- if (pref & PRE_LOCK) { 118- if (m_mod == 3) { 119- hs->flags |= F_ERROR | F_ERROR_LOCK; 120- } else { 121- uint8_t *table_end, op = opcode; 122- if (hs->opcode2) { 123- ht = hde32_table + DELTA_OP2_LOCK_OK; 124- table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK; 125- } else { 126- ht = hde32_table + DELTA_OP_LOCK_OK; 127- table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK; 128- op &= -2; 129- } 130- for (; ht != table_end; ht++) 131- if (*ht++ == op) { 132- if (!((*ht << m_reg) & 0x80)) 133- goto no_lock_error; 134- else 135- break; 136- } 137- hs->flags |= F_ERROR | F_ERROR_LOCK; 138- no_lock_error: 139- ; 140- } 141- } 142- 143- if (hs->opcode2) { 144- switch (opcode) { 145- case 0x20: case 0x22: 146- m_mod = 3; 147- if (m_reg > 4 || m_reg == 1) 148- goto error_operand; 149- else 150- goto no_error_operand; 151- case 0x21: case 0x23: 152- m_mod = 3; 153- if (m_reg == 4 || m_reg == 5) 154- goto error_operand; 155- else 156- goto no_error_operand; 157- } 158- } else { 159- switch (opcode) { 160- case 0x8c: 161- if (m_reg > 5) 162- goto error_operand; 163- else 164- goto no_error_operand; 165- case 0x8e: 166- if (m_reg == 1 || m_reg > 5) 167- goto error_operand; 168- else 169- goto no_error_operand; 170- } 171- } 172- 173- if (m_mod == 3) { 174- uint8_t *table_end; 175- if (hs->opcode2) { 176- ht = hde32_table + DELTA_OP2_ONLY_MEM; 177- table_end = ht + sizeof(hde32_table) - DELTA_OP2_ONLY_MEM; 178- } else { 179- ht = hde32_table + DELTA_OP_ONLY_MEM; 180- table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM; 181- } 182- for (; ht != table_end; ht += 2) 183- if (*ht++ == opcode) { 184- if (*ht++ & pref && !((*ht << m_reg) & 0x80)) 185- goto error_operand; 186- else 187- break; 188- } 189- goto no_error_operand; 190- } else if (hs->opcode2) { 191- switch (opcode) { 192- case 0x50: case 0xd7: case 0xf7: 193- if (pref & (PRE_NONE | PRE_66)) 194- goto error_operand; 195- break; 196- case 0xd6: 197- if (pref & (PRE_F2 | PRE_F3)) 198- goto error_operand; 199- break; 200- case 0xc5: 201- goto error_operand; 202- } 203- goto no_error_operand; 204- } else 205- goto no_error_operand; 206- 207- error_operand: 208- hs->flags |= F_ERROR | F_ERROR_OPERAND; 209- no_error_operand: 210- 211- c = *p++; 212- if (m_reg <= 1) { 213- if (opcode == 0xf6) 214- cflags |= C_IMM8; 215- else if (opcode == 0xf7) 216- cflags |= C_IMM_P66; 217- } 218- 219- switch (m_mod) { 220- case 0: 221- if (pref & PRE_67) { 222- if (m_rm == 6) 223- disp_size = 2; 224- } else 225- if (m_rm == 5) 226- disp_size = 4; 227- break; 228- case 1: 229- disp_size = 1; 230- break; 231- case 2: 232- disp_size = 2; 233- if (!(pref & PRE_67)) 234- disp_size <<= 1; 235- } 236- 237- if (m_mod != 3 && m_rm == 4 && !(pref & PRE_67)) { 238- hs->flags |= F_SIB; 239- p++; 240- hs->sib = c; 241- hs->sib_scale = c >> 6; 242- hs->sib_index = (c & 0x3f) >> 3; 243- if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1)) 244- disp_size = 4; 245- } 246- 247- p--; 248- switch (disp_size) { 249- case 1: 250- hs->flags |= F_DISP8; 251- hs->disp.disp8 = *p; 252- break; 253- case 2: 254- hs->flags |= F_DISP16; 255- hs->disp.disp16 = *(uint16_t *)p; 256- break; 257- case 4: 258- hs->flags |= F_DISP32; 259- hs->disp.disp32 = *(uint32_t *)p; 260- } 261- p += disp_size; 262- } else if (pref & PRE_LOCK) 263- hs->flags |= F_ERROR | F_ERROR_LOCK; 264- 265- if (cflags & C_IMM_P66) { 266- if (cflags & C_REL32) { 267- if (pref & PRE_66) { 268- hs->flags |= F_IMM16 | F_RELATIVE; 269- hs->imm.imm16 = *(uint16_t *)p; 270- p += 2; 271- goto disasm_done; 272- } 273- goto rel32_ok; 274- } 275- if (pref & PRE_66) { 276- hs->flags |= F_IMM16; 277- hs->imm.imm16 = *(uint16_t *)p; 278- p += 2; 279- } else { 280- hs->flags |= F_IMM32; 281- hs->imm.imm32 = *(uint32_t *)p; 282- p += 4; 283- } 284- } 285- 286- if (cflags & C_IMM16) { 287- if (hs->flags & F_IMM32) { 288- hs->flags |= F_IMM16; 289- hs->disp.disp16 = *(uint16_t *)p; 290- } else if (hs->flags & F_IMM16) { 291- hs->flags |= F_2IMM16; 292- hs->disp.disp16 = *(uint16_t *)p; 293- } else { 294- hs->flags |= F_IMM16; 295- hs->imm.imm16 = *(uint16_t *)p; 296- } 297- p += 2; 298- } 299- if (cflags & C_IMM8) { 300- hs->flags |= F_IMM8; 301- hs->imm.imm8 = *p++; 302- } 303- 304- if (cflags & C_REL32) { 305- rel32_ok: 306- hs->flags |= F_IMM32 | F_RELATIVE; 307- hs->imm.imm32 = *(uint32_t *)p; 308- p += 4; 309- } else if (cflags & C_REL8) { 310- hs->flags |= F_IMM8 | F_RELATIVE; 311- hs->imm.imm8 = *p++; 312- } 313- 314- disasm_done: 315- 316- if ((hs->len = (uint8_t)(p-(uint8_t *)code)) > 15) { 317- hs->flags |= F_ERROR | F_ERROR_LENGTH; 318- hs->len = 15; 319- } 320- 321- return (unsigned int)hs->len; 322-} --- exewrap/trunk/exewrap/src/minhook/src/trampoline.h (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/trampoline.h (nonexistent) @@ -1,105 +0,0 @@ 1-/* 2- * MinHook - The Minimalistic API Hooking Library for x64/x86 3- * Copyright (C) 2009-2015 Tsuda Kageyu. 4- * All rights reserved. 5- * 6- * Redistribution and use in source and binary forms, with or without 7- * modification, are permitted provided that the following conditions 8- * are met: 9- * 10- * 1. Redistributions of source code must retain the above copyright 11- * notice, this list of conditions and the following disclaimer. 12- * 2. Redistributions in binary form must reproduce the above copyright 13- * notice, this list of conditions and the following disclaimer in the 14- * documentation and/or other materials provided with the distribution. 15- * 16- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18- * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19- * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20- * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27- */ 28- 29-#pragma once 30- 31-#pragma pack(push, 1) 32- 33-// Structs for writing x86/x64 instructions. 34- 35-// 8-bit relative jump. 36-typedef struct _JMP_REL_SHORT 37-{ 38- UINT8 opcode; // EB xx: JMP +2+xx 39- UINT8 operand; 40-} JMP_REL_SHORT, *PJMP_REL_SHORT; 41- 42-// 32-bit direct relative jump/call. 43-typedef struct _JMP_REL 44-{ 45- UINT8 opcode; // E9/E8 xxxxxxxx: JMP/CALL +5+xxxxxxxx 46- UINT32 operand; // Relative destination address 47-} JMP_REL, *PJMP_REL, CALL_REL; 48- 49-// 64-bit indirect absolute jump. 50-typedef struct _JMP_ABS 51-{ 52- UINT8 opcode0; // FF25 00000000: JMP [+6] 53- UINT8 opcode1; 54- UINT32 dummy; 55- UINT64 address; // Absolute destination address 56-} JMP_ABS, *PJMP_ABS; 57- 58-// 64-bit indirect absolute call. 59-typedef struct _CALL_ABS 60-{ 61- UINT8 opcode0; // FF15 00000002: CALL [+6] 62- UINT8 opcode1; 63- UINT32 dummy0; 64- UINT8 dummy1; // EB 08: JMP +10 65- UINT8 dummy2; 66- UINT64 address; // Absolute destination address 67-} CALL_ABS; 68- 69-// 32-bit direct relative conditional jumps. 70-typedef struct _JCC_REL 71-{ 72- UINT8 opcode0; // 0F8* xxxxxxxx: J** +6+xxxxxxxx 73- UINT8 opcode1; 74- UINT32 operand; // Relative destination address 75-} JCC_REL; 76- 77-// 64bit indirect absolute conditional jumps that x64 lacks. 78-typedef struct _JCC_ABS 79-{ 80- UINT8 opcode; // 7* 0E: J** +16 81- UINT8 dummy0; 82- UINT8 dummy1; // FF25 00000000: JMP [+6] 83- UINT8 dummy2; 84- UINT32 dummy3; 85- UINT64 address; // Absolute destination address 86-} JCC_ABS; 87- 88-#pragma pack(pop) 89- 90-typedef struct _TRAMPOLINE 91-{ 92- LPVOID pTarget; // [In] Address of the target function. 93- LPVOID pDetour; // [In] Address of the detour function. 94- LPVOID pTrampoline; // [In] Buffer address for the trampoline and relay function. 95- 96-#ifdef _M_X64 97- LPVOID pRelay; // [Out] Address of the relay function. 98-#endif 99- BOOL patchAbove; // [Out] Should use the hot patch area? 100- UINT nIP; // [Out] Number of the instruction boundaries. 101- UINT8 oldIPs[8]; // [Out] Instruction boundaries of the target function. 102- UINT8 newIPs[8]; // [Out] Instruction boundaries of the trampoline function. 103-} TRAMPOLINE, *PTRAMPOLINE; 104- 105-BOOL CreateTrampolineFunction(PTRAMPOLINE ct); --- exewrap/trunk/exewrap/src/minhook/src/hook.c (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/hook.c (nonexistent) @@ -1,874 +0,0 @@ 1-/* 2- * MinHook - The Minimalistic API Hooking Library for x64/x86 3- * Copyright (C) 2009-2015 Tsuda Kageyu. 4- * All rights reserved. 5- * 6- * Redistribution and use in source and binary forms, with or without 7- * modification, are permitted provided that the following conditions 8- * are met: 9- * 10- * 1. Redistributions of source code must retain the above copyright 11- * notice, this list of conditions and the following disclaimer. 12- * 2. Redistributions in binary form must reproduce the above copyright 13- * notice, this list of conditions and the following disclaimer in the 14- * documentation and/or other materials provided with the distribution. 15- * 16- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18- * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19- * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20- * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27- */ 28- 29-#define STRICT 30-#define _WIN32_WINNT 0x0501 31-#include <windows.h> 32-#include <tlhelp32.h> 33-#include <limits.h> 34- 35-#include "../include/MinHook.h" 36-#include "buffer.h" 37-#include "trampoline.h" 38- 39-#ifndef ARRAYSIZE 40- #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) 41-#endif 42- 43-// Initial capacity of the HOOK_ENTRY buffer. 44-#define INITIAL_HOOK_CAPACITY 32 45- 46-// Initial capacity of the thread IDs buffer. 47-#define INITIAL_THREAD_CAPACITY 128 48- 49-// Special hook position values. 50-#define INVALID_HOOK_POS UINT_MAX 51-#define ALL_HOOKS_POS UINT_MAX 52- 53-// Freeze() action argument defines. 54-#define ACTION_DISABLE 0 55-#define ACTION_ENABLE 1 56-#define ACTION_APPLY_QUEUED 2 57- 58-// Thread access rights for suspending/resuming threads. 59-#define THREAD_ACCESS \ 60- (THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | THREAD_SET_CONTEXT) 61- 62-// Hook information. 63-typedef struct _HOOK_ENTRY 64-{ 65- LPVOID pTarget; // Address of the target function. 66- LPVOID pDetour; // Address of the detour or relay function. 67- LPVOID pTrampoline; // Address of the trampoline function. 68- UINT8 backup[8]; // Original prologue of the target function. 69- 70- BOOL patchAbove : 1; // Uses the hot patch area. 71- BOOL isEnabled : 1; // Enabled. 72- BOOL queueEnable : 1; // Queued for enabling/disabling when != isEnabled. 73- 74- UINT nIP : 3; // Count of the instruction boundaries. 75- UINT8 oldIPs[8]; // Instruction boundaries of the target function. 76- UINT8 newIPs[8]; // Instruction boundaries of the trampoline function. 77-} HOOK_ENTRY, *PHOOK_ENTRY; 78- 79-// Suspended threads for Freeze()/Unfreeze(). 80-typedef struct _FROZEN_THREADS 81-{ 82- LPDWORD pItems; // Data heap 83- UINT capacity; // Size of allocated data heap, items 84- UINT size; // Actual number of data items 85-} FROZEN_THREADS, *PFROZEN_THREADS; 86- 87-//------------------------------------------------------------------------- 88-// Global Variables: 89-//------------------------------------------------------------------------- 90- 91-// Spin lock flag for EnterSpinLock()/LeaveSpinLock(). 92-volatile LONG g_isLocked = FALSE; 93- 94-// Private heap handle. If not NULL, this library is initialized. 95-HANDLE g_hHeap = NULL; 96- 97-// Hook entries. 98-struct 99-{ 100- PHOOK_ENTRY pItems; // Data heap 101- UINT capacity; // Size of allocated data heap, items 102- UINT size; // Actual number of data items 103-} g_hooks; 104- 105-//------------------------------------------------------------------------- 106-// Returns INVALID_HOOK_POS if not found. 107-static UINT FindHookEntry(LPVOID pTarget) 108-{ 109- UINT i; 110- for (i = 0; i < g_hooks.size; ++i) 111- { 112- if ((ULONG_PTR)pTarget == (ULONG_PTR)g_hooks.pItems[i].pTarget) 113- return i; 114- } 115- 116- return INVALID_HOOK_POS; 117-} 118- 119-//------------------------------------------------------------------------- 120-static PHOOK_ENTRY AddHookEntry() 121-{ 122- if (g_hooks.pItems == NULL) 123- { 124- g_hooks.capacity = INITIAL_HOOK_CAPACITY; 125- g_hooks.pItems = (PHOOK_ENTRY)HeapAlloc( 126- g_hHeap, 0, g_hooks.capacity * sizeof(HOOK_ENTRY)); 127- if (g_hooks.pItems == NULL) 128- return NULL; 129- } 130- else if (g_hooks.size >= g_hooks.capacity) 131- { 132- PHOOK_ENTRY p = (PHOOK_ENTRY)HeapReAlloc( 133- g_hHeap, 0, g_hooks.pItems, (g_hooks.capacity * 2) * sizeof(HOOK_ENTRY)); 134- if (p == NULL) 135- return NULL; 136- 137- g_hooks.capacity *= 2; 138- g_hooks.pItems = p; 139- } 140- 141- return &g_hooks.pItems[g_hooks.size++]; 142-} 143- 144-//------------------------------------------------------------------------- 145-static void DeleteHookEntry(UINT pos) 146-{ 147- if (pos < g_hooks.size - 1) 148- g_hooks.pItems[pos] = g_hooks.pItems[g_hooks.size - 1]; 149- 150- g_hooks.size--; 151- 152- if (g_hooks.capacity / 2 >= INITIAL_HOOK_CAPACITY && g_hooks.capacity / 2 >= g_hooks.size) 153- { 154- PHOOK_ENTRY p = (PHOOK_ENTRY)HeapReAlloc( 155- g_hHeap, 0, g_hooks.pItems, (g_hooks.capacity / 2) * sizeof(HOOK_ENTRY)); 156- if (p == NULL) 157- return; 158- 159- g_hooks.capacity /= 2; 160- g_hooks.pItems = p; 161- } 162-} 163- 164-//------------------------------------------------------------------------- 165-static DWORD_PTR FindOldIP(PHOOK_ENTRY pHook, DWORD_PTR ip) 166-{ 167- UINT i; 168- 169- if (pHook->patchAbove && ip == ((DWORD_PTR)pHook->pTarget - sizeof(JMP_REL))) 170- return (DWORD_PTR)pHook->pTarget; 171- 172- for (i = 0; i < pHook->nIP; ++i) 173- { 174- if (ip == ((DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i])) 175- return (DWORD_PTR)pHook->pTarget + pHook->oldIPs[i]; 176- } 177- 178-#ifdef _M_X64 179- // Check relay function. 180- if (ip == (DWORD_PTR)pHook->pDetour) 181- return (DWORD_PTR)pHook->pTarget; 182-#endif 183- 184- return 0; 185-} 186- 187-//------------------------------------------------------------------------- 188-static DWORD_PTR FindNewIP(PHOOK_ENTRY pHook, DWORD_PTR ip) 189-{ 190- UINT i; 191- for (i = 0; i < pHook->nIP; ++i) 192- { 193- if (ip == ((DWORD_PTR)pHook->pTarget + pHook->oldIPs[i])) 194- return (DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i]; 195- } 196- 197- return 0; 198-} 199- 200-//------------------------------------------------------------------------- 201-static void ProcessThreadIPs(HANDLE hThread, UINT pos, UINT action) 202-{ 203- // If the thread suspended in the overwritten area, 204- // move IP to the proper address. 205- 206- CONTEXT c; 207-#ifdef _M_X64 208- DWORD64 *pIP = &c.Rip; 209-#else 210- DWORD *pIP = &c.Eip; 211-#endif 212- UINT count; 213- 214- c.ContextFlags = CONTEXT_CONTROL; 215- if (!GetThreadContext(hThread, &c)) 216- return; 217- 218- if (pos == ALL_HOOKS_POS) 219- { 220- pos = 0; 221- count = g_hooks.size; 222- } 223- else 224- { 225- count = pos + 1; 226- } 227- 228- for (; pos < count; ++pos) 229- { 230- PHOOK_ENTRY pHook = &g_hooks.pItems[pos]; 231- BOOL enable; 232- DWORD_PTR ip; 233- 234- switch (action) 235- { 236- case ACTION_DISABLE: 237- enable = FALSE; 238- break; 239- 240- case ACTION_ENABLE: 241- enable = TRUE; 242- break; 243- 244- case ACTION_APPLY_QUEUED: 245- enable = pHook->queueEnable; 246- break; 247- } 248- if (pHook->isEnabled == enable) 249- continue; 250- 251- if (enable) 252- ip = FindNewIP(pHook, *pIP); 253- else 254- ip = FindOldIP(pHook, *pIP); 255- 256- if (ip != 0) 257- { 258- *pIP = ip; 259- SetThreadContext(hThread, &c); 260- } 261- } 262-} 263- 264-//------------------------------------------------------------------------- 265-static VOID EnumerateThreads(PFROZEN_THREADS pThreads) 266-{ 267- HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); 268- if (hSnapshot != INVALID_HANDLE_VALUE) 269- { 270- THREADENTRY32 te; 271- te.dwSize = sizeof(THREADENTRY32); 272- if (Thread32First(hSnapshot, &te)) 273- { 274- do 275- { 276- if (te.dwSize >= (FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(DWORD)) 277- && te.th32OwnerProcessID == GetCurrentProcessId() 278- && te.th32ThreadID != GetCurrentThreadId()) 279- { 280- if (pThreads->pItems == NULL) 281- { 282- pThreads->capacity = INITIAL_THREAD_CAPACITY; 283- pThreads->pItems 284- = (LPDWORD)HeapAlloc(g_hHeap, 0, pThreads->capacity * sizeof(DWORD)); 285- if (pThreads->pItems == NULL) 286- break; 287- } 288- else if (pThreads->size >= pThreads->capacity) 289- { 290- LPDWORD p = (LPDWORD)HeapReAlloc( 291- g_hHeap, 0, pThreads->pItems, (pThreads->capacity * 2) * sizeof(DWORD)); 292- if (p == NULL) 293- break; 294- 295- pThreads->capacity *= 2; 296- pThreads->pItems = p; 297- } 298- pThreads->pItems[pThreads->size++] = te.th32ThreadID; 299- } 300- 301- te.dwSize = sizeof(THREADENTRY32); 302- } while (Thread32Next(hSnapshot, &te)); 303- } 304- CloseHandle(hSnapshot); 305- } 306-} 307- 308-//------------------------------------------------------------------------- 309-static VOID Freeze(PFROZEN_THREADS pThreads, UINT pos, UINT action) 310-{ 311- pThreads->pItems = NULL; 312- pThreads->capacity = 0; 313- pThreads->size = 0; 314- EnumerateThreads(pThreads); 315- 316- if (pThreads->pItems != NULL) 317- { 318- UINT i; 319- for (i = 0; i < pThreads->size; ++i) 320- { 321- HANDLE hThread = OpenThread(THREAD_ACCESS, FALSE, pThreads->pItems[i]); 322- if (hThread != NULL) 323- { 324- SuspendThread(hThread); 325- ProcessThreadIPs(hThread, pos, action); 326- CloseHandle(hThread); 327- } 328- } 329- } 330-} 331- 332-//------------------------------------------------------------------------- 333-static VOID Unfreeze(PFROZEN_THREADS pThreads) 334-{ 335- if (pThreads->pItems != NULL) 336- { 337- UINT i; 338- for (i = 0; i < pThreads->size; ++i) 339- { 340- HANDLE hThread = OpenThread(THREAD_ACCESS, FALSE, pThreads->pItems[i]); 341- if (hThread != NULL) 342- { 343- ResumeThread(hThread); 344- CloseHandle(hThread); 345- } 346- } 347- 348- HeapFree(g_hHeap, 0, pThreads->pItems); 349- } 350-} 351- 352-//------------------------------------------------------------------------- 353-static MH_STATUS EnableHookLL(UINT pos, BOOL enable) 354-{ 355- PHOOK_ENTRY pHook = &g_hooks.pItems[pos]; 356- DWORD oldProtect; 357- SIZE_T patchSize = sizeof(JMP_REL); 358- LPBYTE pPatchTarget = (LPBYTE)pHook->pTarget; 359- 360- if (pHook->patchAbove) 361- { 362- pPatchTarget -= sizeof(JMP_REL); 363- patchSize += sizeof(JMP_REL_SHORT); 364- } 365- 366- if (!VirtualProtect(pPatchTarget, patchSize, PAGE_EXECUTE_READWRITE, &oldProtect)) 367- return MH_ERROR_MEMORY_PROTECT; 368- 369- if (enable) 370- { 371- PJMP_REL pJmp = (PJMP_REL)pPatchTarget; 372- pJmp->opcode = 0xE9; 373- pJmp->operand = (UINT32)((LPBYTE)pHook->pDetour - (pPatchTarget + sizeof(JMP_REL))); 374- 375- if (pHook->patchAbove) 376- { 377- PJMP_REL_SHORT pShortJmp = (PJMP_REL_SHORT)pHook->pTarget; 378- pShortJmp->opcode = 0xEB; 379- pShortJmp->operand = (UINT8)(0 - (sizeof(JMP_REL_SHORT) + sizeof(JMP_REL))); 380- } 381- } 382- else 383- { 384- if (pHook->patchAbove) 385- memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL) + sizeof(JMP_REL_SHORT)); 386- else 387- memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL)); 388- } 389- 390- VirtualProtect(pPatchTarget, patchSize, oldProtect, &oldProtect); 391- 392- // Just-in-case measure. 393- FlushInstructionCache(GetCurrentProcess(), pPatchTarget, patchSize); 394- 395- pHook->isEnabled = enable; 396- pHook->queueEnable = enable; 397- 398- return MH_OK; 399-} 400- 401-//------------------------------------------------------------------------- 402-static MH_STATUS EnableAllHooksLL(BOOL enable) 403-{ 404- MH_STATUS status = MH_OK; 405- UINT i, first = INVALID_HOOK_POS; 406- 407- for (i = 0; i < g_hooks.size; ++i) 408- { 409- if (g_hooks.pItems[i].isEnabled != enable) 410- { 411- first = i; 412- break; 413- } 414- } 415- 416- if (first != INVALID_HOOK_POS) 417- { 418- FROZEN_THREADS threads; 419- Freeze(&threads, ALL_HOOKS_POS, enable ? ACTION_ENABLE : ACTION_DISABLE); 420- 421- for (i = first; i < g_hooks.size; ++i) 422- { 423- if (g_hooks.pItems[i].isEnabled != enable) 424- { 425- status = EnableHookLL(i, enable); 426- if (status != MH_OK) 427- break; 428- } 429- } 430- 431- Unfreeze(&threads); 432- } 433- 434- return status; 435-} 436- 437-//------------------------------------------------------------------------- 438-static VOID EnterSpinLock(VOID) 439-{ 440- SIZE_T spinCount = 0; 441- 442- // Wait until the flag is FALSE. 443- while (InterlockedCompareExchange(&g_isLocked, TRUE, FALSE) != FALSE) 444- { 445- // Prevent the loop from being too busy. 446- if (spinCount < 32) 447- Sleep(0); 448- else 449- Sleep(1); 450- 451- spinCount++; 452- } 453-} 454- 455-//------------------------------------------------------------------------- 456-static VOID LeaveSpinLock(VOID) 457-{ 458- InterlockedExchange(&g_isLocked, FALSE); 459-} 460- 461-//------------------------------------------------------------------------- 462-MH_STATUS WINAPI MH_Initialize(VOID) 463-{ 464- MH_STATUS status = MH_OK; 465- 466- EnterSpinLock(); 467- 468- if (g_hHeap == NULL) 469- { 470- g_hHeap = HeapCreate(0, 0, 0); 471- if (g_hHeap != NULL) 472- { 473- // Initialize the internal function buffer. 474- InitializeBuffer(); 475- } 476- else 477- { 478- status = MH_ERROR_MEMORY_ALLOC; 479- } 480- } 481- else 482- { 483- status = MH_ERROR_ALREADY_INITIALIZED; 484- } 485- 486- LeaveSpinLock(); 487- 488- return status; 489-} 490- 491-//------------------------------------------------------------------------- 492-MH_STATUS WINAPI MH_Uninitialize(VOID) 493-{ 494- MH_STATUS status = MH_OK; 495- 496- EnterSpinLock(); 497- 498- if (g_hHeap != NULL) 499- { 500- status = EnableAllHooksLL(FALSE); 501- if (status == MH_OK) 502- { 503- // Free the internal function buffer. 504- 505- // HeapFree is actually not required, but some tools detect a false 506- // memory leak without HeapFree. 507- 508- UninitializeBuffer(); 509- 510- HeapFree(g_hHeap, 0, g_hooks.pItems); 511- HeapDestroy(g_hHeap); 512- 513- g_hHeap = NULL; 514- 515- g_hooks.pItems = NULL; 516- g_hooks.capacity = 0; 517- g_hooks.size = 0; 518- } 519- } 520- else 521- { 522- status = MH_ERROR_NOT_INITIALIZED; 523- } 524- 525- LeaveSpinLock(); 526- 527- return status; 528-} 529- 530-//------------------------------------------------------------------------- 531-MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal) 532-{ 533- MH_STATUS status = MH_OK; 534- 535- EnterSpinLock(); 536- 537- if (g_hHeap != NULL) 538- { 539- if (IsExecutableAddress(pTarget) && IsExecutableAddress(pDetour)) 540- { 541- UINT pos = FindHookEntry(pTarget); 542- if (pos == INVALID_HOOK_POS) 543- { 544- LPVOID pBuffer = AllocateBuffer(pTarget); 545- if (pBuffer != NULL) 546- { 547- TRAMPOLINE ct; 548- 549- ct.pTarget = pTarget; 550- ct.pDetour = pDetour; 551- ct.pTrampoline = pBuffer; 552- if (CreateTrampolineFunction(&ct)) 553- { 554- PHOOK_ENTRY pHook = AddHookEntry(); 555- if (pHook != NULL) 556- { 557- pHook->pTarget = ct.pTarget; 558-#ifdef _M_X64 559- pHook->pDetour = ct.pRelay; 560-#else 561- pHook->pDetour = ct.pDetour; 562-#endif 563- pHook->pTrampoline = ct.pTrampoline; 564- pHook->patchAbove = ct.patchAbove; 565- pHook->isEnabled = FALSE; 566- pHook->queueEnable = FALSE; 567- pHook->nIP = ct.nIP; 568- memcpy(pHook->oldIPs, ct.oldIPs, ARRAYSIZE(ct.oldIPs)); 569- memcpy(pHook->newIPs, ct.newIPs, ARRAYSIZE(ct.newIPs)); 570- 571- // Back up the target function. 572- 573- if (ct.patchAbove) 574- { 575- memcpy( 576- pHook->backup, 577- (LPBYTE)pTarget - sizeof(JMP_REL), 578- sizeof(JMP_REL) + sizeof(JMP_REL_SHORT)); 579- } 580- else 581- { 582- memcpy(pHook->backup, pTarget, sizeof(JMP_REL)); 583- } 584- 585- if (ppOriginal != NULL) 586- *ppOriginal = pHook->pTrampoline; 587- } 588- else 589- { 590- status = MH_ERROR_MEMORY_ALLOC; 591- } 592- } 593- else 594- { 595- status = MH_ERROR_UNSUPPORTED_FUNCTION; 596- } 597- 598- if (status != MH_OK) 599- { 600- FreeBuffer(pBuffer); 601- } 602- } 603- else 604- { 605- status = MH_ERROR_MEMORY_ALLOC; 606- } 607- } 608- else 609- { 610- status = MH_ERROR_ALREADY_CREATED; 611- } 612- } 613- else 614- { 615- status = MH_ERROR_NOT_EXECUTABLE; 616- } 617- } 618- else 619- { 620- status = MH_ERROR_NOT_INITIALIZED; 621- } 622- 623- LeaveSpinLock(); 624- 625- return status; 626-} 627- 628-//------------------------------------------------------------------------- 629-MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget) 630-{ 631- MH_STATUS status = MH_OK; 632- 633- EnterSpinLock(); 634- 635- if (g_hHeap != NULL) 636- { 637- UINT pos = FindHookEntry(pTarget); 638- if (pos != INVALID_HOOK_POS) 639- { 640- if (g_hooks.pItems[pos].isEnabled) 641- { 642- FROZEN_THREADS threads; 643- Freeze(&threads, pos, ACTION_DISABLE); 644- 645- status = EnableHookLL(pos, FALSE); 646- 647- Unfreeze(&threads); 648- } 649- 650- if (status == MH_OK) 651- { 652- FreeBuffer(g_hooks.pItems[pos].pTrampoline); 653- DeleteHookEntry(pos); 654- } 655- } 656- else 657- { 658- status = MH_ERROR_NOT_CREATED; 659- } 660- } 661- else 662- { 663- status = MH_ERROR_NOT_INITIALIZED; 664- } 665- 666- LeaveSpinLock(); 667- 668- return status; 669-} 670- 671-//------------------------------------------------------------------------- 672-static MH_STATUS EnableHook(LPVOID pTarget, BOOL enable) 673-{ 674- MH_STATUS status = MH_OK; 675- 676- EnterSpinLock(); 677- 678- if (g_hHeap != NULL) 679- { 680- if (pTarget == MH_ALL_HOOKS) 681- { 682- status = EnableAllHooksLL(enable); 683- } 684- else 685- { 686- FROZEN_THREADS threads; 687- UINT pos = FindHookEntry(pTarget); 688- if (pos != INVALID_HOOK_POS) 689- { 690- if (g_hooks.pItems[pos].isEnabled != enable) 691- { 692- Freeze(&threads, pos, ACTION_ENABLE); 693- 694- status = EnableHookLL(pos, enable); 695- 696- Unfreeze(&threads); 697- } 698- else 699- { 700- status = enable ? MH_ERROR_ENABLED : MH_ERROR_DISABLED; 701- } 702- } 703- else 704- { 705- status = MH_ERROR_NOT_CREATED; 706- } 707- } 708- } 709- else 710- { 711- status = MH_ERROR_NOT_INITIALIZED; 712- } 713- 714- LeaveSpinLock(); 715- 716- return status; 717-} 718- 719-//------------------------------------------------------------------------- 720-MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget) 721-{ 722- return EnableHook(pTarget, TRUE); 723-} 724- 725-//------------------------------------------------------------------------- 726-MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget) 727-{ 728- return EnableHook(pTarget, FALSE); 729-} 730- 731-//------------------------------------------------------------------------- 732-static MH_STATUS QueueHook(LPVOID pTarget, BOOL queueEnable) 733-{ 734- MH_STATUS status = MH_OK; 735- 736- EnterSpinLock(); 737- 738- if (g_hHeap != NULL) 739- { 740- if (pTarget == MH_ALL_HOOKS) 741- { 742- UINT i; 743- for (i = 0; i < g_hooks.size; ++i) 744- g_hooks.pItems[i].queueEnable = queueEnable; 745- } 746- else 747- { 748- UINT pos = FindHookEntry(pTarget); 749- if (pos != INVALID_HOOK_POS) 750- { 751- g_hooks.pItems[pos].queueEnable = queueEnable; 752- } 753- else 754- { 755- status = MH_ERROR_NOT_CREATED; 756- } 757- } 758- } 759- else 760- { 761- status = MH_ERROR_NOT_INITIALIZED; 762- } 763- 764- LeaveSpinLock(); 765- 766- return status; 767-} 768- 769-//------------------------------------------------------------------------- 770-MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget) 771-{ 772- return QueueHook(pTarget, TRUE); 773-} 774- 775-//------------------------------------------------------------------------- 776-MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget) 777-{ 778- return QueueHook(pTarget, FALSE); 779-} 780- 781-//------------------------------------------------------------------------- 782-MH_STATUS WINAPI MH_ApplyQueued(VOID) 783-{ 784- MH_STATUS status = MH_OK; 785- UINT i, first = INVALID_HOOK_POS; 786- 787- EnterSpinLock(); 788- 789- if (g_hHeap != NULL) 790- { 791- for (i = 0; i < g_hooks.size; ++i) 792- { 793- if (g_hooks.pItems[i].isEnabled != g_hooks.pItems[i].queueEnable) 794- { 795- first = i; 796- break; 797- } 798- } 799- 800- if (first != INVALID_HOOK_POS) 801- { 802- FROZEN_THREADS threads; 803- Freeze(&threads, ALL_HOOKS_POS, ACTION_APPLY_QUEUED); 804- 805- for (i = first; i < g_hooks.size; ++i) 806- { 807- PHOOK_ENTRY pHook = &g_hooks.pItems[i]; 808- if (pHook->isEnabled != pHook->queueEnable) 809- { 810- status = EnableHookLL(i, pHook->queueEnable); 811- if (status != MH_OK) 812- break; 813- } 814- } 815- 816- Unfreeze(&threads); 817- } 818- } 819- else 820- { 821- status = MH_ERROR_NOT_INITIALIZED; 822- } 823- 824- LeaveSpinLock(); 825- 826- return status; 827-} 828- 829-//------------------------------------------------------------------------- 830-MH_STATUS WINAPI MH_CreateHookApi( 831- LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal) 832-{ 833- HMODULE hModule; 834- LPVOID pTarget; 835- 836- hModule = GetModuleHandleW(pszModule); 837- if (hModule == NULL) 838- return MH_ERROR_MODULE_NOT_FOUND; 839- 840- pTarget = (LPVOID)GetProcAddress(hModule, pszProcName); 841- if (pTarget == NULL) 842- return MH_ERROR_FUNCTION_NOT_FOUND; 843- 844- return MH_CreateHook(pTarget, pDetour, ppOriginal); 845-} 846- 847-//------------------------------------------------------------------------- 848-const char * WINAPI MH_StatusToString(MH_STATUS status) 849-{ 850-#define MH_ST2STR(x) \ 851- case x: \ 852- return #x; 853- 854- switch (status) { 855- MH_ST2STR(MH_UNKNOWN) 856- MH_ST2STR(MH_OK) 857- MH_ST2STR(MH_ERROR_ALREADY_INITIALIZED) 858- MH_ST2STR(MH_ERROR_NOT_INITIALIZED) 859- MH_ST2STR(MH_ERROR_ALREADY_CREATED) 860- MH_ST2STR(MH_ERROR_NOT_CREATED) 861- MH_ST2STR(MH_ERROR_ENABLED) 862- MH_ST2STR(MH_ERROR_DISABLED) 863- MH_ST2STR(MH_ERROR_NOT_EXECUTABLE) 864- MH_ST2STR(MH_ERROR_UNSUPPORTED_FUNCTION) 865- MH_ST2STR(MH_ERROR_MEMORY_ALLOC) 866- MH_ST2STR(MH_ERROR_MEMORY_PROTECT) 867- MH_ST2STR(MH_ERROR_MODULE_NOT_FOUND) 868- MH_ST2STR(MH_ERROR_FUNCTION_NOT_FOUND) 869- } 870- 871-#undef MH_ST2STR 872- 873- return "(unknown)"; 874-} --- exewrap/trunk/exewrap/src/minhook/src/buffer.c (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/buffer.c (nonexistent) @@ -1,315 +0,0 @@ 1-/* 2- * MinHook - The Minimalistic API Hooking Library for x64/x86 3- * Copyright (C) 2009-2015 Tsuda Kageyu. 4- * All rights reserved. 5- * 6- * Redistribution and use in source and binary forms, with or without 7- * modification, are permitted provided that the following conditions 8- * are met: 9- * 10- * 1. Redistributions of source code must retain the above copyright 11- * notice, this list of conditions and the following disclaimer. 12- * 2. Redistributions in binary form must reproduce the above copyright 13- * notice, this list of conditions and the following disclaimer in the 14- * documentation and/or other materials provided with the distribution. 15- * 16- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18- * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19- * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20- * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27- */ 28- 29-#define STRICT 30-#define NOMINMAX 31-#define _WIN32_WINNT 0x0501 32-#include <windows.h> 33-#include "buffer.h" 34- 35-// Size of each memory block. (= page size of VirtualAlloc) 36-#define MEMORY_BLOCK_SIZE 0x1000 37- 38-// Max range for seeking a memory block. (= 1024MB) 39-#define MAX_MEMORY_RANGE 0x40000000 40- 41-// Memory protection flags to check the executable address. 42-#define PAGE_EXECUTE_FLAGS \ 43- (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY) 44- 45-// Memory slot. 46-typedef struct _MEMORY_SLOT 47-{ 48- union 49- { 50- struct _MEMORY_SLOT *pNext; 51- UINT8 buffer[MEMORY_SLOT_SIZE]; 52- }; 53-} MEMORY_SLOT, *PMEMORY_SLOT; 54- 55-// Memory block info. Placed at the head of each block. 56-typedef struct _MEMORY_BLOCK 57-{ 58- struct _MEMORY_BLOCK *pNext; 59- PMEMORY_SLOT pFree; // First element of the free slot list. 60- UINT usedCount; 61-} MEMORY_BLOCK, *PMEMORY_BLOCK; 62- 63-//------------------------------------------------------------------------- 64-// Global Variables: 65-//------------------------------------------------------------------------- 66- 67-// First element of the memory block list. 68-PMEMORY_BLOCK g_pMemoryBlocks; 69- 70-//------------------------------------------------------------------------- 71-VOID InitializeBuffer(VOID) 72-{ 73- // Nothing to do for now. 74-} 75- 76-//------------------------------------------------------------------------- 77-VOID UninitializeBuffer(VOID) 78-{ 79- PMEMORY_BLOCK pBlock = g_pMemoryBlocks; 80- g_pMemoryBlocks = NULL; 81- 82- while (pBlock) 83- { 84- PMEMORY_BLOCK pNext = pBlock->pNext; 85- VirtualFree(pBlock, 0, MEM_RELEASE); 86- pBlock = pNext; 87- } 88-} 89- 90-//------------------------------------------------------------------------- 91-#ifdef _M_X64 92-static LPVOID FindPrevFreeRegion(LPVOID pAddress, LPVOID pMinAddr, DWORD dwAllocationGranularity) 93-{ 94- ULONG_PTR tryAddr = (ULONG_PTR)pAddress; 95- 96- // Round down to the next allocation granularity. 97- tryAddr -= tryAddr % dwAllocationGranularity; 98- 99- // Start from the previous allocation granularity multiply. 100- tryAddr -= dwAllocationGranularity; 101- 102- while (tryAddr >= (ULONG_PTR)pMinAddr) 103- { 104- MEMORY_BASIC_INFORMATION mbi; 105- if (VirtualQuery((LPVOID)tryAddr, &mbi, sizeof(MEMORY_BASIC_INFORMATION)) == 0) 106- break; 107- 108- if (mbi.State == MEM_FREE) 109- return (LPVOID)tryAddr; 110- 111- if ((ULONG_PTR)mbi.AllocationBase < dwAllocationGranularity) 112- break; 113- 114- tryAddr = (ULONG_PTR)mbi.AllocationBase - dwAllocationGranularity; 115- } 116- 117- return NULL; 118-} 119-#endif 120- 121-//------------------------------------------------------------------------- 122-#ifdef _M_X64 123-static LPVOID FindNextFreeRegion(LPVOID pAddress, LPVOID pMaxAddr, DWORD dwAllocationGranularity) 124-{ 125- ULONG_PTR tryAddr = (ULONG_PTR)pAddress; 126- 127- // Round down to the next allocation granularity. 128- tryAddr -= tryAddr % dwAllocationGranularity; 129- 130- // Start from the next allocation granularity multiply. 131- tryAddr += dwAllocationGranularity; 132- 133- while (tryAddr <= (ULONG_PTR)pMaxAddr) 134- { 135- MEMORY_BASIC_INFORMATION mbi; 136- if (VirtualQuery((LPVOID)tryAddr, &mbi, sizeof(MEMORY_BASIC_INFORMATION)) == 0) 137- break; 138- 139- if (mbi.State == MEM_FREE) 140- return (LPVOID)tryAddr; 141- 142- tryAddr = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; 143- 144- // Round up to the next allocation granularity. 145- tryAddr += dwAllocationGranularity - 1; 146- tryAddr -= tryAddr % dwAllocationGranularity; 147- } 148- 149- return NULL; 150-} 151-#endif 152- 153-//------------------------------------------------------------------------- 154-static PMEMORY_BLOCK GetMemoryBlock(LPVOID pOrigin) 155-{ 156- PMEMORY_BLOCK pBlock; 157-#ifdef _M_X64 158- ULONG_PTR minAddr; 159- ULONG_PTR maxAddr; 160- 161- SYSTEM_INFO si; 162- GetSystemInfo(&si); 163- minAddr = (ULONG_PTR)si.lpMinimumApplicationAddress; 164- maxAddr = (ULONG_PTR)si.lpMaximumApplicationAddress; 165- 166- // pOrigin ± 512MB 167- if ((ULONG_PTR)pOrigin > MAX_MEMORY_RANGE && minAddr < (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE) 168- minAddr = (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE; 169- 170- if (maxAddr > (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE) 171- maxAddr = (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE; 172- 173- // Make room for MEMORY_BLOCK_SIZE bytes. 174- maxAddr -= MEMORY_BLOCK_SIZE - 1; 175-#endif 176- 177- // Look the registered blocks for a reachable one. 178- for (pBlock = g_pMemoryBlocks; pBlock != NULL; pBlock = pBlock->pNext) 179- { 180-#ifdef _M_X64 181- // Ignore the blocks too far. 182- if ((ULONG_PTR)pBlock < minAddr || (ULONG_PTR)pBlock >= maxAddr) 183- continue; 184-#endif 185- // The block has at least one unused slot. 186- if (pBlock->pFree != NULL) 187- return pBlock; 188- } 189- 190-#ifdef _M_X64 191- // Alloc a new block above if not found. 192- { 193- LPVOID pAlloc = pOrigin; 194- while ((ULONG_PTR)pAlloc >= minAddr) 195- { 196- pAlloc = FindPrevFreeRegion(pAlloc, (LPVOID)minAddr, si.dwAllocationGranularity); 197- if (pAlloc == NULL) 198- break; 199- 200- pBlock = (PMEMORY_BLOCK)VirtualAlloc( 201- pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); 202- if (pBlock != NULL) 203- break; 204- } 205- } 206- 207- // Alloc a new block below if not found. 208- if (pBlock == NULL) 209- { 210- LPVOID pAlloc = pOrigin; 211- while ((ULONG_PTR)pAlloc <= maxAddr) 212- { 213- pAlloc = FindNextFreeRegion(pAlloc, (LPVOID)maxAddr, si.dwAllocationGranularity); 214- if (pAlloc == NULL) 215- break; 216- 217- pBlock = (PMEMORY_BLOCK)VirtualAlloc( 218- pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); 219- if (pBlock != NULL) 220- break; 221- } 222- } 223-#else 224- // In x86 mode, a memory block can be placed anywhere. 225- pBlock = (PMEMORY_BLOCK)VirtualAlloc( 226- NULL, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); 227-#endif 228- 229- if (pBlock != NULL) 230- { 231- // Build a linked list of all the slots. 232- PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBlock + 1; 233- pBlock->pFree = NULL; 234- pBlock->usedCount = 0; 235- do 236- { 237- pSlot->pNext = pBlock->pFree; 238- pBlock->pFree = pSlot; 239- pSlot++; 240- } while ((ULONG_PTR)pSlot - (ULONG_PTR)pBlock <= MEMORY_BLOCK_SIZE - MEMORY_SLOT_SIZE); 241- 242- pBlock->pNext = g_pMemoryBlocks; 243- g_pMemoryBlocks = pBlock; 244- } 245- 246- return pBlock; 247-} 248- 249-//------------------------------------------------------------------------- 250-LPVOID AllocateBuffer(LPVOID pOrigin) 251-{ 252- PMEMORY_SLOT pSlot; 253- PMEMORY_BLOCK pBlock = GetMemoryBlock(pOrigin); 254- if (pBlock == NULL) 255- return NULL; 256- 257- // Remove an unused slot from the list. 258- pSlot = pBlock->pFree; 259- pBlock->pFree = pSlot->pNext; 260- pBlock->usedCount++; 261-#ifdef _DEBUG 262- // Fill the slot with INT3 for debugging. 263- memset(pSlot, 0xCC, sizeof(MEMORY_SLOT)); 264-#endif 265- return pSlot; 266-} 267- 268-//------------------------------------------------------------------------- 269-VOID FreeBuffer(LPVOID pBuffer) 270-{ 271- PMEMORY_BLOCK pBlock = g_pMemoryBlocks; 272- PMEMORY_BLOCK pPrev = NULL; 273- ULONG_PTR pTargetBlock = ((ULONG_PTR)pBuffer / MEMORY_BLOCK_SIZE) * MEMORY_BLOCK_SIZE; 274- 275- while (pBlock != NULL) 276- { 277- if ((ULONG_PTR)pBlock == pTargetBlock) 278- { 279- PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBuffer; 280-#ifdef _DEBUG 281- // Clear the released slot for debugging. 282- memset(pSlot, 0x00, sizeof(MEMORY_SLOT)); 283-#endif 284- // Restore the released slot to the list. 285- pSlot->pNext = pBlock->pFree; 286- pBlock->pFree = pSlot; 287- pBlock->usedCount--; 288- 289- // Free if unused. 290- if (pBlock->usedCount == 0) 291- { 292- if (pPrev) 293- pPrev->pNext = pBlock->pNext; 294- else 295- g_pMemoryBlocks = pBlock->pNext; 296- 297- VirtualFree(pBlock, 0, MEM_RELEASE); 298- } 299- 300- break; 301- } 302- 303- pPrev = pBlock; 304- pBlock = pBlock->pNext; 305- } 306-} 307- 308-//------------------------------------------------------------------------- 309-BOOL IsExecutableAddress(LPVOID pAddress) 310-{ 311- MEMORY_BASIC_INFORMATION mi; 312- VirtualQuery(pAddress, &mi, sizeof(MEMORY_BASIC_INFORMATION)); 313- 314- return (mi.State == MEM_COMMIT && (mi.Protect & PAGE_EXECUTE_FLAGS)); 315-} --- exewrap/trunk/exewrap/src/minhook/src/trampoline.c (revision 38) +++ exewrap/trunk/exewrap/src/minhook/src/trampoline.c (nonexistent) @@ -1,316 +0,0 @@ 1-/* 2- * MinHook - The Minimalistic API Hooking Library for x64/x86 3- * Copyright (C) 2009-2015 Tsuda Kageyu. 4- * All rights reserved. 5- * 6- * Redistribution and use in source and binary forms, with or without 7- * modification, are permitted provided that the following conditions 8- * are met: 9- * 10- * 1. Redistributions of source code must retain the above copyright 11- * notice, this list of conditions and the following disclaimer. 12- * 2. Redistributions in binary form must reproduce the above copyright 13- * notice, this list of conditions and the following disclaimer in the 14- * documentation and/or other materials provided with the distribution. 15- * 16- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18- * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19- * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20- * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27- */ 28- 29-#include <windows.h> 30- 31-#ifndef ARRAYSIZE 32- #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) 33-#endif 34- 35-#ifdef _M_X64 36- #include "./hde/hde64.h" 37- typedef hde64s HDE; 38- #define HDE_DISASM(code, hs) hde64_disasm(code, hs) 39-#else 40- #include "./hde/hde32.h" 41- typedef hde32s HDE; 42- #define HDE_DISASM(code, hs) hde32_disasm(code, hs) 43-#endif 44- 45-#include "trampoline.h" 46-#include "buffer.h" 47- 48-// Maximum size of a trampoline function. 49-#ifdef _M_X64 50- #define TRAMPOLINE_MAX_SIZE (MEMORY_SLOT_SIZE - sizeof(JMP_ABS)) 51-#else 52- #define TRAMPOLINE_MAX_SIZE MEMORY_SLOT_SIZE 53-#endif 54- 55-//------------------------------------------------------------------------- 56-static BOOL IsCodePadding(LPBYTE pInst, UINT size) 57-{ 58- UINT i; 59- 60- if (pInst[0] != 0x00 && pInst[0] != 0x90 && pInst[0] != 0xCC) 61- return FALSE; 62- 63- for (i = 1; i < size; ++i) 64- { 65- if (pInst[i] != pInst[0]) 66- return FALSE; 67- } 68- return TRUE; 69-} 70- 71-//------------------------------------------------------------------------- 72-BOOL CreateTrampolineFunction(PTRAMPOLINE ct) 73-{ 74-#ifdef _M_X64 75- CALL_ABS call = { 76- 0xFF, 0x15, 0x00000002, // FF15 00000002: CALL [RIP+8] 77- 0xEB, 0x08, // EB 08: JMP +10 78- 0x0000000000000000ULL // Absolute destination address 79- }; 80- JMP_ABS jmp = { 81- 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] 82- 0x0000000000000000ULL // Absolute destination address 83- }; 84- JCC_ABS jcc = { 85- 0x70, 0x0E, // 7* 0E: J** +16 86- 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] 87- 0x0000000000000000ULL // Absolute destination address 88- }; 89-#else 90- CALL_REL call = { 91- 0xE8, // E8 xxxxxxxx: CALL +5+xxxxxxxx 92- 0x00000000 // Relative destination address 93- }; 94- JMP_REL jmp = { 95- 0xE9, // E9 xxxxxxxx: JMP +5+xxxxxxxx 96- 0x00000000 // Relative destination address 97- }; 98- JCC_REL jcc = { 99- 0x0F, 0x80, // 0F8* xxxxxxxx: J** +6+xxxxxxxx 100- 0x00000000 // Relative destination address 101- }; 102-#endif 103- 104- UINT8 oldPos = 0; 105- UINT8 newPos = 0; 106- ULONG_PTR jmpDest = 0; // Destination address of an internal jump. 107- BOOL finished = FALSE; // Is the function completed? 108-#ifdef _M_X64 109- UINT8 instBuf[16]; 110-#endif 111- 112- ct->patchAbove = FALSE; 113- ct->nIP = 0; 114- 115- do 116- { 117- HDE hs; 118- UINT copySize; 119- LPVOID pCopySrc; 120- ULONG_PTR pOldInst = (ULONG_PTR)ct->pTarget + oldPos; 121- ULONG_PTR pNewInst = (ULONG_PTR)ct->pTrampoline + newPos; 122- 123- copySize = HDE_DISASM((LPVOID)pOldInst, &hs); 124- if (hs.flags & F_ERROR) 125- return FALSE; 126- 127- pCopySrc = (LPVOID)pOldInst; 128- if (oldPos >= sizeof(JMP_REL)) 129- { 130- // The trampoline function is long enough. 131- // Complete the function with the jump to the target function. 132-#ifdef _M_X64 133- jmp.address = pOldInst; 134-#else 135- jmp.operand = (UINT32)(pOldInst - (pNewInst + sizeof(jmp))); 136-#endif 137- pCopySrc = &jmp; 138- copySize = sizeof(jmp); 139- 140- finished = TRUE; 141- } 142-#ifdef _M_X64 143- else if ((hs.modrm & 0xC7) == 0x05) 144- { 145- // Instructions using RIP relative addressing. (ModR/M = 00???101B) 146- 147- // Modify the RIP relative address. 148- PUINT32 pRelAddr; 149- 150- // Avoid using memcpy to reduce the footprint. 151-#ifndef _MSC_VER 152- memcpy(instBuf, (LPBYTE)pOldInst, copySize); 153-#else 154- __movsb(instBuf, (LPBYTE)pOldInst, copySize); 155-#endif 156- pCopySrc = instBuf; 157- 158- // Relative address is stored at (instruction length - immediate value length - 4). 159- pRelAddr = (PUINT32)(instBuf + hs.len - ((hs.flags & 0x3C) >> 2) - 4); 160- *pRelAddr 161- = (UINT32)((pOldInst + hs.len + (INT32)hs.disp.disp32) - (pNewInst + hs.len)); 162- 163- // Complete the function if JMP (FF /4). 164- if (hs.opcode == 0xFF && hs.modrm_reg == 4) 165- finished = TRUE; 166- } 167-#endif 168- else if (hs.opcode == 0xE8) 169- { 170- // Direct relative CALL 171- ULONG_PTR dest = pOldInst + hs.len + (INT32)hs.imm.imm32; 172-#ifdef _M_X64 173- call.address = dest; 174-#else 175- call.operand = (UINT32)(dest - (pNewInst + sizeof(call))); 176-#endif 177- pCopySrc = &call; 178- copySize = sizeof(call); 179- } 180- else if ((hs.opcode & 0xFD) == 0xE9) 181- { 182- // Direct relative JMP (EB or E9) 183- ULONG_PTR dest = pOldInst + hs.len; 184- 185- if (hs.opcode == 0xEB) // isShort jmp 186- dest += (INT8)hs.imm.imm8; 187- else 188- dest += (INT32)hs.imm.imm32; 189- 190- // Simply copy an internal jump. 191- if ((ULONG_PTR)ct->pTarget <= dest 192- && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) 193- { 194- if (jmpDest < dest) 195- jmpDest = dest; 196- } 197- else 198- { 199-#ifdef _M_X64 200- jmp.address = dest; 201-#else 202- jmp.operand = (UINT32)(dest - (pNewInst + sizeof(jmp))); 203-#endif 204- pCopySrc = &jmp; 205- copySize = sizeof(jmp); 206- 207- // Exit the function If it is not in the branch 208- finished = (pOldInst >= jmpDest); 209- } 210- } 211- else if ((hs.opcode & 0xF0) == 0x70 212- || (hs.opcode & 0xFC) == 0xE0 213- || (hs.opcode2 & 0xF0) == 0x80) 214- { 215- // Direct relative Jcc 216- ULONG_PTR dest = pOldInst + hs.len; 217- 218- if ((hs.opcode & 0xF0) == 0x70 // Jcc 219- || (hs.opcode & 0xFC) == 0xE0) // LOOPNZ/LOOPZ/LOOP/JECXZ 220- dest += (INT8)hs.imm.imm8; 221- else 222- dest += (INT32)hs.imm.imm32; 223- 224- // Simply copy an internal jump. 225- if ((ULONG_PTR)ct->pTarget <= dest 226- && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) 227- { 228- if (jmpDest < dest) 229- jmpDest = dest; 230- } 231- else if ((hs.opcode & 0xFC) == 0xE0) 232- { 233- // LOOPNZ/LOOPZ/LOOP/JCXZ/JECXZ to the outside are not supported. 234- return FALSE; 235- } 236- else 237- { 238- UINT8 cond = ((hs.opcode != 0x0F ? hs.opcode : hs.opcode2) & 0x0F); 239-#ifdef _M_X64 240- // Invert the condition in x64 mode to simplify the conditional jump logic. 241- jcc.opcode = 0x71 ^ cond; 242- jcc.address = dest; 243-#else 244- jcc.opcode1 = 0x80 | cond; 245- jcc.operand = (UINT32)(dest - (pNewInst + sizeof(jcc))); 246-#endif 247- pCopySrc = &jcc; 248- copySize = sizeof(jcc); 249- } 250- } 251- else if ((hs.opcode & 0xFE) == 0xC2) 252- { 253- // RET (C2 or C3) 254- 255- // Complete the function if not in a branch. 256- finished = (pOldInst >= jmpDest); 257- } 258- 259- // Can't alter the instruction length in a branch. 260- if (pOldInst < jmpDest && copySize != hs.len) 261- return FALSE; 262- 263- // Trampoline function is too large. 264- if ((newPos + copySize) > TRAMPOLINE_MAX_SIZE) 265- return FALSE; 266- 267- // Trampoline function has too many instructions. 268- if (ct->nIP >= ARRAYSIZE(ct->oldIPs)) 269- return FALSE; 270- 271- ct->oldIPs[ct->nIP] = oldPos; 272- ct->newIPs[ct->nIP] = newPos; 273- ct->nIP++; 274- 275- // Avoid using memcpy to reduce the footprint. 276-#ifndef _MSC_VER 277- memcpy((LPBYTE)ct->pTrampoline + newPos, pCopySrc, copySize); 278-#else 279- __movsb((LPBYTE)ct->pTrampoline + newPos, pCopySrc, copySize); 280-#endif 281- newPos += copySize; 282- oldPos += hs.len; 283- } 284- while (!finished); 285- 286- // Is there enough place for a long jump? 287- if (oldPos < sizeof(JMP_REL) 288- && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL) - oldPos)) 289- { 290- // Is there enough place for a short jump? 291- if (oldPos < sizeof(JMP_REL_SHORT) 292- && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL_SHORT) - oldPos)) 293- { 294- return FALSE; 295- } 296- 297- // Can we place the long jump above the function? 298- if (!IsExecutableAddress((LPBYTE)ct->pTarget - sizeof(JMP_REL))) 299- return FALSE; 300- 301- if (!IsCodePadding((LPBYTE)ct->pTarget - sizeof(JMP_REL), sizeof(JMP_REL))) 302- return FALSE; 303- 304- ct->patchAbove = TRUE; 305- } 306- 307-#ifdef _M_X64 308- // Create a relay function. 309- jmp.address = (ULONG_PTR)ct->pDetour; 310- 311- ct->pRelay = (LPBYTE)ct->pTrampoline + newPos; 312- memcpy(ct->pRelay, &jmp, sizeof(jmp)); 313-#endif 314- 315- return TRUE; 316-} --- exewrap/trunk/exewrap/src/minhook/WindowsSDK/include/winapifamily.h (revision 38) +++ exewrap/trunk/exewrap/src/minhook/WindowsSDK/include/winapifamily.h (nonexistent) @@ -1,240 +0,0 @@ 1-/* 2- 3-Copyright (c) Microsoft Corporation. All rights reserved. 4- 5-Module Name: 6- 7- winapifamily.h 8- 9-Abstract: 10- 11- Master include file for API family partitioning. 12- 13-*/ 14- 15-#ifndef _INC_WINAPIFAMILY 16-#define _INC_WINAPIFAMILY 17- 18-#if defined(_MSC_VER) && !defined(MOFCOMP_PASS) 19-#if _MSC_VER >= 1200 20-#pragma warning(push) 21-#pragma warning(disable:4001) /* nonstandard extension 'single line comment' was used */ 22-#endif 23-#pragma once 24-#endif // defined(_MSC_VER) && !defined(MOFCOMP_PASS) 25- 26-#include <winpackagefamily.h> 27- 28-/* 29- * When compiling C and C++ code using SDK header files, the development 30- * environment can specify a target platform by #define-ing the 31- * pre-processor symbol WINAPI_FAMILY to one of the following values. 32- * Each FAMILY value denotes an application family for which a different 33- * subset of the total set of header-file-defined APIs are available. 34- * Setting the WINAPI_FAMILY value will effectively hide from the 35- * editing and compilation environments the existence of APIs that 36- * are not applicable to the family of applications targeting a 37- * specific platform. 38- */ 39- 40-/* In Windows 10, WINAPI_PARTITIONs will be used to add additional 41- * device specific APIs to a particular WINAPI_FAMILY. 42- * For example, when writing Windows Universal apps, specifying 43- * WINAPI_FAMILY_APP will hide phone APIs from compilation. 44- * However, specifying WINAPI_PARTITION_PHONE_APP=1 additionally, will 45- * unhide any API hidden behind the partition, to the compiler. 46- 47- * The following partitions are currently defined: 48- * WINAPI_PARTITION_DESKTOP // usable for Desktop Win32 apps (but not store apps) 49- * WINAPI_PARTITION_APP // usable for Windows Universal store apps 50- * WINAPI_PARTITION_PC_APP // specific to Desktop-only store apps 51- * WINAPI_PARTITION_PHONE_APP // specific to Phone-only store apps 52- * WINAPI_PARTITION_SYSTEM // specific to System applications 53- 54- * The following partitions are indirect partitions and defined in 55- * winpackagefamily.h. These partitions are related to package based 56- * partitions. For example, specifying WINAPI_PARTITION_SERVER=1 will light up 57- * any API hidden behind the package based partitions that are bound to 58- * WINAPI_PARTITION_SERVER, to the compiler. 59- * WINAPI_PARTITION_SERVER // specific to Server applications 60-*/ 61- 62-/* 63- * The WINAPI_FAMILY values of 0 and 1 are reserved to ensure that 64- * an error will occur if WINAPI_FAMILY is set to any 65- * WINAPI_PARTITION value (which must be 0 or 1, see below). 66- */ 67-#define WINAPI_FAMILY_PC_APP 2 /* Windows Store Applications */ 68-#define WINAPI_FAMILY_PHONE_APP 3 /* Windows Phone Applications */ 69-#define WINAPI_FAMILY_SYSTEM 4 /* Windows Drivers and Tools */ 70-#define WINAPI_FAMILY_SERVER 5 /* Windows Server Applications */ 71-#define WINAPI_FAMILY_DESKTOP_APP 100 /* Windows Desktop Applications */ 72-/* The value of WINAPI_FAMILY_DESKTOP_APP may change in future SDKs. */ 73-/* Additional WINAPI_FAMILY values may be defined in future SDKs. */ 74- 75-/* 76- * For compatibility with Windows 8 header files, the following 77- * synonym for WINAPI_FAMILY_PC_APP is temporarily #define'd. 78- * Use of this symbol should be considered deprecated. 79- */ 80-#define WINAPI_FAMILY_APP WINAPI_FAMILY_PC_APP 81- 82-/* 83- * If no WINAPI_FAMILY value is specified, then all APIs available to 84- * Windows desktop applications are exposed. 85- */ 86-#ifndef WINAPI_FAMILY 87-#define WINAPI_FAMILY WINAPI_FAMILY_DESKTOP_APP 88-#endif 89- 90-/* 91- * API PARTITONs are part of an indirection mechanism for mapping between 92- * individual APIs and the FAMILYs to which they apply. 93- * Each PARTITION is a category or subset of named APIs. PARTITIONs 94- * are permitted to have overlapping membership -- some single API 95- * might be part of more than one PARTITION. PARTITIONS are each #define-ed 96- * to be either 1 or 0 or depending on the platform at which the app is targeted. 97- */ 98- 99-/* 100- * The mapping between families and partitions is summarized here. 101- * An X indicates that the given partition is active for the given 102- * platform/family. 103- * 104- * +-------------------+---+ 105- * | *Partition* | | 106- * +---+---+---+---+---+---+ 107- * | | | | | | | 108- * | | | | | | | 109- * | | | | P | | | 110- * | | | | H | | | 111- * | D | | | O | | | 112- * | E | | P | N | S | S | 113- * | S | | C | E | Y | E | 114- * | K | | _ | _ | S | R | 115- * | T | A | A | A | T | V | 116- * +-------------------------+----+ O | P | P | P | E | E | 117- * | *Platform/Family* \| P | P | P | P | M | R | 118- * +------------------------------+---+---+---+---+---+---+ 119- * | WINAPI_FAMILY_DESKTOP_APP | X | X | X | | | | 120- * +------------------------------+---+---+---+---+---+---+ 121- * | WINAPI_FAMILY_PC_APP | | X | X | | | | 122- * +------------------------------+---+---+---+---+---+---+ 123- * | WINAPI_FAMILY_PHONE_APP | | X | | X | | | 124- * +----------------------------- +---+---+---+---+---+---+ 125- * | WINAPI_FAMILY_SYSTEM | | | | | X | | 126- * +----------------------------- +---+---+---+---+---+---+ 127- * | WINAPI_FAMILY_SERVER | | | | | X | X | 128- * +------------------------------+---+---+---+---+---+---+ 129- * 130- * The table above is encoded in the following expressions, 131- * each of which evaluates to 1 or 0. 132- * 133- * Whenever a new family is added, all of these expressions 134- * need to be reconsidered. 135- */ 136-#if WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP && \ 137- WINAPI_FAMILY != WINAPI_FAMILY_PC_APP && \ 138- WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP && \ 139- WINAPI_FAMILY != WINAPI_FAMILY_SYSTEM && \ 140- WINAPI_FAMILY != WINAPI_FAMILY_SERVER 141-#error Unknown WINAPI_FAMILY value. Was it defined in terms of a WINAPI_PARTITION_* value? 142-#endif 143- 144-#ifndef WINAPI_PARTITION_DESKTOP 145-#define WINAPI_PARTITION_DESKTOP (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) 146-#endif 147- 148-#ifndef WINAPI_PARTITION_APP 149-#define WINAPI_PARTITION_APP \ 150- (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP || \ 151- WINAPI_FAMILY == WINAPI_FAMILY_PC_APP || \ 152- WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) 153-#endif 154- 155-#ifndef WINAPI_PARTITION_PC_APP 156-#define WINAPI_PARTITION_PC_APP \ 157- (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP || \ 158- WINAPI_FAMILY == WINAPI_FAMILY_PC_APP) 159-#endif 160- 161-#ifndef WINAPI_PARTITION_PHONE_APP 162-#define WINAPI_PARTITION_PHONE_APP (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) 163-#endif 164- 165-/* 166- * SYSTEM is the only partition defined here. 167- * All other System based editions are defined as packages 168- * on top of the System partition. 169- * See winpackagefamily.h for packages level partitions 170- */ 171-#ifndef WINAPI_PARTITION_SYSTEM 172-#define WINAPI_PARTITION_SYSTEM \ 173- (WINAPI_FAMILY == WINAPI_FAMILY_SYSTEM || \ 174- WINAPI_FAMILY == WINAPI_FAMILY_SERVER) 175-#endif 176- 177-/* 178- * For compatibility with Windows Phone 8 header files, the following 179- * synonym for WINAPI_PARTITION_PHONE_APP is temporarily #define'd. 180- * Use of this symbol should be regarded as deprecated. 181- */ 182-#define WINAPI_PARTITION_PHONE WINAPI_PARTITION_PHONE_APP 183- 184-/* 185- * Header files use the WINAPI_FAMILY_PARTITION macro to assign one or 186- * more declarations to some group of partitions. The macro chooses 187- * whether the preprocessor will emit or omit a sequence of declarations 188- * bracketed by an #if/#endif pair. All header file references to the 189- * WINAPI_PARTITION_* values should be in the form of occurrences of 190- * WINAPI_FAMILY_PARTITION(...). 191- * 192- * For example, the following usage of WINAPI_FAMILY_PARTITION identifies 193- * a sequence of declarations that are part of both the Windows Desktop 194- * Partition and the Windows-Phone-Specific Store Partition: 195- * 196- * #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_PHONE_APP) 197- * ... 198- * #endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_PHONE_APP) 199- * 200- * The comment on the closing #endif allow tools as well as people to find the 201- * matching #ifdef properly. 202- * 203- * Usages of WINAPI_FAMILY_PARTITION may be combined, when the partitition definitions are 204- * related. In particular one might use declarations like 205- * 206- * #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) 207- * 208- * or 209- * 210- * #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) 211- * 212- * Direct references to WINAPI_PARTITION_ values (eg #if !WINAPI_FAMILY_PARTITION_...) 213- * should not be used. 214- */ 215-#define WINAPI_FAMILY_PARTITION(Partitions) (Partitions) 216- 217-/* 218- * Macro used to #define or typedef a symbol used for selective deprecation 219- * of individual methods of a COM interfaces that are otherwise available 220- * for a given set of partitions. 221- */ 222-#define _WINAPI_DEPRECATED_DECLARATION __declspec(deprecated("This API cannot be used in the context of the caller's application type.")) 223- 224-/* 225- * For compatibility with Windows 8 header files, the following 226- * symbol is temporarily conditionally #define'd. Additional symbols 227- * like this should be not defined in winapifamily.h, but rather should be 228- * introduced locally to the header files of the component that needs them. 229- */ 230-#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) 231-# define APP_DEPRECATED_HRESULT HRESULT _WINAPI_DEPRECATED_DECLARATION 232-#endif // WINAPIFAMILY_PARTITION(WINAPI_PARTITION_APP) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) 233- 234-#if defined(_MSC_VER) && !defined(MOFCOMP_PASS) 235-#if _MSC_VER >= 1200 236-#pragma warning(pop) 237-#endif 238-#endif 239- 240-#endif /* !_INC_WINAPIFAMILY */ --- exewrap/trunk/exewrap/src/minhook/WindowsSDK/include/winpackagefamily.h (revision 38) +++ exewrap/trunk/exewrap/src/minhook/WindowsSDK/include/winpackagefamily.h (nonexistent) @@ -1,91 +0,0 @@ 1-/* 2- 3-Copyright (c) Microsoft Corporation. All rights reserved. 4- 5-Module Name: 6- 7- winpackagefamily.h 8- 9-Abstract: 10- 11- API family partitioning based on packages. 12- 13-*/ 14- 15-#ifndef _INC_WINPACKAGEFAMILY 16-#define _INC_WINPACKAGEFAMILY 17- 18-#if defined(_MSC_VER) && !defined(MOFCOMP_PASS) 19-#if _MSC_VER >= 1200 20-#pragma warning(push) 21-#pragma warning(disable:4001) /* nonstandard extension 'single line comment' was used */ 22-#endif 23-#pragma once 24-#endif // defined(_MSC_VER) && !defined(MOFCOMP_PASS) 25- 26-#ifndef WINAPI_PARTITION_SERVER 27-#define WINAPI_PARTITION_SERVER (WINAPI_FAMILY == WINAPI_FAMILY_SERVER) 28-#endif 29- 30-/* 31- * PARTITIONS based on packages are each #undef'ed below, and then will be #define-ed 32- * to be either 1 or 0 or depending on the active WINAPI_FAMILY. 33- */ 34-#undef WINAPI_PARTITION_PKG_WINTRUST 35-#undef WINAPI_PARTITION_PKG_WEBSERVICES 36-#undef WINAPI_PARTITION_PKG_EVENTLOGSERVICE 37-#undef WINAPI_PARTITION_PKG_VHD 38-#undef WINAPI_PARTITION_PKG_PERFCOUNTER 39-#undef WINAPI_PARTITION_PKG_SECURESTARTUP 40-#undef WINAPI_PARTITION_PKG_REMOTEFS 41-#undef WINAPI_PARTITION_PKG_BOOTABLESKU 42-#undef WINAPI_PARTITION_PKG_CMDTOOLS 43-#undef WINAPI_PARTITION_PKG_DISM 44-#undef WINAPI_PARTITION_PKG_CORESETUP 45-#undef WINAPI_PARTITION_PKG_APPRUNTIME 46-#undef WINAPI_PARTITION_PKG_ESENT 47-#undef WINAPI_PARTITION_PKG_WINMGMT 48-#undef WINAPI_PARTITION_PKG_WNV 49-#undef WINAPI_PARTITION_PKG_CLUSTER 50-#undef WINAPI_PARTITION_PKG_VSS 51-#undef WINAPI_PARTITION_PKG_TRAFFIC 52-#undef WINAPI_PARTITION_PKG_ISCSI 53-#undef WINAPI_PARTITION_PKG_STORAGE 54-#undef WINAPI_PARTITION_PKG_MPSSVC 55-#undef WINAPI_PARTITION_PKG_APPXDEPLOYMENT 56-#undef WINAPI_PARTITION_PKG_WER 57- 58-/* 59- * PARTITIONS for feature packages. Each package might be active for one or more editions 60- */ 61-#define WINAPI_PARTITION_PKG_WINTRUST (WINAPI_PARTITION_SERVER == 1) 62-#define WINAPI_PARTITION_PKG_WEBSERVICES (WINAPI_PARTITION_SERVER == 1) 63-#define WINAPI_PARTITION_PKG_EVENTLOGSERVICE (WINAPI_PARTITION_SERVER == 1) 64-#define WINAPI_PARTITION_PKG_VHD (WINAPI_PARTITION_SERVER == 1) 65-#define WINAPI_PARTITION_PKG_PERFCOUNTER (WINAPI_PARTITION_SERVER == 1) 66-#define WINAPI_PARTITION_PKG_SECURESTARTUP (WINAPI_PARTITION_SERVER == 1) 67-#define WINAPI_PARTITION_PKG_REMOTEFS (WINAPI_PARTITION_SERVER == 1) 68-#define WINAPI_PARTITION_PKG_BOOTABLESKU (WINAPI_PARTITION_SERVER == 1) 69-#define WINAPI_PARTITION_PKG_CMDTOOLS (WINAPI_PARTITION_SERVER == 1) 70-#define WINAPI_PARTITION_PKG_DISM (WINAPI_PARTITION_SERVER == 1) 71-#define WINAPI_PARTITION_PKG_CORESETUP (WINAPI_PARTITION_SERVER == 1) 72-#define WINAPI_PARTITION_PKG_APPRUNTIME (WINAPI_PARTITION_SERVER == 1) 73-#define WINAPI_PARTITION_PKG_ESENT (WINAPI_PARTITION_SERVER == 1) 74-#define WINAPI_PARTITION_PKG_WINMGMT (WINAPI_PARTITION_SERVER == 1) 75-#define WINAPI_PARTITION_PKG_WNV (WINAPI_PARTITION_SERVER == 1) 76-#define WINAPI_PARTITION_PKG_CLUSTER (WINAPI_PARTITION_SERVER == 1) 77-#define WINAPI_PARTITION_PKG_VSS (WINAPI_PARTITION_SERVER == 1) 78-#define WINAPI_PARTITION_PKG_TRAFFIC (WINAPI_PARTITION_SERVER == 1) 79-#define WINAPI_PARTITION_PKG_ISCSI (WINAPI_PARTITION_SERVER == 1) 80-#define WINAPI_PARTITION_PKG_STORAGE (WINAPI_PARTITION_SERVER == 1) 81-#define WINAPI_PARTITION_PKG_MPSSVC (WINAPI_PARTITION_SERVER == 1) 82-#define WINAPI_PARTITION_PKG_APPXDEPLOYMENT (WINAPI_PARTITION_SERVER == 1) 83-#define WINAPI_PARTITION_PKG_WER (WINAPI_PARTITION_SERVER == 1) 84- 85-#if defined(_MSC_VER) && !defined(MOFCOMP_PASS) 86-#if _MSC_VER >= 1200 87-#pragma warning(pop) 88-#endif 89-#endif 90- 91-#endif /* !_INC_WINPACKAGEFAMILY */ --- exewrap/trunk/exewrap/src/minhook/WindowsSDK/include/TlHelp32.h (revision 38) +++ exewrap/trunk/exewrap/src/minhook/WindowsSDK/include/TlHelp32.h (nonexistent) @@ -1,325 +0,0 @@ 1-/*****************************************************************************\ 2-* * 3-* tlhelp32.h - WIN32 tool help functions, types, and definitions * 4-* * 5-* Version 1.0 * 6-* * 7-* NOTE: windows.h/winbase.h must be #included first * 8-* * 9-* Copyright (c) Microsoft Corp. All rights reserved. * 10-* * 11-\*****************************************************************************/ 12- 13-#ifndef _INC_TOOLHELP32 14-#define _INC_TOOLHELP32 15- 16-#if _MSC_VER > 1000 17-#pragma once 18-#endif 19-#include <winapifamily.h> 20- 21-#pragma region Desktop Family 22-#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) 23- 24- 25-#ifdef __cplusplus 26-extern "C" { /* Assume C declarations for C++ */ 27-#endif /* __cplusplus */ 28- 29-#define MAX_MODULE_NAME32 255 30- 31-/****** Shapshot function **********************************************/ 32- 33-HANDLE 34-WINAPI 35-CreateToolhelp32Snapshot( 36- DWORD dwFlags, 37- DWORD th32ProcessID 38- ); 39- 40-// 41-// The th32ProcessID argument is only used if TH32CS_SNAPHEAPLIST or 42-// TH32CS_SNAPMODULE is specified. th32ProcessID == 0 means the current 43-// process. 44-// 45-// NOTE that all of the snapshots are global except for the heap and module 46-// lists which are process specific. To enumerate the heap or module 47-// state for all WIN32 processes call with TH32CS_SNAPALL and the 48-// current process. Then for each process in the TH32CS_SNAPPROCESS 49-// list that isn't the current process, do a call with just 50-// TH32CS_SNAPHEAPLIST and/or TH32CS_SNAPMODULE. 51-// 52-// dwFlags 53-// 54-#define TH32CS_SNAPHEAPLIST 0x00000001 55-#define TH32CS_SNAPPROCESS 0x00000002 56-#define TH32CS_SNAPTHREAD 0x00000004 57-#define TH32CS_SNAPMODULE 0x00000008 58-#define TH32CS_SNAPMODULE32 0x00000010 59-#define TH32CS_SNAPALL (TH32CS_SNAPHEAPLIST | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD | TH32CS_SNAPMODULE) 60-#define TH32CS_INHERIT 0x80000000 61-// 62-// Use CloseHandle to destroy the snapshot 63-// 64- 65-/****** heap walking ***************************************************/ 66- 67-typedef struct tagHEAPLIST32 68-{ 69- SIZE_T dwSize; 70- DWORD th32ProcessID; // owning process 71- ULONG_PTR th32HeapID; // heap (in owning process's context!) 72- DWORD dwFlags; 73-} HEAPLIST32; 74-typedef HEAPLIST32 * PHEAPLIST32; 75-typedef HEAPLIST32 * LPHEAPLIST32; 76-// 77-// dwFlags 78-// 79-#define HF32_DEFAULT 1 // process's default heap 80-#define HF32_SHARED 2 // is shared heap 81- 82-BOOL 83-WINAPI 84-Heap32ListFirst( 85- HANDLE hSnapshot, 86- LPHEAPLIST32 lphl 87- ); 88- 89-BOOL 90-WINAPI 91-Heap32ListNext( 92- HANDLE hSnapshot, 93- LPHEAPLIST32 lphl 94- ); 95- 96-typedef struct tagHEAPENTRY32 97-{ 98- SIZE_T dwSize; 99- HANDLE hHandle; // Handle of this heap block 100- ULONG_PTR dwAddress; // Linear address of start of block 101- SIZE_T dwBlockSize; // Size of block in bytes 102- DWORD dwFlags; 103- DWORD dwLockCount; 104- DWORD dwResvd; 105- DWORD th32ProcessID; // owning process 106- ULONG_PTR th32HeapID; // heap block is in 107-} HEAPENTRY32; 108-typedef HEAPENTRY32 * PHEAPENTRY32; 109-typedef HEAPENTRY32 * LPHEAPENTRY32; 110-// 111-// dwFlags 112-// 113-#define LF32_FIXED 0x00000001 114-#define LF32_FREE 0x00000002 115-#define LF32_MOVEABLE 0x00000004 116- 117-BOOL 118-WINAPI 119-Heap32First( 120- LPHEAPENTRY32 lphe, 121- DWORD th32ProcessID, 122- ULONG_PTR th32HeapID 123- ); 124- 125-BOOL 126-WINAPI 127-Heap32Next( 128- LPHEAPENTRY32 lphe 129- ); 130- 131-BOOL 132-WINAPI 133-Toolhelp32ReadProcessMemory( 134- DWORD th32ProcessID, 135- LPCVOID lpBaseAddress, 136- LPVOID lpBuffer, 137- SIZE_T cbRead, 138- SIZE_T *lpNumberOfBytesRead 139- ); 140- 141-/***** Process walking *************************************************/ 142- 143-typedef struct tagPROCESSENTRY32W 144-{ 145- DWORD dwSize; 146- DWORD cntUsage; 147- DWORD th32ProcessID; // this process 148- ULONG_PTR th32DefaultHeapID; 149- DWORD th32ModuleID; // associated exe 150- DWORD cntThreads; 151- DWORD th32ParentProcessID; // this process's parent process 152- LONG pcPriClassBase; // Base priority of process's threads 153- DWORD dwFlags; 154- WCHAR szExeFile[MAX_PATH]; // Path 155-} PROCESSENTRY32W; 156-typedef PROCESSENTRY32W * PPROCESSENTRY32W; 157-typedef PROCESSENTRY32W * LPPROCESSENTRY32W; 158- 159-BOOL 160-WINAPI 161-Process32FirstW( 162- HANDLE hSnapshot, 163- LPPROCESSENTRY32W lppe 164- ); 165- 166-BOOL 167-WINAPI 168-Process32NextW( 169- HANDLE hSnapshot, 170- LPPROCESSENTRY32W lppe 171- ); 172- 173-typedef struct tagPROCESSENTRY32 174-{ 175- DWORD dwSize; 176- DWORD cntUsage; 177- DWORD th32ProcessID; // this process 178- ULONG_PTR th32DefaultHeapID; 179- DWORD th32ModuleID; // associated exe 180- DWORD cntThreads; 181- DWORD th32ParentProcessID; // this process's parent process 182- LONG pcPriClassBase; // Base priority of process's threads 183- DWORD dwFlags; 184- CHAR szExeFile[MAX_PATH]; // Path 185-} PROCESSENTRY32; 186-typedef PROCESSENTRY32 * PPROCESSENTRY32; 187-typedef PROCESSENTRY32 * LPPROCESSENTRY32; 188- 189-BOOL 190-WINAPI 191-Process32First( 192- HANDLE hSnapshot, 193- LPPROCESSENTRY32 lppe 194- ); 195- 196-BOOL 197-WINAPI 198-Process32Next( 199- HANDLE hSnapshot, 200- LPPROCESSENTRY32 lppe 201- ); 202- 203-#ifdef UNICODE 204-#define Process32First Process32FirstW 205-#define Process32Next Process32NextW 206-#define PROCESSENTRY32 PROCESSENTRY32W 207-#define PPROCESSENTRY32 PPROCESSENTRY32W 208-#define LPPROCESSENTRY32 LPPROCESSENTRY32W 209-#endif // !UNICODE 210- 211-/***** Thread walking **************************************************/ 212- 213-typedef struct tagTHREADENTRY32 214-{ 215- DWORD dwSize; 216- DWORD cntUsage; 217- DWORD th32ThreadID; // this thread 218- DWORD th32OwnerProcessID; // Process this thread is associated with 219- LONG tpBasePri; 220- LONG tpDeltaPri; 221- DWORD dwFlags; 222-} THREADENTRY32; 223-typedef THREADENTRY32 * PTHREADENTRY32; 224-typedef THREADENTRY32 * LPTHREADENTRY32; 225- 226-BOOL 227-WINAPI 228-Thread32First( 229- HANDLE hSnapshot, 230- LPTHREADENTRY32 lpte 231- ); 232- 233-BOOL 234-WINAPI 235-Thread32Next( 236- HANDLE hSnapshot, 237- LPTHREADENTRY32 lpte 238- ); 239- 240-/***** Module walking *************************************************/ 241- 242-typedef struct tagMODULEENTRY32W 243-{ 244- DWORD dwSize; 245- DWORD th32ModuleID; // This module 246- DWORD th32ProcessID; // owning process 247- DWORD GlblcntUsage; // Global usage count on the module 248- DWORD ProccntUsage; // Module usage count in th32ProcessID's context 249- BYTE * modBaseAddr; // Base address of module in th32ProcessID's context 250- DWORD modBaseSize; // Size in bytes of module starting at modBaseAddr 251- HMODULE hModule; // The hModule of this module in th32ProcessID's context 252- WCHAR szModule[MAX_MODULE_NAME32 + 1]; 253- WCHAR szExePath[MAX_PATH]; 254-} MODULEENTRY32W; 255-typedef MODULEENTRY32W * PMODULEENTRY32W; 256-typedef MODULEENTRY32W * LPMODULEENTRY32W; 257- 258-BOOL 259-WINAPI 260-Module32FirstW( 261- HANDLE hSnapshot, 262- LPMODULEENTRY32W lpme 263- ); 264- 265-BOOL 266-WINAPI 267-Module32NextW( 268- HANDLE hSnapshot, 269- LPMODULEENTRY32W lpme 270- ); 271- 272- 273-typedef struct tagMODULEENTRY32 274-{ 275- DWORD dwSize; 276- DWORD th32ModuleID; // This module 277- DWORD th32ProcessID; // owning process 278- DWORD GlblcntUsage; // Global usage count on the module 279- DWORD ProccntUsage; // Module usage count in th32ProcessID's context 280- BYTE * modBaseAddr; // Base address of module in th32ProcessID's context 281- DWORD modBaseSize; // Size in bytes of module starting at modBaseAddr 282- HMODULE hModule; // The hModule of this module in th32ProcessID's context 283- char szModule[MAX_MODULE_NAME32 + 1]; 284- char szExePath[MAX_PATH]; 285-} MODULEENTRY32; 286-typedef MODULEENTRY32 * PMODULEENTRY32; 287-typedef MODULEENTRY32 * LPMODULEENTRY32; 288- 289-// 290-// NOTE CAREFULLY that the modBaseAddr and hModule fields are valid ONLY 291-// in th32ProcessID's process context. 292-// 293- 294-BOOL 295-WINAPI 296-Module32First( 297- HANDLE hSnapshot, 298- LPMODULEENTRY32 lpme 299- ); 300- 301-BOOL 302-WINAPI 303-Module32Next( 304- HANDLE hSnapshot, 305- LPMODULEENTRY32 lpme 306- ); 307- 308-#ifdef UNICODE 309-#define Module32First Module32FirstW 310-#define Module32Next Module32NextW 311-#define MODULEENTRY32 MODULEENTRY32W 312-#define PMODULEENTRY32 PMODULEENTRY32W 313-#define LPMODULEENTRY32 LPMODULEENTRY32W 314-#endif // !UNICODE 315- 316- 317-#ifdef __cplusplus 318-} 319-#endif 320- 321- 322-#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */ 323-#pragma endregion 324- 325-#endif // _INC_TOOLHELP32 --- exewrap/trunk/exewrap/src/minhook/README.md (revision 38) +++ exewrap/trunk/exewrap/src/minhook/README.md (nonexistent) @@ -1,72 +0,0 @@ 1-# MinHook 2- 3-The Minimalistic x86/x64 API Hooking Library for Windows 4- 5-http://www.codeproject.com/KB/winsdk/LibMinHook.aspx 6- 7-### Donation please 8- 9-Need some funds to continue developing this library. All contributions gratefully accepted. 10- 11-<a href='https://pledgie.com/campaigns/27314'><img alt='Click here to lend your support to: MinHook - Help me continue to develop this library and make a donation at pledgie.com !' src='https://pledgie.com/campaigns/27314.png?skin_name=chrome' border='0' ></a> 12- 13-### Version history 14- 15-- ####v1.3.2-beta3 16- * Support MinGW. (Experimental) 17- 18-- ####v1.3.2-beta2 - 18 May 2015 19- * Fixed some subtle bugs. (Thanks to RaMMicHaeL) 20- * Added a helper function ```MH_StatusToString```. (Thanks to Jan Klass) 21- 22-- ####v1.3.2-beta - 12 May 2015 23- * Fixed a possible thread deadlock in x64 mode. (Thanks to Aleh Kazakevich) 24- * Reduced the footprint a little more. 25- * Support Visual Studio 2015 RC. (Experimental) 26- 27-- ####v1.3.1 - 19 Mar 2015 28- * No major changes from v1.3.1-beta. 29- 30-- ####v1.3.1-beta - 11 Mar 2015 31- * Added a helper function ```MH_CreateHookApi```. (Thanks to uniskz). 32- * Fixed a false memory leak reported by some tools. 33- * Fixed a degradated compatibility issue. 34- 35-- ####v1.3 - 13 Sep 2014 36- * No major changes from v1.3-beta3. 37- 38-- ####v1.3-beta3 - 31 Jul 2014 39- 40- * Fixed some small bugs. 41- * Improved the memory management. 42- 43-- ####v1.3-beta2 - 21 Jul 2014 44- 45- * Changed the parameters to Windows-friendly types. (void* to LPVOID) 46- * Fixed some small bugs. 47- * Reorganized the source files. 48- * Reduced the footprint a little more. 49- 50-- ####v1.3-beta - 17 Jul 2014 51- 52- * Rewrote in plain C to reduce the footprint and memory usage. (suggested by Andrey Unis) 53- * Simplified the overall code base to make it more readable and maintainable. 54- * Changed the license from 3-clause to 2-clause BSD License. 55- 56-- ####v1.2 - 28 Sep 2013 57- 58- * Removed boost dependency ([jarredholman](https://github.com/jarredholman/minhook)). 59- * Fixed a small bug in the GetRelativeBranchDestination function ([pillbug99](http://www.codeproject.com/Messages/4058892/Small-Bug-Found.aspx)). 60- * Added the ```MH_RemoveHook``` function, which removes a hook created with the ```MH_CreateHook``` function. 61- * Added the following functions to enable or disable multiple hooks in one go: ```MH_QueueEnableHook```, ```MH_QueueDisableHook```, ```MH_ApplyQueued```. This is the preferred way of handling multiple hooks as every call to `MH_EnableHook` or `MH_DisableHook` suspends and resumes all threads. 62- * Made the functions ```MH_EnableHook``` and ```MH_DisableHook``` enable/disable all created hooks when the ```MH_ALL_HOOKS``` parameter is passed. This, too, is an efficient way of handling multiple hooks. 63- * If the target function is too small to be patched with a jump, MinHook tries to place the jump above the function. If that fails as well, the ```MH_CreateHook``` function returns ```MH_ERROR_UNSUPPORTED_FUNCTION```. This fixes an issue of hooking the LoadLibraryExW function on Windows 7 x64 ([reported by Obble](http://www.codeproject.com/Messages/4578613/Re-Bug-LoadLibraryExW-hook-fails-on-windows-2008-r.aspx)). 64- 65-- ####v1.1 - 26 Nov 2009 66- 67- * Changed the interface to create a hook and a trampoline function in one go to prevent the detour function from being called before the trampoline function is created. ([reported by xliqz](http://www.codeproject.com/Messages/3280374/Unsafe.aspx)) 68- * Shortened the function names from ```MinHook_*``` to ```MH_*``` to make them handier. 69- 70-- ####v1.0 - 22 Nov 2009 71- 72- * Initial release. --- exewrap/trunk/exewrap/src/minhook/LICENSE.txt (revision 38) +++ exewrap/trunk/exewrap/src/minhook/LICENSE.txt (nonexistent) @@ -1,81 +0,0 @@ 1-MinHook - The Minimalistic API Hooking Library for x64/x86 2-Copyright (C) 2009-2015 Tsuda Kageyu. 3-All rights reserved. 4- 5-Redistribution and use in source and binary forms, with or without 6-modification, are permitted provided that the following conditions 7-are met: 8- 9- 1. Redistributions of source code must retain the above copyright 10- notice, this list of conditions and the following disclaimer. 11- 2. Redistributions in binary form must reproduce the above copyright 12- notice, this list of conditions and the following disclaimer in the 13- documentation and/or other materials provided with the distribution. 14- 15-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 16-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 17-TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 18-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 19-OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20-EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21-PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 23-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 24-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26- 27-================================================================================ 28-Portions of this software are Copyright (c) 2008-2009, Vyacheslav Patkov. 29-================================================================================ 30-Hacker Disassembler Engine 32 C 31-Copyright (c) 2008-2009, Vyacheslav Patkov. 32-All rights reserved. 33- 34-Redistribution and use in source and binary forms, with or without 35-modification, are permitted provided that the following conditions 36-are met: 37- 38- 1. Redistributions of source code must retain the above copyright 39- notice, this list of conditions and the following disclaimer. 40- 2. Redistributions in binary form must reproduce the above copyright 41- notice, this list of conditions and the following disclaimer in the 42- documentation and/or other materials provided with the distribution. 43- 44-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 45-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 46-TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 47-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR 48-CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 49-EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 50-PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 51-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 52-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 53-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 54-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 55- 56-------------------------------------------------------------------------------- 57-Hacker Disassembler Engine 64 C 58-Copyright (c) 2008-2009, Vyacheslav Patkov. 59-All rights reserved. 60- 61-Redistribution and use in source and binary forms, with or without 62-modification, are permitted provided that the following conditions 63-are met: 64- 65- 1. Redistributions of source code must retain the above copyright 66- notice, this list of conditions and the following disclaimer. 67- 2. Redistributions in binary form must reproduce the above copyright 68- notice, this list of conditions and the following disclaimer in the 69- documentation and/or other materials provided with the distribution. 70- 71-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 72-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 73-TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 74-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR 75-CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 76-EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 77-PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 78-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 79-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 80-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 81-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --- exewrap/trunk/exewrap/src/trace.c (revision 38) +++ exewrap/trunk/exewrap/src/trace.c (nonexistent) @@ -1,423 +0,0 @@ 1-#define _CRT_SECURE_NO_WARNINGS 2- 3-#include <Windows.h> 4-#include <stdio.h> 5-#include <string.h> 6-#include "minhook\include\MinHook.h" 7- 8-#define BUFFER_SIZE 1024 9- 10-const char* StartTrace(); 11-void StopTrace(); 12- 13-static char* _w2a(LPCWSTR s); 14- 15-static char* filename1 = NULL; 16-static char* filename2 = NULL; 17-static HANDLE hStdOut = NULL; 18-static FILE* fpStdOut = NULL; 19-static FILE* fp = NULL; 20- 21-typedef HANDLE(WINAPI *CREATEFILEA)(LPCSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); 22-typedef HANDLE(WINAPI *CREATEFILEW)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); 23-typedef HMODULE(WINAPI *LOADLIBRARYA)(LPCSTR); 24-typedef HMODULE(WINAPI *LOADLIBRARYW)(LPCWSTR); 25-typedef HMODULE(WINAPI *LOADLIBRARYEXA)(LPCSTR, HANDLE, DWORD); 26-typedef HMODULE(WINAPI *LOADLIBRARYEXW)(LPCWSTR, HANDLE, DWORD); 27- 28-CREATEFILEA fpCreateFileA = NULL; 29-CREATEFILEW fpCreateFileW = NULL; 30-LOADLIBRARYA fpLoadLibraryA = NULL; 31-LOADLIBRARYW fpLoadLibraryW = NULL; 32-LOADLIBRARYEXA fpLoadLibraryExA = NULL; 33-LOADLIBRARYEXW fpLoadLibraryExW = NULL; 34- 35-HANDLE WINAPI DetourCreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); 36-HANDLE WINAPI DetourCreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); 37-HMODULE WINAPI DetourLoadLibraryA(LPCSTR lpLibFileName); 38-HMODULE WINAPI DetourLoadLibraryW(LPCWSTR lpLibFileName); 39-HMODULE WINAPI DetourLoadLibraryExA(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); 40-HMODULE WINAPI DetourLoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); 41- 42-static void print(LPCSTR type, LPCSTR full_path_name); 43-static LPSTR is_file_in_JRE(LPCSTR lpFileName); 44- 45-const char* StartTrace(BOOL replace_stdout) 46-{ 47- BOOL succeeded = FALSE; 48- 49- filename1 = (char*)malloc(1024); 50- GetModuleFileName(NULL, filename1, 1024); 51- *strrchr(filename1, '.') = '\0'; 52- strcat(filename1, ".log"); 53- 54- if (replace_stdout) 55- { 56- hStdOut = CreateFile(filename1, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 57- if (hStdOut == INVALID_HANDLE_VALUE) 58- { 59- goto EXIT; 60- } 61- 62- fpStdOut = freopen(filename1, "wb", stdout); 63- if (fpStdOut == NULL) 64- { 65- goto EXIT; 66- } 67- } 68- else 69- { 70- filename2 = (char*)malloc(1024); 71- strcpy(filename2, filename1); 72- *strrchr(filename2, '.') = '\0'; 73- strcat(filename2, "2.log"); 74- fp = fopen(filename2, "wb"); 75- } 76- 77- if (MH_Initialize() != MH_OK) 78- { 79- goto EXIT; 80- } 81- 82- if (MH_CreateHook(&CreateFileA, &DetourCreateFileA, (LPVOID*)(&fpCreateFileA)) != MH_OK) 83- { 84- goto EXIT; 85- } 86- if (MH_EnableHook(&CreateFileA) != MH_OK) 87- { 88- goto EXIT; 89- } 90- 91- if (MH_CreateHook(&CreateFileW, &DetourCreateFileW, (LPVOID*)(&fpCreateFileW)) != MH_OK) 92- { 93- goto EXIT; 94- } 95- if (MH_EnableHook(&CreateFileW) != MH_OK) 96- { 97- goto EXIT; 98- } 99- 100- if (MH_CreateHook(&LoadLibraryA, &DetourLoadLibraryA, (LPVOID*)(&fpLoadLibraryA)) != MH_OK) 101- { 102- goto EXIT; 103- } 104- if (MH_EnableHook(&LoadLibraryA) != MH_OK) 105- { 106- goto EXIT; 107- } 108- 109- if (MH_CreateHook(&LoadLibraryW, &DetourLoadLibraryW, (LPVOID*)(&fpLoadLibraryW)) != MH_OK) 110- { 111- goto EXIT; 112- } 113- if (MH_EnableHook(&LoadLibraryW) != MH_OK) 114- { 115- goto EXIT; 116- } 117- 118- if (MH_CreateHook(&LoadLibraryExA, &DetourLoadLibraryExA, (LPVOID*)(&fpLoadLibraryExA)) != MH_OK) 119- { 120- goto EXIT; 121- } 122- if (MH_EnableHook(&LoadLibraryExA) != MH_OK) 123- { 124- goto EXIT; 125- } 126- 127- if (MH_CreateHook(&LoadLibraryExW, &DetourLoadLibraryExW, (LPVOID*)(&fpLoadLibraryExW)) != MH_OK) 128- { 129- goto EXIT; 130- } 131- if (MH_EnableHook(&LoadLibraryExW) != MH_OK) 132- { 133- goto EXIT; 134- } 135- 136- succeeded = TRUE; 137- 138-EXIT: 139- if (!succeeded) 140- { 141- free(filename1); 142- filename1 = NULL; 143- } 144- return filename1; 145-} 146- 147- 148-void StopTrace() 149-{ 150- if (MH_DisableHook(&LoadLibraryW) != MH_OK) 151- { 152- } 153- 154- if (MH_DisableHook(&CreateFileW) != MH_OK) 155- { 156- } 157- 158- if (MH_Uninitialize() != MH_OK) 159- { 160- } 161- 162- if (hStdOut != NULL && hStdOut != INVALID_HANDLE_VALUE) 163- { 164- FlushFileBuffers(hStdOut); 165- CloseHandle(hStdOut); 166- } 167- hStdOut = NULL; 168- 169- if (fpStdOut != NULL) 170- { 171- fflush(fpStdOut); 172- fclose(fpStdOut); 173- } 174- fpStdOut = NULL; 175- 176- if (fp != NULL) 177- { 178- fclose(fp); 179- } 180- fp = NULL; 181- 182- if (filename2 != NULL) 183- { 184- free(filename2); 185- } 186- 187- if (filename1 != NULL) 188- { 189- free(filename1); 190- } 191-} 192- 193- 194-static void print(LPCSTR type, LPCSTR full_path_name) 195-{ 196- if (fpStdOut != NULL) 197- { 198- printf("[%s %s]\n", type, full_path_name); 199- fflush(stdout); 200- } 201- else if (fp != NULL) 202- { 203- fprintf(fp, "[%s %s]\n", type, full_path_name); 204- fflush(fp); 205- } 206-} 207- 208- 209-static LPSTR is_file_in_JRE(LPCSTR lpFileName) 210-{ 211- BOOL b = FALSE; 212- LPSTR buf = NULL; 213- LPSTR java_home = NULL; 214- LPSTR full_path_name = NULL; 215- DWORD size1; 216- DWORD size2; 217- LPSTR ptr; 218- 219- buf = (LPSTR)malloc(BUFFER_SIZE); 220- size1 = GetEnvironmentVariableA("JAVA_HOME", buf, BUFFER_SIZE); 221- if (size1 > 0) 222- { 223- java_home = (LPSTR)malloc(BUFFER_SIZE); 224- size1 = GetFullPathNameA(buf, BUFFER_SIZE, java_home, &ptr); 225- if (size1 > 0) 226- { 227- full_path_name = (LPSTR)malloc(BUFFER_SIZE); 228- size2 = GetFullPathNameA(lpFileName, BUFFER_SIZE, full_path_name, &ptr); 229- if (size2 > 0) 230- { 231- if (_memicmp(java_home, full_path_name, size1) == 0) 232- { 233- b = TRUE; 234- } 235- } 236- } 237- } 238- 239- if (buf != NULL) 240- { 241- free(buf); 242- } 243- if (java_home != NULL) 244- { 245- free(java_home); 246- } 247- if (!b && full_path_name != NULL) 248- { 249- free(full_path_name); 250- full_path_name = NULL; 251- } 252- return full_path_name; 253-} 254- 255- 256-HANDLE WINAPI DetourCreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) 257-{ 258- LPSTR full_path_name; 259- 260- full_path_name = is_file_in_JRE(lpFileName); 261- if (full_path_name != NULL) 262- { 263- print("CreateFile", full_path_name); 264- free(full_path_name); 265- } 266- 267- return fpCreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); 268-} 269- 270- 271-HANDLE WINAPI DetourCreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) 272-{ 273- LPSTR lpFileNameA = _w2a(lpFileName); 274- LPSTR full_path_name; 275- 276- full_path_name = is_file_in_JRE(lpFileNameA); 277- if (full_path_name != NULL) 278- { 279- print("CreateFile", full_path_name); 280- free(full_path_name); 281- } 282- free(lpFileNameA); 283- 284- return fpCreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); 285-} 286- 287- 288-HMODULE WINAPI DetourLoadLibraryA(LPCSTR lpLibFileName) 289-{ 290- HMODULE hModule; 291- LPSTR buf = (LPSTR)malloc(BUFFER_SIZE); 292- LPSTR full_path_name = NULL; 293- 294- hModule = fpLoadLibraryA(lpLibFileName); 295- if (hModule != NULL) 296- { 297- if (GetModuleFileNameA(hModule, buf, BUFFER_SIZE) > 0) 298- { 299- full_path_name = is_file_in_JRE(buf); 300- if (full_path_name != NULL) 301- { 302- print("LoadLibrary", full_path_name); 303- } 304- } 305- } 306- 307- if (full_path_name != NULL) 308- { 309- free(full_path_name); 310- } 311- free(buf); 312- 313- return hModule; 314-} 315- 316- 317-HMODULE WINAPI DetourLoadLibraryW(LPCWSTR lpLibFileName) 318-{ 319- HMODULE hModule; 320- LPSTR buf = (LPSTR)malloc(BUFFER_SIZE); 321- LPSTR full_path_name = NULL; 322- 323- hModule = fpLoadLibraryW(lpLibFileName); 324- if (hModule != NULL) 325- { 326- if (GetModuleFileName(hModule, buf, BUFFER_SIZE) > 0) 327- { 328- full_path_name = is_file_in_JRE(buf); 329- if (full_path_name != NULL) 330- { 331- print("LoadLibrary", full_path_name); 332- } 333- } 334- } 335- 336- if (full_path_name != NULL) 337- { 338- free(full_path_name); 339- } 340- free(buf); 341- 342- return hModule; 343-} 344- 345- 346-HMODULE WINAPI DetourLoadLibraryExA(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) 347-{ 348- HMODULE hModule; 349- LPSTR buf = (LPSTR)malloc(BUFFER_SIZE); 350- LPSTR full_path_name = NULL; 351- 352- hModule = fpLoadLibraryExA(lpLibFileName, hFile, dwFlags); 353- if (hModule != NULL) 354- { 355- if (GetModuleFileNameA(hModule, buf, BUFFER_SIZE) > 0) 356- { 357- full_path_name = is_file_in_JRE(buf); 358- if (full_path_name != NULL) 359- { 360- print("LoadLibrary", full_path_name); 361- } 362- } 363- } 364- 365- if (full_path_name != NULL) 366- { 367- free(full_path_name); 368- } 369- free(buf); 370- 371- return hModule; 372-} 373- 374- 375-HMODULE WINAPI DetourLoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) 376-{ 377- HMODULE hModule; 378- LPSTR buf = (LPSTR)malloc(BUFFER_SIZE); 379- LPSTR full_path_name = NULL; 380- 381- hModule = fpLoadLibraryExW(lpLibFileName, hFile, dwFlags); 382- if (hModule != NULL) 383- { 384- if (GetModuleFileNameA(hModule, buf, BUFFER_SIZE) > 0) 385- { 386- full_path_name = is_file_in_JRE(buf); 387- if (full_path_name != NULL) 388- { 389- print("LoadLibrary", full_path_name); 390- } 391- } 392- } 393- 394- if (full_path_name != NULL) 395- { 396- free(full_path_name); 397- } 398- free(buf); 399- 400- return hModule; 401-} 402- 403-static char* _w2a(LPCWSTR s) 404-{ 405- char* buf; 406- int ret; 407- 408- ret = WideCharToMultiByte(CP_ACP, 0, s, -1, NULL, 0, NULL, NULL); 409- if (ret <= 0) 410- { 411- return NULL; 412- } 413- buf = (LPSTR)malloc(ret + 1); 414- ret = WideCharToMultiByte(CP_ACP, 0, s, -1, buf, (ret + 1), NULL, NULL); 415- if (ret == 0) 416- { 417- free(buf); 418- return NULL; 419- } 420- buf[ret] = '\0'; 421- 422- return buf; 423-} --- exewrap/trunk/exewrap/src/Makefile (revision 38) +++ exewrap/trunk/exewrap/src/Makefile (revision 39) @@ -47,15 +47,6 @@ 4747 IMAGE_X86 : $(OBJ)\image_console.exe $(OBJ)\image_gui.exe $(OBJ)\image_service.exe 4848 IMAGE_X64 : $(OBJ)\image_console.exe $(OBJ)\image_gui.exe $(OBJ)\image_service.exe 4949 50-TRACE_EXEWRAP_X86 : $(BIN)\exewrap-trace.exe 51-TRACE_EXEWRAP_X64 : $(BIN)\exewrap-trace.exe 52- 53-TRACE_IMAGE_X86 : $(OBJ)\image_console_trace.exe $(OBJ)\image_gui_trace.exe $(OBJ)\image_service_trace.exe 54-TRACE_IMAGE_X64 : $(OBJ)\image_console_trace.exe $(OBJ)\image_gui_trace.exe $(OBJ)\image_service_trace.exe 55- 56-JREMIN_X86 : $(BIN)\jremin.exe 57-JREMIN_X64 : $(BIN)\jremin.exe 58- 5950 CLEAN : 6051 @if exist $(OBJ)\..\x86 RMDIR /S /Q $(OBJ)\..\x86 6152 @if exist $(OBJ)\..\x64 RMDIR /S /Q $(OBJ)\..\x64 @@ -65,53 +56,28 @@ 6556 6657 $(OBJ) : 6758 @if not exist $(OBJ)/$(NULL) mkdir $(OBJ) 59+ 60+$(OBJ)\exewrap-tool : 61+ @if not exist $(OBJ)\exewrap-tool/$(NULL) mkdir $(OBJ)\exewrap-tool 6862 6963 $(BIN)\exewrap.exe : $(BIN) $(OBJ) $(OBJ)\exewrap.res $(OBJ)\exewrap.obj \ 7064 $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\eventlog.obj \ 7165 $(OBJ)\image_console.exe $(OBJ)\image_gui.exe $(OBJ)\image_service.exe \ 72- $(OBJ)\bindres.exe $(OBJ)\exewrap\core\ByteBufferInputStream.class $(OBJ)\exewrap\core\ExewrapClassLoader.class $(OBJ)\tool.jar 73- $(LINK) $(LDFLAGS) /SUBSYSTEM:CONSOLE$(TARGET_VER) /MANIFEST /MANIFESTFILE:$(OBJ)\exewrap\exewrap.exe.manifest /OUT:$(BIN)\exewrap.exe $(OBJ)\exewrap.res $(OBJ)\exewrap.obj \ 66+ $(OBJ)\bindres.exe $(OBJ)\core.jar $(OBJ)\tool.jar 67+ $(LINK) $(LDFLAGS) /SUBSYSTEM:CONSOLE$(TARGET_VER) /MANIFEST /MANIFESTFILE:$(OBJ)\exewrap.exe.manifest /OUT:$(OBJ)\exewrap.exe $(OBJ)\exewrap.res $(OBJ)\exewrap.obj \ 7468 $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\eventlog.obj $(LIBS) $(MSVCRT_PATCH) 75- $(MT) -manifest $(OBJ)\exewrap\exewrap.exe.manifest -outputresource:$(BIN)\exewrap.exe;1 76- $(OBJ)\bindres.exe $(BIN)\exewrap.exe VERSION_INFO resources\versioninfo.bin 77- $(OBJ)\bindres.exe -r $(BIN)\exewrap.exe IMAGE_CONSOLE_32 $(OBJ)\..\x86\image_console.exe 78- $(OBJ)\bindres.exe -r $(BIN)\exewrap.exe IMAGE_CONSOLE_64 $(OBJ)\..\x64\image_console.exe 79- $(OBJ)\bindres.exe -r $(BIN)\exewrap.exe IMAGE_GUI_32 $(OBJ)\..\x86\image_gui.exe 80- $(OBJ)\bindres.exe -r $(BIN)\exewrap.exe IMAGE_GUI_64 $(OBJ)\..\x64\image_gui.exe 81- $(OBJ)\bindres.exe -r $(BIN)\exewrap.exe IMAGE_SERVICE_32 $(OBJ)\..\x86\image_service.exe 82- $(OBJ)\bindres.exe -r $(BIN)\exewrap.exe IMAGE_SERVICE_64 $(OBJ)\..\x64\image_service.exe 83- $(OBJ)\bindres.exe $(BIN)\exewrap.exe BYTE_BUFFER_INPUT_STREAM $(OBJ)\exewrap\core\ByteBufferInputStream.class 84- $(OBJ)\bindres.exe $(BIN)\exewrap.exe PACK_INPUT_STREAM $(OBJ)\exewrap\core\PackInputStream.class 85- $(OBJ)\bindres.exe $(BIN)\exewrap.exe URL_CONNECTION $(OBJ)\exewrap\core\URLConnection.class 86- $(OBJ)\bindres.exe $(BIN)\exewrap.exe URL_STREAM_HANDLER $(OBJ)\exewrap\core\URLStreamHandler.class 87- $(OBJ)\bindres.exe $(BIN)\exewrap.exe URL_STREAM_HANDLER_FACTORY $(OBJ)\exewrap\core\URLStreamHandlerFactory.class 88- $(OBJ)\bindres.exe $(BIN)\exewrap.exe EXEWRAP_CLASS_LOADER $(OBJ)\exewrap\core\ExewrapClassLoader.class 89- $(OBJ)\bindres.exe $(BIN)\exewrap.exe UTIL_JAR $(OBJ)\util.jar 90- $(OBJ)\bindres.exe $(BIN)\exewrap.exe JAR $(OBJ)\tool.jar 69+ $(MT) -manifest $(OBJ)\exewrap.exe.manifest -outputresource:$(BIN)\exewrap.exe;1 70+ $(OBJ)\bindres.exe $(OBJ)\exewrap.exe VERSION_INFO resources\versioninfo.bin 71+ $(OBJ)\bindres.exe -r $(OBJ)\exewrap.exe IMAGE_CONSOLE_32 $(OBJ)\..\x86\image_console.exe 72+ $(OBJ)\bindres.exe -r $(OBJ)\exewrap.exe IMAGE_CONSOLE_64 $(OBJ)\..\x64\image_console.exe 73+ $(OBJ)\bindres.exe -r $(OBJ)\exewrap.exe IMAGE_GUI_32 $(OBJ)\..\x86\image_gui.exe 74+ $(OBJ)\bindres.exe -r $(OBJ)\exewrap.exe IMAGE_GUI_64 $(OBJ)\..\x64\image_gui.exe 75+ $(OBJ)\bindres.exe -r $(OBJ)\exewrap.exe IMAGE_SERVICE_32 $(OBJ)\..\x86\image_service.exe 76+ $(OBJ)\bindres.exe -r $(OBJ)\exewrap.exe IMAGE_SERVICE_64 $(OBJ)\..\x64\image_service.exe 77+ $(OBJ)\bindres.exe $(OBJ)\exewrap.exe JAR $(OBJ)\tool.jar 78+ $(OBJ)\bindres.exe $(OBJ)\exewrap.exe CORE_JAR $(OBJ)\core.jar 79+ copy /V /Y /B $(OBJ)\exewrap.exe + $(OBJ)\core.jar $(BIN)\exewrap.exe 9180 92-$(BIN)\exewrap-trace.exe : $(BIN) $(OBJ) $(OBJ)\exewrap.res $(OBJ)\exewrap.obj \ 93- $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\eventlog.obj \ 94- $(OBJ)\image_console_trace.exe $(OBJ)\image_gui_trace.exe $(OBJ)\image_service_trace.exe \ 95- $(OBJ)\bindres.exe $(OBJ)\exewrap\core\ByteBufferInputStream.class $(OBJ)\exewrap\core\ExewrapClassLoader.class $(OBJ)\tool.jar 96- $(LINK) $(LDFLAGS) /SUBSYSTEM:CONSOLE$(TARGET_VER) /MANIFEST /MANIFESTFILE:$(OBJ)\exewrap\exewrap-trace.exe.manifest /OUT:$(BIN)\exewrap-trace.exe $(OBJ)\exewrap.res $(OBJ)\exewrap.obj \ 97- $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\eventlog.obj $(LIBS) $(MSVCRT_PATCH) 98- $(MT) -manifest $(OBJ)\exewrap\exewrap-trace.exe.manifest -outputresource:$(BIN)\exewrap-trace.exe;1 99- $(OBJ)\bindres.exe $(BIN)\exewrap-trace.exe VERSION_INFO resources\versioninfo.bin 100- $(OBJ)\bindres.exe -r $(BIN)\exewrap-trace.exe IMAGE_TRACE_CONSOLE_32 $(OBJ)\..\x86\image_console_trace.exe 101- $(OBJ)\bindres.exe -r $(BIN)\exewrap-trace.exe IMAGE_TRACE_CONSOLE_64 $(OBJ)\..\x64\image_console_trace.exe 102- $(OBJ)\bindres.exe -r $(BIN)\exewrap-trace.exe IMAGE_TRACE_GUI_32 $(OBJ)\..\x86\image_gui_trace.exe 103- $(OBJ)\bindres.exe -r $(BIN)\exewrap-trace.exe IMAGE_TRACE_GUI_64 $(OBJ)\..\x64\image_gui_trace.exe 104- $(OBJ)\bindres.exe -r $(BIN)\exewrap-trace.exe IMAGE_TRACE_SERVICE_32 $(OBJ)\..\x86\image_service_trace.exe 105- $(OBJ)\bindres.exe -r $(BIN)\exewrap-trace.exe IMAGE_TRACE_SERVICE_64 $(OBJ)\..\x64\image_service_trace.exe 106- $(OBJ)\bindres.exe $(BIN)\exewrap-trace.exe BYTE_BUFFER_INPUT_STREAM $(OBJ)\exewrap\core\ByteBufferInputStream.class 107- $(OBJ)\bindres.exe $(BIN)\exewrap-trace.exe PACK_INPUT_STREAM $(OBJ)\exewrap\core\PackInputStream.class 108- $(OBJ)\bindres.exe $(BIN)\exewrap-trace.exe URL_CONNECTION $(OBJ)\exewrap\core\URLConnection.class 109- $(OBJ)\bindres.exe $(BIN)\exewrap-trace.exe URL_STREAM_HANDLER $(OBJ)\exewrap\core\URLStreamHandler.class 110- $(OBJ)\bindres.exe $(BIN)\exewrap-trace.exe URL_STREAM_HANDLER_FACTORY $(OBJ)\exewrap\core\URLStreamHandlerFactory.class 111- $(OBJ)\bindres.exe $(BIN)\exewrap-trace.exe EXEWRAP_CLASS_LOADER $(OBJ)\exewrap\core\ExewrapClassLoader.class 112- $(OBJ)\bindres.exe $(BIN)\exewrap-trace.exe UTIL_JAR $(OBJ)\util.jar 113- $(OBJ)\bindres.exe $(BIN)\exewrap-trace.exe JAR $(OBJ)\tool.jar 114- 11581 $(OBJ)\exewrap.obj : $(OBJ) exewrap.c 11682 $(CC) $(CFLAGS) $(INC) /Fo$(OBJ)\exewrap.obj exewrap.c 11783 @@ -120,34 +86,11 @@ 12086 12187 $(OBJ)\image_console.exe : $(OBJ) $(OBJ)\image_console.res $(OBJ)\image_console.obj \ 12288 $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\notify.obj $(OBJ)\eventlog.obj \ 123- $(OBJ)\bindres.exe $(OBJ)\exewrap\core\ByteBufferInputStream.class $(OBJ)\exewrap\core\PackInputStream.class $(OBJ)\exewrap\core\ExewrapClassLoader.class $(OBJ)\exewrap\core\URLConnection.class $(OBJ)\exewrap\core\URLStreamHandler.class $(OBJ)\exewrap\core\URLStreamHandlerFactory.class $(OBJ)\util.jar 89+ $(OBJ)\bindres.exe $(OBJ)\core.jar 12490 $(LINK) $(LDFLAGS) /SUBSYSTEM:CONSOLE$(TARGET_VER) /MANIFEST /OUT:$(OBJ)\image_console.exe $(OBJ)\image_console.obj \ 12591 $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\notify.obj $(OBJ)\eventlog.obj $(LIBS) $(MSVCRT_PATCH) 12692 $(MT) -manifest $(OBJ)\image_console.exe.manifest -outputresource:$(OBJ)\image_console.exe;1 127- $(OBJ)\bindres.exe $(OBJ)\image_console.exe BYTE_BUFFER_INPUT_STREAM $(OBJ)\exewrap\core\ByteBufferInputStream.class 128- $(OBJ)\bindres.exe $(OBJ)\image_console.exe PACK_INPUT_STREAM $(OBJ)\exewrap\core\PackInputStream.class 129- $(OBJ)\bindres.exe $(OBJ)\image_console.exe URL_CONNECTION $(OBJ)\exewrap\core\URLConnection.class 130- $(OBJ)\bindres.exe $(OBJ)\image_console.exe URL_STREAM_HANDLER $(OBJ)\exewrap\core\URLStreamHandler.class 131- $(OBJ)\bindres.exe $(OBJ)\image_console.exe URL_STREAM_HANDLER_FACTORY $(OBJ)\exewrap\core\URLStreamHandlerFactory.class 132- $(OBJ)\bindres.exe $(OBJ)\image_console.exe EXEWRAP_CLASS_LOADER $(OBJ)\exewrap\core\ExewrapClassLoader.class 133- $(OBJ)\bindres.exe $(OBJ)\image_console.exe UTIL_JAR $(OBJ)\util.jar 13493 135-$(OBJ)\image_console_trace.exe : $(OBJ) $(OBJ)\image_console.res $(OBJ)\image_console_trace.obj $(OBJ)\trace.obj \ 136- $(OBJ)\buffer.obj $(OBJ)\hde$(BITS).obj $(OBJ)\hook.obj $(OBJ)\trampoline.obj \ 137- $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\notify.obj $(OBJ)\eventlog.obj \ 138- $(OBJ)\bindres.exe $(OBJ)\exewrap\core\ByteBufferInputStream.class $(OBJ)\exewrap\core\PackInputStream.class $(OBJ)\exewrap\core\ExewrapClassLoader.class $(OBJ)\exewrap\core\URLConnection.class $(OBJ)\exewrap\core\URLStreamHandler.class $(OBJ)\exewrap\core\URLStreamHandlerFactory.class $(OBJ)\util.jar 139- $(LINK) $(LDFLAGS) /SUBSYSTEM:CONSOLE$(TARGET_VER) /MANIFEST /OUT:$(OBJ)\image_console_trace.exe $(OBJ)\image_console_trace.obj $(OBJ)\trace.obj \ 140- $(OBJ)\buffer.obj $(OBJ)\hde$(BITS).obj $(OBJ)\hook.obj $(OBJ)\trampoline.obj \ 141- $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\notify.obj $(OBJ)\eventlog.obj $(LIBS) $(MSVCRT_PATCH) 142- $(MT) -manifest $(OBJ)\image_console_trace.exe.manifest -outputresource:$(OBJ)\image_console_trace.exe;1 143- $(OBJ)\bindres.exe $(OBJ)\image_console_trace.exe BYTE_BUFFER_INPUT_STREAM $(OBJ)\exewrap\core\ByteBufferInputStream.class 144- $(OBJ)\bindres.exe $(OBJ)\image_console_trace.exe PACK_INPUT_STREAM $(OBJ)\exewrap\core\PackInputStream.class 145- $(OBJ)\bindres.exe $(OBJ)\image_console_trace.exe URL_CONNECTION $(OBJ)\exewrap\core\URLConnection.class 146- $(OBJ)\bindres.exe $(OBJ)\image_console_trace.exe URL_STREAM_HANDLER $(OBJ)\exewrap\core\URLStreamHandler.class 147- $(OBJ)\bindres.exe $(OBJ)\image_console_trace.exe URL_STREAM_HANDLER_FACTORY $(OBJ)\exewrap\core\URLStreamHandlerFactory.class 148- $(OBJ)\bindres.exe $(OBJ)\image_console_trace.exe EXEWRAP_CLASS_LOADER $(OBJ)\exewrap\core\ExewrapClassLoader.class 149- $(OBJ)\bindres.exe $(OBJ)\image_console_trace.exe UTIL_JAR $(OBJ)\util.jar 150- 15194 $(OBJ)\image_console.res : $(OBJ) resources\image_console.rc resources\eventlog.bin 15295 $(RC) /fo$(OBJ)\image_console.res resources\image_console.rc 15396 @@ -154,39 +97,13 @@ 15497 $(OBJ)\image_console.obj : $(OBJ) image_console.c 15598 $(CC) $(CFLAGS) $(INC) /Fo$(OBJ)\image_console.obj image_console.c 15699 157-$(OBJ)\image_console_trace.obj : $(OBJ) image_console.c 158- $(CC) $(CFLAGS) $(INC) /DTRACE /Fo$(OBJ)\image_console_trace.obj image_console.c 159- 160100 $(OBJ)\image_gui.exe : $(OBJ) $(OBJ)\image_gui.res $(OBJ)\image_gui.obj \ 161101 $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\notify.obj $(OBJ)\eventlog.obj \ 162- $(OBJ)\bindres.exe $(OBJ)\exewrap\core\ByteBufferInputStream.class $(OBJ)\exewrap\core\PackInputStream.class $(OBJ)\exewrap\core\ExewrapClassLoader.class $(OBJ)\exewrap\core\URLConnection.class $(OBJ)\exewrap\core\URLStreamHandler.class $(OBJ)\exewrap\core\URLStreamHandlerFactory.class $(OBJ)\util.jar 102+ $(OBJ)\bindres.exe $(OBJ)\core.jar 163103 $(LINK) $(LDFLAGS) /SUBSYSTEM:WINDOWS$(TARGET_VER) /MANIFEST /OUT:$(OBJ)\image_gui.exe $(OBJ)\image_gui.res $(OBJ)\image_gui.obj \ 164104 $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\notify.obj $(OBJ)\eventlog.obj $(LIBS) $(MSVCRT_PATCH) 165105 $(MT) -manifest $(OBJ)\image_gui.exe.manifest -outputresource:$(OBJ)\image_gui.exe;1 166- $(OBJ)\bindres.exe $(OBJ)\image_gui.exe BYTE_BUFFER_INPUT_STREAM $(OBJ)\exewrap\core\ByteBufferInputStream.class 167- $(OBJ)\bindres.exe $(OBJ)\image_gui.exe PACK_INPUT_STREAM $(OBJ)\exewrap\core\PackInputStream.class 168- $(OBJ)\bindres.exe $(OBJ)\image_gui.exe URL_CONNECTION $(OBJ)\exewrap\core\URLConnection.class 169- $(OBJ)\bindres.exe $(OBJ)\image_gui.exe URL_STREAM_HANDLER $(OBJ)\exewrap\core\URLStreamHandler.class 170- $(OBJ)\bindres.exe $(OBJ)\image_gui.exe URL_STREAM_HANDLER_FACTORY $(OBJ)\exewrap\core\URLStreamHandlerFactory.class 171- $(OBJ)\bindres.exe $(OBJ)\image_gui.exe EXEWRAP_CLASS_LOADER $(OBJ)\exewrap\core\ExewrapClassLoader.class 172- $(OBJ)\bindres.exe $(OBJ)\image_gui.exe UTIL_JAR $(OBJ)\util.jar 173106 174-$(OBJ)\image_gui_trace.exe : $(OBJ) $(OBJ)\image_gui.res $(OBJ)\image_gui_trace.obj $(OBJ)\trace.obj \ 175- $(OBJ)\buffer.obj $(OBJ)\hde$(BITS).obj $(OBJ)\hook.obj $(OBJ)\trampoline.obj \ 176- $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\notify.obj $(OBJ)\eventlog.obj \ 177- $(OBJ)\bindres.exe $(OBJ)\exewrap\core\ByteBufferInputStream.class $(OBJ)\exewrap\core\PackInputStream.class $(OBJ)\exewrap\core\ExewrapClassLoader.class $(OBJ)\exewrap\core\URLConnection.class $(OBJ)\exewrap\core\URLStreamHandler.class $(OBJ)\exewrap\core\URLStreamHandlerFactory.class $(OBJ)\util.jar 178- $(LINK) $(LDFLAGS) /SUBSYSTEM:WINDOWS$(TARGET_VER) /MANIFEST /OUT:$(OBJ)\image_gui_trace.exe $(OBJ)\image_gui.res $(OBJ)\image_gui_trace.obj $(OBJ)\trace.obj \ 179- $(OBJ)\buffer.obj $(OBJ)\hde$(BITS).obj $(OBJ)\hook.obj $(OBJ)\trampoline.obj \ 180- $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\notify.obj $(OBJ)\eventlog.obj $(LIBS) $(MSVCRT_PATCH) 181- $(MT) -manifest $(OBJ)\image_gui_trace.exe.manifest -outputresource:$(OBJ)\image_gui_trace.exe;1 182- $(OBJ)\bindres.exe $(OBJ)\image_gui_trace.exe BYTE_BUFFER_INPUT_STREAM $(OBJ)\exewrap\core\ByteBufferInputStream.class 183- $(OBJ)\bindres.exe $(OBJ)\image_gui_trace.exe PACK_INPUT_STREAM $(OBJ)\exewrap\core\PackInputStream.class 184- $(OBJ)\bindres.exe $(OBJ)\image_gui_trace.exe URL_CONNECTION $(OBJ)\exewrap\core\URLConnection.class 185- $(OBJ)\bindres.exe $(OBJ)\image_gui_trace.exe URL_STREAM_HANDLER $(OBJ)\exewrap\core\URLStreamHandler.class 186- $(OBJ)\bindres.exe $(OBJ)\image_gui_trace.exe URL_STREAM_HANDLER_FACTORY $(OBJ)\exewrap\core\URLStreamHandlerFactory.class 187- $(OBJ)\bindres.exe $(OBJ)\image_gui_trace.exe EXEWRAP_CLASS_LOADER $(OBJ)\exewrap\core\ExewrapClassLoader.class 188- $(OBJ)\bindres.exe $(OBJ)\image_gui_trace.exe UTIL_JAR $(OBJ)\util.jar 189- 190107 $(OBJ)\image_gui.res : $(OBJ) resources\image_gui.rc resources\eventlog.bin 191108 $(RC) /fo$(OBJ)\image_gui.res resources\image_gui.rc 192109 @@ -193,39 +110,13 @@ 193110 $(OBJ)\image_gui.obj : $(OBJ) image_gui.c 194111 $(CC) $(CFLAGS) $(INC) /Fo$(OBJ)\image_gui.obj image_gui.c 195112 196-$(OBJ)\image_gui_trace.obj : $(OBJ) image_gui.c 197- $(CC) $(CFLAGS) $(INC) /DTRACE /Fo$(OBJ)\image_gui_trace.obj image_gui.c 198- 199113 $(OBJ)\image_service.exe : $(OBJ) $(OBJ)\image_service.res $(OBJ)\image_service.obj \ 200114 $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\eventlog.obj \ 201- $(OBJ)\bindres.exe $(OBJ)\exewrap\core\ByteBufferInputStream.class $(OBJ)\exewrap\core\PackInputStream.class $(OBJ)\exewrap\core\ExewrapClassLoader.class $(OBJ)\exewrap\core\URLConnection.class $(OBJ)\exewrap\core\URLStreamHandler.class $(OBJ)\exewrap\core\URLStreamHandlerFactory.class $(OBJ)\util.jar 115+ $(OBJ)\bindres.exe $(OBJ)\core.jar 202116 $(LINK) $(LDFLAGS) /SUBSYSTEM:CONSOLE$(TARGET_VER) /MANIFEST /OUT:$(OBJ)\image_service.exe $(OBJ)\image_service.res $(OBJ)\image_service.obj \ 203117 $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\eventlog.obj $(LIBS) $(MSVCRT_PATCH) 204118 $(MT) -manifest $(OBJ)\image_service.exe.manifest -outputresource:$(OBJ)\image_service.exe;1 205- $(OBJ)\bindres.exe $(OBJ)\image_service.exe BYTE_BUFFER_INPUT_STREAM $(OBJ)\exewrap\core\ByteBufferInputStream.class 206- $(OBJ)\bindres.exe $(OBJ)\image_service.exe PACK_INPUT_STREAM $(OBJ)\exewrap\core\PackInputStream.class 207- $(OBJ)\bindres.exe $(OBJ)\image_service.exe URL_CONNECTION $(OBJ)\exewrap\core\URLConnection.class 208- $(OBJ)\bindres.exe $(OBJ)\image_service.exe URL_STREAM_HANDLER $(OBJ)\exewrap\core\URLStreamHandler.class 209- $(OBJ)\bindres.exe $(OBJ)\image_service.exe URL_STREAM_HANDLER_FACTORY $(OBJ)\exewrap\core\URLStreamHandlerFactory.class 210- $(OBJ)\bindres.exe $(OBJ)\image_service.exe EXEWRAP_CLASS_LOADER $(OBJ)\exewrap\core\ExewrapClassLoader.class 211- $(OBJ)\bindres.exe $(OBJ)\image_service.exe UTIL_JAR $(OBJ)\util.jar 212119 213-$(OBJ)\image_service_trace.exe : $(OBJ) $(OBJ)\image_service.res $(OBJ)\image_service_trace.obj $(OBJ)\trace.obj \ 214- $(OBJ)\buffer.obj $(OBJ)\hde$(BITS).obj $(OBJ)\hook.obj $(OBJ)\trampoline.obj \ 215- $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\eventlog.obj \ 216- $(OBJ)\bindres.exe $(OBJ)\exewrap\core\ByteBufferInputStream.class $(OBJ)\exewrap\core\PackInputStream.class $(OBJ)\exewrap\core\ExewrapClassLoader.class $(OBJ)\exewrap\core\URLConnection.class $(OBJ)\exewrap\core\URLStreamHandler.class $(OBJ)\exewrap\core\URLStreamHandlerFactory.class $(OBJ)\util.jar 217- $(LINK) $(LDFLAGS) /SUBSYSTEM:CONSOLE$(TARGET_VER) /MANIFEST /OUT:$(OBJ)\image_service_trace.exe $(OBJ)\image_service.res $(OBJ)\image_service_trace.obj $(OBJ)\trace.obj \ 218- $(OBJ)\buffer.obj $(OBJ)\hde$(BITS).obj $(OBJ)\hook.obj $(OBJ)\trampoline.obj \ 219- $(OBJ)\jvm.obj $(OBJ)\loader.obj $(OBJ)\message.obj $(OBJ)\eventlog.obj $(LIBS) $(MSVCRT_PATCH) 220- $(MT) -manifest $(OBJ)\image_service_trace.exe.manifest -outputresource:$(OBJ)\image_service_trace.exe;1 221- $(OBJ)\bindres.exe $(OBJ)\image_service_trace.exe BYTE_BUFFER_INPUT_STREAM $(OBJ)\exewrap\core\ByteBufferInputStream.class 222- $(OBJ)\bindres.exe $(OBJ)\image_service_trace.exe PACK_INPUT_STREAM $(OBJ)\exewrap\core\PackInputStream.class 223- $(OBJ)\bindres.exe $(OBJ)\image_service_trace.exe URL_CONNECTION $(OBJ)\exewrap\core\URLConnection.class 224- $(OBJ)\bindres.exe $(OBJ)\image_service_trace.exe URL_STREAM_HANDLER $(OBJ)\exewrap\core\URLStreamHandler.class 225- $(OBJ)\bindres.exe $(OBJ)\image_service_trace.exe URL_STREAM_HANDLER_FACTORY $(OBJ)\exewrap\core\URLStreamHandlerFactory.class 226- $(OBJ)\bindres.exe $(OBJ)\image_service_trace.exe EXEWRAP_CLASS_LOADER $(OBJ)\exewrap\core\ExewrapClassLoader.class 227- $(OBJ)\bindres.exe $(OBJ)\image_service_trace.exe UTIL_JAR $(OBJ)\util.jar 228- 229120 $(OBJ)\image_service.res : $(OBJ) resources\image_service.rc resources\eventlog.bin 230121 $(RC) /fo$(OBJ)\image_service.res resources\image_service.rc 231122 @@ -232,9 +123,6 @@ 232123 $(OBJ)\image_service.obj : $(OBJ) image_service.c 233124 $(CC) $(CFLAGS) $(INC) /Fo$(OBJ)\image_service.obj image_service.c 234125 235-$(OBJ)\image_service_trace.obj : $(OBJ) image_service.c 236- $(CC) $(CFLAGS) $(INC) /Fo$(OBJ)\image_service_trace.obj image_service.c 237- 238126 $(OBJ)\eventlog.obj : $(OBJ) eventlog.c 239127 $(CC) $(CFLAGS) $(INC) /Fo$(OBJ)\eventlog.obj eventlog.c 240128 @@ -250,9 +138,6 @@ 250138 $(OBJ)\jvm.obj : $(OBJ) jvm.c 251139 $(CC) $(CFLAGS) $(INC) /Fo$(OBJ)\jvm.obj jvm.c 252140 253-$(OBJ)\trace.obj : $(OBJ) trace.c 254- $(CC) $(CFLAGS) $(INC) /Fo$(OBJ)\trace.obj trace.c 255- 256141 $(OBJ)\bindres.exe : $(OBJ) $(OBJ)\bindres.obj 257142 $(LINK) $(LDFLAGS) /SUBSYSTEM:CONSOLE$(TARGET_VER) /OUT:$(OBJ)\bindres.exe $(OBJ)\bindres.obj $(LIBS) $(MSVCRT_PATCH) 258143 @@ -261,28 +146,14 @@ 261146 262147 263148 ### 264-### MinHook 149+### Java 265150 ### 266151 267-$(OBJ)\buffer.obj : minhook\src\buffer.c 268- $(CC) $(CFLAGS) $(INC) /Fo$(OBJ)\buffer.obj minhook\src\buffer.c 269- 270-$(OBJ)\hook.obj : minhook\src\hook.c 271- $(CC) $(CFLAGS) $(INC) /I minhook\WindowsSDK\include /Fo$(OBJ)\hook.obj minhook\src\hook.c 272- 273-$(OBJ)\trampoline.obj : minhook\src\trampoline.c 274- $(CC) $(CFLAGS) $(INC) /Fo$(OBJ)\trampoline.obj minhook\src\trampoline.c 152+### exewrap.core (including exewrap.util) 275153 276-$(OBJ)\hde$(BITS).obj : minhook\src\HDE\hde$(BITS).c 277- $(CC) $(CFLAGS) $(INC) /Fo$(OBJ)\hde$(BITS).obj minhook\src\HDE\hde$(BITS).c 154+$(OBJ)\core.jar : $(OBJ) $(OBJ)\exewrap\core\ExewrapClassLoader.class $(OBJ)\exewrap\core\PackInputStream.class $(OBJ)\exewrap\core\ByteBufferInputStream.class $(OBJ)\exewrap\core\URLConnection.class $(OBJ)\exewrap\core\URLStreamHandler.class $(OBJ)\exewrap\core\URLStreamHandler.class $(OBJ)\exewrap\util\EventLogHandler.class $(OBJ)\exewrap\util\EventLogStream.class $(OBJ)\exewrap\util\FileLogStream.class $(OBJ)\exewrap\util\UncaughtExceptionHandler.class $(OBJ)\exewrap\util\ConsoleOutputStream.class $(OBJ)\exewrap\util\Environment.class 155+ $(JAR) cvf $(OBJ)\core.jar -C $(OBJ) exewrap 278156 279- 280-### 281-### Java 282-### 283- 284-### exewrap.core 285- 286157 $(OBJ)\exewrap\core\ExewrapClassLoader.class : $(OBJ) java\exewrap\core\ExewrapClassLoader.java 287158 $(JAVAC) -Xlint:none -source 1.5 -target 1.5 -sourcepath java -d $(OBJ) java\exewrap\core\ExewrapClassLoader.java 288159 @@ -326,42 +197,12 @@ 326197 327198 ### exewrap.tool 328199 329-$(OBJ)\tool.jar : $(OBJ) $(OBJ)\exewrap\tool\JarProcessor.class $(OBJ)\exewrap\tool\PackOutputStream.class 330- $(JAR) cvfe $(OBJ)\tool.jar exewrap.tool.JarProcessor -C $(OBJ) exewrap\tool 200+$(OBJ)\tool.jar : $(OBJ) $(OBJ)\exewrap-tool $(OBJ)\exewrap\tool\JarProcessor.class $(OBJ)\exewrap\tool\PackOutputStream.class 201+ $(JAR) cvfe $(OBJ)\tool.jar exewrap.tool.JarProcessor -C $(OBJ)\exewrap-tool exewrap\tool 331202 332203 $(OBJ)\exewrap\tool\PackOutputStream.class : $(OBJ) java\exewrap\tool\PackOutputStream.java 333- $(JAVAC) -Xlint:none -source 1.5 -target 1.5 -sourcepath java -d $(OBJ) java\exewrap\tool\PackOutputStream.java 204+ $(JAVAC) -Xlint:none -source 1.5 -target 1.5 -sourcepath java -d $(OBJ)\exewrap-tool java\exewrap\tool\PackOutputStream.java 334205 335206 $(OBJ)\exewrap\tool\JarProcessor.class : $(OBJ) java\exewrap\tool\JarProcessor.java 336- $(JAVAC) -Xlint:none -source 1.5 -target 1.5 -sourcepath java -d $(OBJ) java\exewrap\tool\JarProcessor.java 207+ $(JAVAC) -Xlint:none -source 1.5 -target 1.5 -sourcepath java -d $(OBJ)\exewrap-tool java\exewrap\tool\JarProcessor.java 337208 338-### jeremin 339- 340-$(BIN)\jremin.exe : $(OBJ)\jremin.jar $(BIN)\exewrap.exe 341- $(BIN)\exewrap.exe -o $(BIN)\jremin.exe -j $(OBJ)\jremin.jar -a "-Xmx1024m" -e "NOSIDEBYSIDE" \ 342- -p jremin \ 343- -V 1.1.0 \ 344- -v 1.1.0.0 \ 345- -d "Java Runtime Environment (JRE) Minimizer" \ 346- -c "Copyright (C) 2015 HIRUKAWA Ryo. All rights reserved." 347- 348-$(OBJ)\jremin.jar : $(OBJ) $(OBJ)\jremin\Jremin.class $(OBJ)\jremin\Trace.class $(OBJ)\jremin\classes.txt 349- $(JAR) cvfe $(OBJ)\jremin.jar jremin.JreMin -C $(OBJ) jremin 350- 351-$(OBJ)\jremin\JreMin.class : $(OBJ) java\jremin\JreMin.java 352- $(JAVAC) -Xlint:none -source 1.5 -target 1.5 -sourcepath java -d $(OBJ) java\jremin\JreMin.java 353- 354-$(OBJ)\jremin\Trace.class : $(OBJ) java\jremin\Trace.java 355- $(JAVAC) -Xlint:none -source 1.5 -target 1.5 -sourcepath java -d $(OBJ) java\jremin\Trace.java 356- 357-$(OBJ)\jremin\classes.txt : $(OBJ) $(OBJ)\agent.exe 358- $(OBJ)\agent.exe > $(OBJ)\jremin\classes.txt 359- 360-$(OBJ)\agent.exe : $(OBJ) $(OBJ)\agent.jar 361- $(BIN)\exewrap.exe -o $(OBJ)\agent.exe -j $(OBJ)\agent.jar -e "NOSIDEBYSIDE" -a "-javaagent:$(OBJ)\agent.jar" 362- 363-$(OBJ)\agent.jar : $(OBJ) $(OBJ)\jremin\agent\Agent.class java\jremin\agent\manifest.txt 364- $(JAR) cvfm $(OBJ)\agent.jar java\jremin\agent\manifest.txt -C $(OBJ) jremin 365- 366-$(OBJ)\jremin\agent\Agent.class : $(OBJ) java\jremin\agent\Agent.java 367- $(JAVAC) -Xlint:none -source 1.5 -target 1.5 -sourcepath java -d $(OBJ) java\jremin\agent\Agent.java --- exewrap/trunk/exewrap/src/exewrap.c (revision 38) +++ exewrap/trunk/exewrap/src/exewrap.c (revision 39) @@ -25,6 +25,7 @@ 2525 static char** parse_opt(int argc, char* argv[]); 2626 static DWORD get_version_revision(char* filename); 2727 static BOOL create_exe_file(const char* filename, BYTE* image_buf, DWORD image_len, BOOL is_reverse); 28+static BOOL append_exe_file(const char* filename, BYTE* image_buf, DWORD image_len); 2829 static DWORD get_target_java_runtime_version(char* version); 2930 static char* get_target_java_runtime_version_string(DWORD version, char* buf); 3031 static void set_resource(const char* filename, const char* rsc_name, const char* rsc_type, BYTE* rsc_data, DWORD rsc_size); @@ -60,7 +61,6 @@ 6061 char* product_version; 6162 char* original_filename; 6263 char* new_version; 63- BOOL is_trace_version = FALSE; 6464 BOOL contains_visualvm_display_name = FALSE; 6565 6666 char* buf = NULL; @@ -83,9 +83,7 @@ 8383 exe_file = argv[0]; 8484 } 8585 86- is_trace_version = strstr(exe_file, "trace") != NULL; 87- 88- printf("exewrap 1.1.9 for %s (%d-bit) %s\r\n" 86+ printf("exewrap 1.2.0 for %s (%d-bit) \r\n" 8987 "Native executable java application wrapper.\r\n" 9088 "Copyright (C) 2005-2017 HIRUKAWA Ryo. All rights reserved.\r\n" 9189 "\r\n" @@ -110,7 +108,7 @@ 110108 " -V <product-version>\t Set product version.\r\n" 111109 " -j <jar-file> \t Input jar-file.\r\n" 112110 " -o <exe-file> \t Output exe-file.\r\n" 113- , (bits == 64 ? "x64" : "x86"), bits, (is_trace_version ? "[ TRACE VERSION ]" : ""), exe_file, (bits == 64 ? "x64" : "x86")); 111+ , (bits == 64 ? "x64" : "x86"), bits, exe_file, (bits == 64 ? "x64" : "x86")); 114112 115113 return 0; 116114 } @@ -156,12 +154,6 @@ 156154 } 157155 strcpy(exe_file, buf); 158156 159- if (is_trace_version) 160- { 161- *strrchr(exe_file, '.') = '\0'; 162- strcat(exe_file, ".TRACE.exe"); 163- } 164- 165157 if(opt['A']) 166158 { 167159 if(strstr(opt['A'], "86") != NULL) @@ -181,15 +173,15 @@ 181173 182174 if(opt['g']) 183175 { 184- sprintf(image_name, "IMAGE%s_GUI_%d", (is_trace_version ? "_TRACE" : ""), architecture_bits); 176+ sprintf(image_name, "IMAGE_GUI_%d", architecture_bits); 185177 } 186178 else if(opt['s']) 187179 { 188- sprintf(image_name, "IMAGE%s_SERVICE_%d", (is_trace_version ? "_TRACE" : ""), architecture_bits); 180+ sprintf(image_name, "IMAGE_SERVICE_%d", architecture_bits); 189181 } 190182 else 191183 { 192- sprintf(image_name, "IMAGE%s_CONSOLE_%d", (is_trace_version ? "_TRACE" : ""), architecture_bits); 184+ sprintf(image_name, "IMAGE_CONSOLE_%d", architecture_bits); 193185 } 194186 195187 GetResource(image_name, &res); @@ -231,7 +223,7 @@ 231223 set_resource(exe_file, "EXTDIRS", RT_RCDATA, "lib", 4); 232224 } 233225 234- enable_java = CreateJavaVM(NULL, FALSE, TRUE, NULL) != NULL; 226+ enable_java = CreateJavaVM(NULL, "exewrap.core.ExewrapClassLoader", FALSE, TRUE, NULL) != NULL; 235227 if (enable_java) 236228 { 237229 LOAD_RESULT result; @@ -313,7 +305,7 @@ 313305 printf(_(MSG_ID_ERR_GET_METHOD), "exewrap.tool.JarProcessor.getSplashScreenImage()"); 314306 goto EXIT; 315307 } 316- jarProcessor_getBytes = (*env)->GetMethodID(env, JarProcessor, "getBytes", "()[B"); 308+ jarProcessor_getBytes = (*env)->GetMethodID(env, JarProcessor, "getBytes", "()[B"); 317309 if (jarProcessor_getBytes == NULL) 318310 { 319311 result.msg_id = MSG_ID_ERR_GET_METHOD; @@ -382,10 +374,6 @@ 382374 383375 ext_flags = (char*)malloc(1024); 384376 ext_flags[0] = '\0'; 385- if (is_trace_version) 386- { 387- strcat(ext_flags, "NOSIDEBYSIDE;"); 388- } 389377 if (opt['e'] && *opt['e'] != '-' && *opt['e'] != '\0') 390378 { 391379 strcat(ext_flags, opt['e']); @@ -393,19 +381,6 @@ 393381 set_resource(exe_file, "EXTFLAGS", RT_RCDATA, ext_flags, (DWORD)strlen(ext_flags) + 1); 394382 free(ext_flags); 395383 396- if (is_trace_version) 397- { 398- if (vmargs == NULL) 399- { 400- vmargs = (char*)malloc(2048); 401- vmargs[0] = '\0'; 402- } 403- else 404- { 405- strcat(vmargs, " "); 406- } 407- strcat(vmargs, "-XX:+TraceClassLoading"); 408- } 409384 if(opt['a'] && *opt['a'] != '\0') 410385 { 411386 if (vmargs == NULL) @@ -533,6 +508,20 @@ 533508 534509 original_filename = strrchr(exe_file, '\\') + 1; 535510 new_version = set_version_info(exe_file, version_number, previous_revision, file_description, copyright, company_name, product_name, product_version, original_filename, jar_file); 511+ 512+ if(GetResource("CORE_JAR", &res) == NULL) 513+ { 514+ printf("ERROR: GetResource: CORE_JAR\n"); 515+ goto EXIT; 516+ } 517+ else 518+ { 519+ if(append_exe_file(exe_file, res.buf, res.len) == FALSE) 520+ { 521+ goto EXIT; 522+ } 523+ } 524+ 536525 printf("%s (%d-bit) version %s\r\n", strrchr(exe_file, '\\') + 1, architecture_bits, new_version); 537526 538527 EXIT: @@ -588,10 +577,11 @@ 588577 589578 static DWORD get_version_revision(char* filename) 590579 { 591- /* GetFileVersionInfoSize, GetFileVersionInfo ?ス?ス?スg?ス?ス?スニ難ソス?ス?ス?ス?ス LoadLibrary ?ス?ス?スg?スp?ス?ス?ス?ス?ス轤オ?ス?ス 592- * ?ス?ス?スフ鯉ソスフ?ソス?ス\?ス[?スX?ス?ス?ス?ス?ス?ス?スンゑソス?ス?ス?スワゑソス?ス?ス?ス?ス?スネゑソス?スネゑソス謔、?スナゑソス?スB?スネので、?ス?ス?スヘゑソス EXE?スt?ス@?スC?ス?ス?ス?ス?ス?ス 593- * ?ス?ス?スr?スW?ス?ス?ス?ス?スi?ス?ス?スo?ス[?ス?ス?ス?ス?スo?ス?ス?ス謔、?スノ変更?ス?ス?スワゑソス?ス?ス?スB 594- */ 580+ /* GetFileVersionInfoSize, GetFileVersionInfo を使うと内部で LoadLibrary が使用されるらしく 581+ * その後のリソース書き込みがうまくいかなくなるようです。なので、自力で EXEファイルから 582+ * リビジョンナンバーを取り出すように変更しました。 583+ */ 584+ int SCAN_SIZE = 8192 * 3; 595585 DWORD revision = 0; 596586 HANDLE hFile; 597587 char HEADER[] = "VS_VERSION_INFO"; @@ -601,7 +591,7 @@ 601591 unsigned int i; 602592 size_t j; 603593 604- buf = (BYTE*)malloc(8192); 594+ buf = (BYTE*)malloc(SCAN_SIZE); 605595 606596 hFile = CreateFile(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 607597 if (hFile == INVALID_HANDLE_VALUE) @@ -609,8 +599,8 @@ 609599 goto EXIT; 610600 } 611601 612- SetFilePointer(hFile, -1 * 8192, 0, FILE_END); 613- ReadFile(hFile, buf, 8192, &size, NULL); 602+ SetFilePointer(hFile, -1 * SCAN_SIZE, 0, FILE_END); 603+ ReadFile(hFile, buf, SCAN_SIZE, &size, NULL); 614604 CloseHandle(hFile); 615605 616606 len = strlen(HEADER); @@ -679,10 +669,6 @@ 679669 } 680670 image_buf = buf; 681671 } 682- else 683- { 684- buf = image_buf; 685- } 686672 687673 while (image_len > 0) 688674 { @@ -711,6 +697,41 @@ 711697 } 712698 713699 700+static BOOL append_exe_file(const char* filename, BYTE* image_buf, DWORD image_len) 701+{ 702+ BOOL ret = FALSE; 703+ HANDLE hFile; 704+ BYTE* buf = NULL; 705+ DWORD write_size; 706+ char* dir; 707+ char* ptr; 708+ 709+ hFile = CreateFile(filename, FILE_APPEND_DATA, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 710+ if (hFile == INVALID_HANDLE_VALUE) 711+ { 712+ printf("Failed to open file: %s\n", filename); 713+ goto EXIT; 714+ } 715+ 716+ while (image_len > 0) 717+ { 718+ if (WriteFile(hFile, image_buf, image_len, &write_size, NULL) == 0) 719+ { 720+ printf("Failed to write: %s\n", filename); 721+ goto EXIT; 722+ } 723+ image_buf += write_size; 724+ image_len -= write_size; 725+ } 726+ CloseHandle(hFile); 727+ 728+ ret = TRUE; 729+ 730+EXIT: 731+ return ret; 732+} 733+ 734+ 714735 /* 715736 * major(7bit) 31-25 716737 * minor(7bit) 24-18 @@ -760,7 +781,7 @@ 760781 761782 *(DWORD*)buf = version; 762783 763- //1.7?ス` 784+ //1.7- 764785 if (major == 1 && minor >= 7 && build == 0) 765786 { 766787 if(revision == 0) @@ -1056,7 +1077,7 @@ 10561077 product_version_build = atoi(strtok(NULL, ".")); 10571078 product_version_revision = atoi(strtok(NULL, ".")); 10581079 1059- // revison ?ス?ス?ス?ス?ス?ス?スI?スノ指?ス閧ウ?ス?ストゑソス?スネゑソス?ス?ス?ス?ス?ス鼾?ソスA?ス?ス?ス?ス?スt?ス@?スC?ス?ス?ス?ス?ス?ス謫セ?ス?ス?ス?ス?スl?ス?ス 1?ス@?ス?ス?ス?ス?スZ?ス?ス?ス?ス revision ?スニゑソス?ス?スB 1080+ // revison が明示的に指定されていなかった場合、既存ファイルから取得した値に 1 を加算して revision とする。 10601081 strcpy(buffer, version_number); 10611082 if (strtok(buffer, ".") != NULL) 10621083 { @@ -1073,7 +1094,7 @@ 10731094 } 10741095 10751096 file_version_revision = (short)previous_revision + 1; 1076- // build ?ス?ス?スZ?ス?ス?ス閧ア?ス?ス?スワで。 1097+ // build 加算判定ここまで。 10771098 sprintf(file_version, "%d.%d.%d.%d", file_version_major, file_version_minor, file_version_build, file_version_revision); 10781099 10791100 GetResource("VERSION_INFO", &res); --- exewrap/trunk/exewrap/src/image_console.c (revision 38) +++ exewrap/trunk/exewrap/src/image_console.c (revision 39) @@ -67,7 +67,7 @@ 6767 } 6868 6969 vm_args_opt = (char*)GetResource("VMARGS", NULL); 70- CreateJavaVM(vm_args_opt, use_server_vm, use_side_by_side_jre, &err); 70+ CreateJavaVM(vm_args_opt, "exewrap.core.ExewrapClassLoader", use_server_vm, use_side_by_side_jre, &err); 7171 if (err != JNI_OK) 7272 { 7373 OutputMessage(GetJniErrorMessage(err, &result.msg_id, result.msg)); --- exewrap/trunk/exewrap/src/image_gui.c (revision 38) +++ exewrap/trunk/exewrap/src/image_gui.c (revision 39) @@ -119,7 +119,7 @@ 119119 { 120120 vm_args_opt = (char*)GetResource("VMARGS", NULL); 121121 } 122- CreateJavaVM(vm_args_opt, use_server_vm, use_side_by_side_jre, &err); 122+ CreateJavaVM(vm_args_opt, "exewrap.core.ExewrapClassLoader", use_server_vm, use_side_by_side_jre, &err); 123123 if (err != JNI_OK) 124124 { 125125 OutputMessage(GetJniErrorMessage(err, &result.msg_id, result.msg)); --- exewrap/trunk/exewrap/src/image_service.c (revision 38) +++ exewrap/trunk/exewrap/src/image_service.c (revision 39) @@ -94,7 +94,7 @@ 9494 if(vm_args_opt == NULL) { 9595 vm_args_opt = (char*)GetResource("VMARGS", NULL); 9696 } 97- CreateJavaVM(vm_args_opt, use_server_vm, use_side_by_side_jre, &err); 97+ CreateJavaVM(vm_args_opt, "exewrap.core.ExewrapClassLoader", use_server_vm, use_side_by_side_jre, &err); 9898 if (err != JNI_OK) 9999 { 100100 OutputMessage(GetWinErrorMessage(err, &result.msg_id, result.msg)); --- exewrap/trunk/exewrap/src/include/jvm.h (revision 38) +++ exewrap/trunk/exewrap/src/include/jvm.h (revision 39) @@ -5,7 +5,7 @@ 55 66 extern int GetProcessArchitecture(); 77 extern void InitializePath(LPTSTR relative_classpath, LPTSTR relative_extdirs, BOOL useServerVM, BOOL useSideBySideJRE); 8-extern JNIEnv* CreateJavaVM(LPTSTR vm_args_opt, BOOL useServerVM, BOOL useSideBySideJRE, int* err); 8+extern JNIEnv* CreateJavaVM(LPTSTR vm_args_opt, LPTSTR systemClassLoader, BOOL useServerVM, BOOL useSideBySideJRE, int* err); 99 extern void DestroyJavaVM(); 1010 extern JNIEnv* AttachJavaVM(); 1111 extern void DetachJavaVM(); --- exewrap/trunk/exewrap/src/include/message.h (revision 38) +++ exewrap/trunk/exewrap/src/include/message.h (revision 39) @@ -18,7 +18,7 @@ 1818 #define MSG_ID_ERR_UNCAUGHT_EXCEPTION 8 1919 #define MSG_ID_ERR_RESOURCE_NOT_FOUND 9 2020 #define MSG_ID_ERR_TARGET_VERSION 10 21-#define MSG_ID_ERR_DEFINE_CLASS 11 21+#define MSG_ID_ERR_FIND_CLASS 11 2222 #define MSG_ID_ERR_GET_METHOD 12 2323 #define MSG_ID_ERR_GET_CONSTRUCTOR 13 2424 #define MSG_ID_ERR_NEW_OBJECT 14 --- exewrap/trunk/exewrap/src/java/jremin/Trace.java (revision 38) +++ exewrap/trunk/exewrap/src/java/jremin/Trace.java (nonexistent) @@ -1,163 +0,0 @@ 1-package jremin; 2- 3-import java.io.BufferedReader; 4-import java.io.File; 5-import java.io.FileInputStream; 6-import java.io.FilenameFilter; 7-import java.io.IOException; 8-import java.io.InputStreamReader; 9-import java.nio.charset.Charset; 10-import java.util.ArrayList; 11-import java.util.HashSet; 12-import java.util.List; 13-import java.util.Set; 14-import java.util.jar.JarEntry; 15-import java.util.jar.JarInputStream; 16-import java.util.regex.Matcher; 17-import java.util.regex.Pattern; 18- 19-public class Trace { 20- 21- private static Pattern LOADED_CLASS = Pattern.compile("Loaded (\\S+)", Pattern.CASE_INSENSITIVE); 22- private static Pattern LOAD_LIBRARY = Pattern.compile("\\[LoadLibrary (.+)\\]", Pattern.CASE_INSENSITIVE); 23- private static Pattern CREATE_FILE = Pattern.compile("\\[CreateFile (.+)\\]", Pattern.CASE_INSENSITIVE); 24- 25- private File jre = null; 26- private Set<String> jars = null; 27- private Set<String> files = new HashSet<String>(); 28- private Set<String> packages = new HashSet<String>(); 29- private Set<String> requiredClassEntryNames = new HashSet<String>(); 30- private boolean useAwt; 31- private boolean useSwing; 32- 33- public Trace(File file) throws IOException { 34- file = file.getCanonicalFile(); 35- String s = file.getName(); 36- int i = s.toUpperCase().indexOf(".TRACE"); 37- if(i >= 0) { 38- s = s.substring(0, i); 39- } 40- final String basename = s; 41- File dir = file.getParentFile(); 42- File[] files = dir.listFiles(new FilenameFilter() { 43- @Override 44- public boolean accept(File dir, String name) { 45- return name.startsWith(basename) && name.toUpperCase().contains(".TRACE") && name.toLowerCase().endsWith(".log"); 46- } 47- }); 48- for(File f : files) { 49- BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(f), Charset.forName("MS932"))); 50- String line; 51- while((line = r.readLine()) != null) { 52- Matcher m; 53- m = LOADED_CLASS.matcher(line); 54- if(m.find()) { 55- String cls = m.group(1); 56- if(!this.useAwt && (cls.startsWith("com.sun.awt.") || cls.startsWith("java.awt."))) { 57- this.useAwt = true; 58- } 59- if(!this.useSwing && (cls.startsWith("com.sun.swing.") || cls.startsWith("javax.swing."))) { 60- this.useSwing = true; 61- } 62- if(cls.startsWith("exewrap.")) { 63- continue; 64- } 65- this.requiredClassEntryNames.add(cls.replace('.', '/') + ".class"); 66- continue; 67- } 68- m = LOAD_LIBRARY.matcher(line); 69- if(m.find()) { 70- this.files.add(m.group(1)); 71- continue; 72- } 73- m = CREATE_FILE.matcher(line); 74- if(m.find()) { 75- this.files.add(m.group(1)); 76- continue; 77- } 78- } 79- r.close(); 80- } 81- for(String cls : this.requiredClassEntryNames) { 82- int j = cls.lastIndexOf('/'); 83- if(j >= 0) { 84- this.packages.add(cls.substring(0, j)); 85- } 86- } 87- } 88- 89- public File getJRE() { 90- if(jre == null) { 91- for(String s : files) { 92- File f = new File(s); 93- if(f.exists() && (f.getName().equalsIgnoreCase("jvm.dll") || f.getName().equalsIgnoreCase("rt.jar"))) { 94- File dir = f.getParentFile(); 95- while(dir != null) { 96- if(dir.getName().equalsIgnoreCase("bin") || dir.getName().equalsIgnoreCase("lib")) { 97- jre = dir.getParentFile(); 98- return jre; 99- } 100- dir = dir.getParentFile(); 101- } 102- } 103- } 104- } 105- return jre; 106- } 107- 108- public Set<String> getUsedJars() throws IOException { 109- if(jars == null) { 110- jars = new HashSet<String>(); 111- List<File> list = new ArrayList<File>(); 112- traverseJars(list, getJRE()); 113- for(File jar : list) { 114- boolean used = false; 115- JarInputStream jarIn = new JarInputStream(new FileInputStream(jar)); 116- JarEntry entry; 117- while((entry = jarIn.getNextJarEntry()) != null) { 118- if(requiredClassEntryNames.contains(entry.getName())) { 119- used = true; 120- break; 121- } 122- } 123- jarIn.close(); 124- if(used) { 125- jars.add(jar.getCanonicalPath()); 126- } 127- } 128- } 129- return jars; 130- } 131- 132- private void traverseJars(List<File> list, File dir) throws IOException { 133- for(File file : dir.listFiles()) { 134- if(file.isDirectory()) { 135- traverseJars(list, file); 136- } else { 137- if(file.getName().toLowerCase().endsWith(".jar")) { 138- list.add(file); 139- }; 140- } 141- } 142- } 143- 144- public Set<String> getRequiredClassEntryNames() { 145- return this.requiredClassEntryNames; 146- } 147- 148- public Set<String> getPackages() { 149- return this.packages; 150- } 151- 152- public Set<String> getFiles() { 153- return this.files; 154- } 155- 156- public boolean useAwt() { 157- return this.useAwt; 158- } 159- 160- public boolean useSwing() { 161- return this.useSwing; 162- } 163-} \ No newline at end of file --- exewrap/trunk/exewrap/src/java/jremin/agent/Agent.java (revision 38) +++ exewrap/trunk/exewrap/src/java/jremin/agent/Agent.java (nonexistent) @@ -1,18 +0,0 @@ 1-package jremin.agent; 2- 3-import java.lang.instrument.Instrumentation; 4- 5-public class Agent { 6- public static void premain(String agentArgs, Instrumentation instrumentation) { 7- Class<?>[] classes = instrumentation.getAllLoadedClasses(); 8- for (Class<?> cls : classes) { 9- String name = cls.getName(); 10- if(name.length() >= 1 && name.charAt(0) != '[' && !name.startsWith("jremin.")) { 11- System.out.println(name); 12- } 13- } 14- } 15- 16- public static void main(String[] args) { 17- } 18-} --- exewrap/trunk/exewrap/src/java/jremin/agent/manifest.txt (revision 38) +++ exewrap/trunk/exewrap/src/java/jremin/agent/manifest.txt (nonexistent) @@ -1,2 +0,0 @@ 1-Premain-Class: jremin.agent.Agent 2-Main-Class: jremin.agent.Agent --- exewrap/trunk/exewrap/src/java/jremin/JreMin.java (revision 38) +++ exewrap/trunk/exewrap/src/java/jremin/JreMin.java (nonexistent) @@ -1,345 +0,0 @@ 1-package jremin; 2- 3-import java.io.BufferedReader; 4-import java.io.BufferedWriter; 5-import java.io.ByteArrayOutputStream; 6-import java.io.File; 7-import java.io.FileInputStream; 8-import java.io.FileNotFoundException; 9-import java.io.FileOutputStream; 10-import java.io.IOException; 11-import java.io.InputStream; 12-import java.io.InputStreamReader; 13-import java.io.OutputStreamWriter; 14-import java.io.Writer; 15-import java.nio.channels.FileChannel; 16-import java.nio.charset.Charset; 17-import java.util.ArrayList; 18-import java.util.Arrays; 19-import java.util.Collections; 20-import java.util.HashMap; 21-import java.util.HashSet; 22-import java.util.List; 23-import java.util.Map; 24-import java.util.Set; 25-import java.util.jar.JarEntry; 26-import java.util.jar.JarInputStream; 27-import java.util.jar.JarOutputStream; 28- 29-public class JreMin { 30- 31- private static Set<String> excluded = new HashSet<String>(Arrays.asList(new String[] { 32- "classes.jsa", 33- "meta-index" 34- })); 35- 36- private static Set<String> requiredFiles = new HashSet<String>(Arrays.asList(new String[] { 37- "copyright", 38- "license", 39- "readme.txt", 40- "thirdpartylicensereadme.txt", 41- "thirdpartylicensereadme-javafx.txt", 42- "welcome.html" 43- })); 44- 45- private static Set<String> fonts = new HashSet<String>(Arrays.asList(new String[] { 46- "lucidabrightdemibold.ttf", 47- "lucidabrightdemiitalic.ttf", 48- "lucidabrightitalic.ttf", 49- "lucidabrightregular.ttf", 50- "lucidasansdemibold.ttf", 51- "lucidasansregular.ttf", 52- "lucidatypewriterbold.ttf", 53- "lucidatypewriterregular.ttf" 54- })); 55- 56- private static Map<String, Set<String>> map = new HashMap<String, Set<String>>(); 57- 58- private static Set<String> requiredPackages = new HashSet<String>(Arrays.asList(new String[] { 59- "java/lang/*" 60- })); 61- 62- public static void main(String[] args) throws Exception { 63- if(args.length == 0) { 64- showUsage(); 65- return; 66- } 67- 68- map.put("awt", new HashSet<String>(Arrays.asList(new String[] { 69- "com/sun/awt/*", 70- "java/text/*", 71- "java/awt/*", 72- "sun/awt/*", 73- "sun/dc/*", 74- "sun/font/*", 75- "sun/util/locale/*", 76- //-------- 77- "java/util", 78- "sun/util", 79- "sun/util/calendar" 80- }))); 81- 82- map.put("swing", new HashSet<String>(Arrays.asList(new String[] { 83- "com/sun/beans/util/*", 84- "com/sun/java/swing/*", 85- "com/sun/media/*", 86- "com/sun/swing/*", 87- "java/applet/*", 88- "java/awt/*", 89- "java/beans/*", 90- "java/io/*", 91- "java/math/*", 92- "java/net/*", 93- "java/nio/*", 94- "java/security/*", 95- "java/text/*", 96- "java/util/*", 97- "javax/accessibility/*", 98- "javax/print/*", 99- "javax/sound/*", 100- "javax/swing/*", 101- "jdk/internal/org/objectweb/asm/*", 102- "sun/awt/*", 103- "sun/dc/*", 104- "sun/font/*", 105- "sun/invoke/*", 106- "sun/io/*", 107- "sun/java2d/*", 108- "sun/misc/*", 109- "sun/net/*", 110- "sun/nio/*", 111- "sun/print/*", 112- "sun/reflect/*", 113- "sun/security/*", 114- "sun/swing/*", 115- "sun/text/*", 116- "sun/util/*" 117- }))); 118- 119- String filename = args[0]; 120- 121- boolean debug = false; 122- if(args.length >= 2 && args[0].equals("-d")) { 123- debug = true; 124- filename = args[1]; 125- } 126- 127- if(!new File(filename).exists()) { 128- System.out.println(); 129- } 130- 131- Trace trace = new Trace(new File(filename)); 132- if(debug) { 133- debugOut(trace); 134- } 135- 136- File jre = trace.getJRE(); 137- if(jre == null) { 138- System.out.println("JRE not found."); 139- return; 140- } 141- File target = new File(jre.getName() + "_min"); 142- 143- Set<String> appends = new HashSet<String>(); 144- 145- if(trace.useAwt()) { 146- for(String pkg : map.get("awt")) { 147- requiredPackages.add(pkg); 148- } 149- appends.addAll(fonts); 150- } 151- if(trace.useSwing()) { 152- for(String pkg : map.get("swing")) { 153- requiredPackages.add(pkg); 154- } 155- appends.addAll(fonts); 156- } 157- 158- Set<File> files = new HashSet<File>(); 159- for(File file : getRequiredFiles(jre, appends)) { 160- files.add(file); 161- } 162- for(String s : trace.getFiles()) { 163- File file = new File(s).getCanonicalFile(); 164- files.add(file); 165- } 166- for(String s : trace.getUsedJars()) { 167- File file = new File(s).getCanonicalFile(); 168- files.add(file); 169- } 170- 171- Set<String> requiredClassEntryNames = getRequiredClassEntryNames(); 172- for(String name : trace.getRequiredClassEntryNames()) { 173- requiredClassEntryNames.add(name); 174- } 175- 176- for(File file : files) { 177- if(!file.exists()) { 178- continue; 179- } 180- if(!file.getPath().toLowerCase().startsWith(jre.getPath().toLowerCase())) { 181- continue; 182- } 183- if(excluded.contains(file.getName().toLowerCase())) { 184- continue; 185- } 186- File dst = new File(target, file.getPath().substring(jre.getPath().length())); 187- File dir = dst.getParentFile(); 188- if(!dir.exists()) { 189- dir.mkdirs(); 190- } 191- System.out.println(dst.getPath()); 192- if(file.getPath().toLowerCase().endsWith(".jar")) { 193- copyJAR(file, dst, requiredClassEntryNames, requiredPackages); 194- } else { 195- copy(file, dst); 196- } 197- } 198- } 199- 200- public static void showUsage() { 201- System.out.println( 202- "jremin 1.1.0\r\n" + 203- "Java Runtime Environment (JRE) minimizer.\r\n" + 204- "Copyright (C) 2015 HIRUKAWA Ryo. All rights reserved.\r\n" + 205- "\r\n" + 206- "Usage: jremin.exe <trace-file>\r\n" 207- ); 208- } 209- 210- public static void copy(File src, File dst) throws IOException { 211- FileChannel sc = null; 212- FileChannel dc = null; 213- try { 214- sc = new FileInputStream(src).getChannel(); 215- dc = new FileOutputStream(dst).getChannel(); 216- dc.transferFrom(sc, 0, sc.size()); 217- } finally { 218- if (dc != null) try { dc.close(); } catch (Exception e) {} 219- if (sc != null) try { sc.close(); } catch (Exception e) {} 220- } 221- } 222- 223- public static void copyJAR(File src, File dst, Set<String> requiredClassEntryNames, Set<String> requirePackages) throws FileNotFoundException, IOException { 224- JarInputStream jarIn = new JarInputStream(new FileInputStream(src)); 225- JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(dst), jarIn.getManifest()); 226- JarEntry entryIn; 227- while((entryIn = jarIn.getNextJarEntry()) != null) { 228- String name = entryIn.getName(); 229- String pkg = null; 230- boolean required = false;; 231- int i = name.lastIndexOf('/'); 232- if(i > 0) { 233- pkg = name.substring(0, i); 234- for(String p : requirePackages) { 235- if(p.endsWith("/*")) { 236- p = p.substring(0, p.length() - 2); 237- if(pkg.startsWith(p)) { 238- required = true; 239- break; 240- } 241- } else if(p.equals(pkg)) { 242- required = true; 243- break; 244- } 245- } 246- } 247- 248- if(!required && name.endsWith(".class") && !requiredClassEntryNames.contains(name)) { 249- continue; 250- } 251- JarEntry entryOut = new JarEntry(name); 252- entryOut.setMethod(JarEntry.DEFLATED); 253- jarOut.putNextEntry(entryOut); 254- byte[] data = getBytes(jarIn); 255- jarIn.closeEntry(); 256- jarOut.write(data); 257- jarOut.flush(); 258- jarOut.closeEntry(); 259- } 260- jarIn.close(); 261- jarOut.flush(); 262- jarOut.finish(); 263- jarOut.close(); 264- } 265- 266- private static byte[] getBytes(InputStream in) throws IOException { 267- ByteArrayOutputStream out = new ByteArrayOutputStream(); 268- byte[] buf = new byte[65536]; 269- int size; 270- while((size = in.read(buf)) != -1) { 271- out.write(buf, 0, size); 272- } 273- return out.toByteArray(); 274- } 275- 276- public static List<File> getRequiredFiles(File jre, Set<String> appends) { 277- List<File> list = new ArrayList<File>(); 278- traverseRequiredFiles(list, jre, appends); 279- return list; 280- } 281- 282- private static void traverseRequiredFiles(List<File> list, File dir, Set<String> appends) { 283- for(File file : dir.listFiles()) { 284- if(file.isDirectory()) { 285- traverseRequiredFiles(list, file, appends); 286- } else { 287- if(appends != null && appends.contains(file.getName().toLowerCase())) { 288- list.add(file); 289- continue; 290- } 291- if(requiredFiles.contains(file.getName().toLowerCase())) { 292- list.add(file); 293- continue; 294- } 295- } 296- } 297- } 298- 299- public static Set<String> getRequiredClassEntryNames() throws IOException { 300- Set<String> set = new HashSet<String>(); 301- InputStream in = JreMin.class.getResourceAsStream("classes.txt"); 302- if(in != null) { 303- BufferedReader r = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8"))); 304- String line; 305- while((line = r.readLine()) != null) { 306- String name = line.replace('.', '/') + ".class"; 307- set.add(name); 308- } 309- r.close(); 310- } 311- in.close(); 312- return set; 313- } 314- 315- public static void debugOut(Trace trace) throws Exception { 316- Writer w; 317- List<String> list; 318- 319- w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("classes.txt"), Charset.forName("UTF-8"))); 320- list = new ArrayList<String>(); 321- for(String s : trace.getRequiredClassEntryNames()) { 322- if(s.endsWith(".class")) { 323- list.add(s.substring(0, s.length() - 6).replace('/', '.')); 324- } 325- }; 326- Collections.sort(list); 327- for(String line : list) { 328- w.write(line); 329- w.write("\r\n"); 330- } 331- w.close(); 332- 333- w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("packages.txt"), Charset.forName("UTF-8"))); 334- list = new ArrayList<String>(); 335- for(String s : trace.getPackages()) { 336- list.add(s.replace('/', '.')); 337- }; 338- Collections.sort(list); 339- for(String line : list) { 340- w.write(line); 341- w.write("\r\n"); 342- } 343- w.close(); 344- } 345-} --- exewrap/trunk/exewrap/src/java/exewrap/core/ExewrapClassLoader.java (revision 38) +++ exewrap/trunk/exewrap/src/java/exewrap/core/ExewrapClassLoader.java (revision 39) @@ -21,36 +21,38 @@ 2121 2222 public class ExewrapClassLoader extends ClassLoader { 2323 24- private Map<String, byte[]> classes = new HashMap<String, byte[]>(); 25- private Map<String, byte[]> resources = new HashMap<String, byte[]>(); 26- private Queue<JarInputStream> inputs = new LinkedList<JarInputStream>(); 27- private JarInputStream in; 28- private String mainClassName; 29- private String specTitle; 30- private String specVersion; 31- private String specVendor; 32- private String implTitle; 33- private String implVersion; 34- private String implVendor; 35- private URL context; 36- private ProtectionDomain protectionDomain; 37- 38- public ExewrapClassLoader(ClassLoader parent, JarInputStream[] inputs) throws MalformedURLException { 39- super(parent); 40- for(JarInputStream in : inputs) { 41- Manifest manifest = in.getManifest(); 24+ private static Map<String, byte[]> classes = new HashMap<String, byte[]>(); 25+ private static Map<String, byte[]> resources = new HashMap<String, byte[]>(); 26+ private static Queue<JarInputStream> inputs = new LinkedList<JarInputStream>(); 27+ private static JarInputStream in; 28+ private static String mainClassName; 29+ private static String specTitle; 30+ private static String specVersion; 31+ private static String specVendor; 32+ private static String implTitle; 33+ private static String implVersion; 34+ private static String implVendor; 35+ private static URL context; 36+ private static ProtectionDomain protectionDomain; 37+ 38+ public static void setInputs(JarInputStream[] jars) throws MalformedURLException { 39+ for(JarInputStream jar : jars) { 40+ if(jar == null) { 41+ continue; 42+ } 43+ Manifest manifest = jar.getManifest(); 4244 if(manifest != null) { 43- this.mainClassName = manifest.getMainAttributes().getValue(Name.MAIN_CLASS); 44- this.specTitle = manifest.getMainAttributes().getValue(Name.SPECIFICATION_TITLE); 45- this.specVersion = manifest.getMainAttributes().getValue(Name.SPECIFICATION_VERSION); 46- this.specVendor = manifest.getMainAttributes().getValue(Name.SPECIFICATION_VENDOR); 47- this.implTitle = manifest.getMainAttributes().getValue(Name.IMPLEMENTATION_TITLE); 48- this.implVersion = manifest.getMainAttributes().getValue(Name.IMPLEMENTATION_VERSION); 49- this.implVendor = manifest.getMainAttributes().getValue(Name.IMPLEMENTATION_VENDOR); 45+ mainClassName = manifest.getMainAttributes().getValue(Name.MAIN_CLASS); 46+ specTitle = manifest.getMainAttributes().getValue(Name.SPECIFICATION_TITLE); 47+ specVersion = manifest.getMainAttributes().getValue(Name.SPECIFICATION_VERSION); 48+ specVendor = manifest.getMainAttributes().getValue(Name.SPECIFICATION_VENDOR); 49+ implTitle = manifest.getMainAttributes().getValue(Name.IMPLEMENTATION_TITLE); 50+ implVersion = manifest.getMainAttributes().getValue(Name.IMPLEMENTATION_VERSION); 51+ implVendor = manifest.getMainAttributes().getValue(Name.IMPLEMENTATION_VENDOR); 5052 } 51- this.inputs.offer(in); 53+ inputs.offer(jar); 5254 } 53- this.in = this.inputs.poll(); 55+ in = inputs.poll(); 5456 5557 String path = System.getProperty("java.application.path"); 5658 if(path == null) { @@ -61,54 +63,63 @@ 6163 name = ""; 6264 } 6365 64- URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory(this)); 65- this.context = new URL("exewrap:file:/" + path.replace('\\', '/') + '/' + name + "!/"); 66+ ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); 67+ URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory(systemClassLoader)); 68+ context = new URL("exewrap:file:/" + path.replace('\\', '/') + '/' + name + "!/"); 6669 6770 URL url = new URL("file:/" + path.replace('\\', '/') + '/' + name); 6871 CodeSource codesource = new CodeSource(url, (Certificate[])null); 6972 PermissionCollection permissions = Policy.getPolicy().getPermissions(new CodeSource(null, (Certificate[])null)); 70- this.protectionDomain = new ProtectionDomain(codesource, permissions, this, null); 73+ protectionDomain = new ProtectionDomain(codesource, permissions, systemClassLoader, null); 7174 } 7275 73- public void register() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { 74- Thread.currentThread().setContextClassLoader(this); 75- } 76- 77- public void loadUtilities(String utilities) throws ClassNotFoundException { 76+ public static void loadUtilities(String utilities) throws ClassNotFoundException { 7877 if(utilities == null) { 7978 return; 8079 } 8180 if(utilities.contains("UncaughtExceptionHandler;")) { 82- Class.forName("exewrap.util.UncaughtExceptionHandler", true, this); 81+ Class.forName("exewrap.util.UncaughtExceptionHandler"); 8382 } 8483 if(utilities.contains("FileLogStream;")) { 85- Class.forName("exewrap.util.FileLogStream", true, this); 84+ Class.forName("exewrap.util.FileLogStream"); 8685 } 8786 if(utilities.contains("EventLogStream;")) { 88- Class.forName("exewrap.util.EventLogStream", true, this); 87+ Class.forName("exewrap.util.EventLogStream"); 8988 } 9089 if(utilities.contains("EventLogHandler;")) { 91- Class.forName("exewrap.util.EventLogHandler", true, this); 90+ Class.forName("exewrap.util.EventLogHandler"); 9291 } 9392 if(utilities.contains("ConsoleOutputStream;")) { 94- Class.forName("exewrap.util.ConsoleOutputStream", true, this); 93+ Class.forName("exewrap.util.ConsoleOutputStream"); 9594 } 9695 } 9796 98- public Class<?> getMainClass(String mainClassName) throws ClassNotFoundException { 97+ public static Class<?> getMainClass(String mainClassName) throws ClassNotFoundException { 98+ ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); 99+ 99100 if(mainClassName != null) { 100- return loadClass(mainClassName); 101+ return Class.forName(mainClassName, true, systemClassLoader); 101102 } 102- if(this.mainClassName != null) { 103- return loadClass(this.mainClassName); 103+ if(ExewrapClassLoader.mainClassName != null) { 104+ return Class.forName(ExewrapClassLoader.mainClassName, true, systemClassLoader); 104105 } 105106 return null; 106107 } 107108 108- public void setSplashScreenResource(String name, byte[] image) { 109- this.resources.put(name, image); 109+ public static void setSplashScreenResource(String name, byte[] image) { 110+ resources.put(name, image); 110111 } 111112 113+ public static native void WriteConsole(byte[] b, int off, int len); 114+ public static native void WriteEventLog(int type, String message); 115+ public static native void UncaughtException(String thread, String message, String trace); 116+ public static native String SetEnvironment(String key, String value); 117+ 118+ 119+ public ExewrapClassLoader(ClassLoader parent) { 120+ super(parent); 121+ } 122+ 112123 protected Class<?> findClass(String name) throws ClassNotFoundException { 113124 String entryName = name.replace('.', '/') + ".class"; 114125 byte[] bytes = this.classes.remove(entryName); @@ -193,9 +204,4 @@ 193204 } 194205 return buf.toByteArray(); 195206 } 196- 197- public static native void WriteConsole(byte[] b, int off, int len); 198- public static native void WriteEventLog(int type, String message); 199- public static native void UncaughtException(String thread, String message, String trace); 200- public static native String SetEnvironment(String key, String value); 201207 } --- exewrap/trunk/exewrap/src/java/exewrap/tool/JarOptimizer.java (revision 38) +++ exewrap/trunk/exewrap/src/java/exewrap/tool/JarOptimizer.java (nonexistent) @@ -1,141 +0,0 @@ 1-import java.io.ByteArrayInputStream; 2-import java.io.ByteArrayOutputStream; 3-import java.io.FileInputStream; 4-import java.util.Arrays; 5-import java.util.jar.JarEntry; 6-import java.util.jar.JarInputStream; 7-import java.util.jar.JarOutputStream; 8-import java.util.jar.Manifest; 9-import java.util.jar.Pack200; 10-import java.util.jar.Pack200.Packer; 11-import java.util.zip.CRC32; 12-import java.util.zip.GZIPOutputStream; 13- 14-public class JarOptimizer extends ClassLoader { 15- 16- private String relative_classpath = null; 17- private ByteArrayOutputStream resource_gz = new ByteArrayOutputStream(); 18- private ByteArrayOutputStream classes_pack_gz = new ByteArrayOutputStream(); 19- private String splash_path = null; 20- private byte[] splash_image = null; 21- 22- public JarOptimizer(String filename) throws Exception { 23- int resourceCount = 0; 24- int classCount = 0; 25- ByteArrayOutputStream resources = new ByteArrayOutputStream(); 26- ByteArrayOutputStream classes = new ByteArrayOutputStream(); 27- 28- JarInputStream in = new JarInputStream(new FileInputStream(filename)); 29- Manifest manifest = in.getManifest(); 30- relative_classpath = manifest.getMainAttributes().getValue("Class-Path"); 31- splash_path = manifest.getMainAttributes().getValue("SplashScreen-Image"); 32- JarOutputStream classJar = new JarOutputStream(classes, manifest); 33- JarOutputStream resourceJar = new JarOutputStream(resources); 34- 35- JarEntry inEntry; 36- byte[] buf = new byte[65536]; 37- int size; 38- while((inEntry = in.getNextJarEntry()) != null) { 39- ByteArrayOutputStream baos = new ByteArrayOutputStream(); 40- while(in.available() > 0) { 41- size = in.read(buf); 42- if(size > 0) { 43- baos.write(buf, 0, size); 44- } 45- } 46- byte[] data = baos.toByteArray(); 47- if(inEntry.getName().equals(this.splash_path)) { 48- this.splash_image = data; 49- } else if(inEntry.getName().toLowerCase().endsWith(".class")) { 50- CRC32 crc = new CRC32(); 51- crc.update(data); 52- 53- JarEntry outEntry = new JarEntry(inEntry.getName()); 54- outEntry.setMethod(JarEntry.STORED); 55- outEntry.setSize(data.length); 56- outEntry.setCrc(crc.getValue()); 57- 58- classJar.putNextEntry(outEntry); 59- classJar.write(data); 60- classJar.closeEntry(); 61- classCount++; 62- } else { 63- /* 64- String resourceEntryName; 65- if(inEntry.getName().length() > 1 && inEntry.getName().charAt(0) == '/' && inEntry.getName().charAt(1) != '/') { 66- resourceEntryName = inEntry.getName().substring(1); 67- } else { 68- resourceEntryName = inEntry.getName(); 69- } 70- */ 71- CRC32 crc = new CRC32(); 72- crc.update(data); 73- 74- //JarEntry outEntry = new JarEntry(resourceEntryName); 75- JarEntry outEntry = new JarEntry(inEntry.getName()); 76- outEntry.setMethod(JarEntry.STORED); 77- outEntry.setSize(data.length); 78- outEntry.setCrc(crc.getValue()); 79- 80- resourceJar.putNextEntry(outEntry); 81- resourceJar.write(data); 82- resourceJar.closeEntry(); 83- resourceCount++; 84- } 85- in.closeEntry(); 86- } 87- in.close(); 88- if(resourceCount > 0) { 89- resourceJar.close(); 90- GZIPOutputStream gzout = new GZIPOutputStream(resource_gz); 91- gzout.write(resources.toByteArray()); 92- gzout.flush(); 93- gzout.finish(); 94- gzout.close(); 95- } 96- if(classCount > 0) { 97- classJar.close(); 98- Packer packer = Pack200.newPacker(); 99- GZIPOutputStream gzout = new GZIPOutputStream(classes_pack_gz); 100- in = new JarInputStream(new ByteArrayInputStream(classes.toByteArray())); 101- packer.pack(in, gzout); 102- gzout.flush(); 103- gzout.finish(); 104- gzout.close(); 105- in.close(); 106- } 107- } 108- 109- public byte[] getRelativeClassPath() { 110- if(this.relative_classpath != null) { 111- byte[] buf = this.relative_classpath.replaceAll("/", "\\\\").getBytes(); 112- return Arrays.copyOf(buf, buf.length + 2); 113- } 114- return null; 115- } 116- 117- public byte[] getClassesPackGz() { 118- if(this.classes_pack_gz.size() > 0) { 119- return this.classes_pack_gz.toByteArray(); 120- } 121- return null; 122- } 123- 124- public byte[] getResourcesGz() { 125- if(this.resource_gz.size() > 0) { 126- return this.resource_gz.toByteArray(); 127- } 128- return null; 129- } 130- 131- public byte[] getSplashPath() { 132- if(this.splash_path != null) { 133- return this.splash_path.getBytes(); 134- } 135- return null; 136- } 137- 138- public byte[] getSplashImage() { 139- return this.splash_image; 140- } 141-} --- exewrap/trunk/exewrap/src/jvm.c (revision 38) +++ exewrap/trunk/exewrap/src/jvm.c (revision 39) @@ -9,7 +9,7 @@ 99 1010 void InitializePath(char* relative_classpath, char* relative_extdirs, BOOL useServerVM, BOOL useSideBySideJRE); 1111 int GetProcessArchitecture(); 12-JNIEnv* CreateJavaVM(LPTSTR vm_args_opt, BOOL useServerVM, BOOL useSideBySideJRE, int* err); 12+JNIEnv* CreateJavaVM(LPTSTR vm_args_opt, LPTSTR systemClassLoader, BOOL useServerVM, BOOL useSideBySideJRE, int* err); 1313 void DestroyJavaVM(); 1414 JNIEnv* AttachJavaVM(); 1515 void DetachJavaVM(); @@ -39,6 +39,7 @@ 3939 JNIEnv* env = NULL; 4040 DWORD javaRuntimeVersion = 0xFFFFFFFF; 4141 42+char opt_system_class_loader[512]; 4243 char opt_app_path[MAX_PATH + 32]; 4344 char opt_app_name[MAX_PATH + 32]; 4445 char opt_app_version[64]; @@ -58,7 +59,7 @@ 5859 return sizeof(int*) * 8; 5960 } 6061 61-JNIEnv* CreateJavaVM(LPTSTR vm_args_opt, BOOL useServerVM, BOOL useSideBySideJRE, int* err) 62+JNIEnv* CreateJavaVM(LPTSTR vm_args_opt, LPTSTR systemClassLoader, BOOL useServerVM, BOOL useSideBySideJRE, int* err) 6263 { 6364 JNIGetDefaultJavaVMInitArgs getDefaultJavaVMInitArgs; 6465 JNICreateJavaVM createJavaVM; @@ -98,6 +99,13 @@ 9899 vm_args.options = options; 99100 vm_args.nOptions = 5; 100101 vm_args.ignoreUnrecognized = 1; 102+ 103+ if(systemClassLoader != NULL) 104+ { 105+ lstrcpy(opt_system_class_loader, "-Djava.system.class.loader="); 106+ lstrcat(opt_system_class_loader, systemClassLoader); 107+ options[vm_args.nOptions++].optionString = opt_system_class_loader; 108+ } 101109 102110 if(opt_policy_path[0] != 0x00) 103111 { @@ -111,6 +119,13 @@ 111119 options[vm_args.nOptions++].optionString = argv[i]; 112120 } 113121 122+ /* 123+ for(i = 0; i < vm_args.nOptions; i++) 124+ { 125+ printf("[%d] %s\n\n", i, options[i].optionString); 126+ } 127+ */ 128+ 114129 getDefaultJavaVMInitArgs(&vm_args); 115130 result = createJavaVM(&jvm, (void**)&env, &vm_args); 116131 if(err != NULL) @@ -317,6 +332,7 @@ 317332 318333 void InitializePath(char* relative_classpath, char* relative_extdirs, BOOL useServerVM, BOOL useSideBySideJRE) { 319334 char modulePath[_MAX_PATH]; 335+ char moduleFileFullPath[_MAX_PATH]; 320336 char* buffer; 321337 char* token; 322338 DWORD size = MAX_PATH; @@ -354,9 +370,9 @@ 354370 lstrcpy(opt_policy_path, "-Djava.security.policy="); 355371 lstrcat(opt_policy_path, modulePath); 356372 357- GetModuleFileName(NULL, buffer, size); 373+ GetModuleFileName(NULL, moduleFileFullPath, MAX_PATH); 358374 lstrcpy(opt_app_name, "-Djava.application.name="); 359- lstrcat(opt_app_name, strrchr(buffer, '\\') + 1); 375+ lstrcat(opt_app_name, strrchr(moduleFileFullPath, '\\') + 1); 360376 361377 lstrcat(opt_policy_path, "\\"); 362378 *(strrchr(buffer, '.')) = 0; @@ -504,6 +520,8 @@ 504520 } 505521 506522 lstrcpy(classpath, "-Djava.class.path="); 523+ lstrcat(classpath, moduleFileFullPath); 524+ lstrcat(classpath, ";"); 507525 lstrcpy(libpath, "-Djava.library.path=.;"); 508526 509527 if(relative_classpath != NULL) --- exewrap/trunk/exewrap/src/loader.c (revision 38) +++ exewrap/trunk/exewrap/src/loader.c (revision 39) @@ -33,7 +33,6 @@ 3333 extern UINT UncaughtException(const char* thread, const char* message, const char* trace); 3434 3535 static jclass ExewrapClassLoader = NULL; 36-static jobject exewrapClassLoader = NULL; 3736 static jclass MainClass = NULL; 3837 static jmethodID MainClass_main = NULL; 3938 @@ -40,63 +39,21 @@ 4039 BOOL LoadMainClass(int argc, char* argv[], char* utilities, LOAD_RESULT* result) 4140 { 4241 RESOURCE res; 43- jclass ClassLoader; 44- jmethodID ClassLoader_getSystemClassLoader; 45- jmethodID ClassLoader_definePackage; 46- jobject systemClassLoader; 4742 jclass JarInputStream; 4843 jmethodID JarInputStream_init; 4944 jclass ByteBufferInputStream; 5045 jmethodID ByteBufferInputStream_init; 5146 jobjectArray jars; 52- jclass URLConnection; 53- jclass URLStreamHandler; 54- jclass URLStreamHandlerFactory; 55- jmethodID ExewrapClassLoader_init; 56- jmethodID exewrapClassLoader_register; 57- jmethodID exewrapClassLoader_loadUtilities; 58- jmethodID exewrapClassLoader_getMainClass; 47+ jmethodID ExewrapClassLoader_setInputs; 48+ jmethodID ExewrapClassLoader_loadUtilities; 49+ jmethodID ExewrapClassLoader_getMainClass; 5950 60- // ClassLoader 61- ClassLoader = (*env)->FindClass(env, "java/lang/ClassLoader"); 62- if (ClassLoader == NULL) 63- { 64- result->msg_id = MSG_ID_ERR_DEFINE_CLASS; 65- sprintf(result->msg, _(MSG_ID_ERR_DEFINE_CLASS), "java.lang.ClassLoader"); 66- goto EXIT; 67- } 68- ClassLoader_definePackage = (*env)->GetMethodID(env, ClassLoader, "definePackage", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/net/URL;)Ljava/lang/Package;"); 69- if (ClassLoader_definePackage == NULL) 70- { 71- result->msg_id = MSG_ID_ERR_GET_METHOD; 72- sprintf(result->msg, _(MSG_ID_ERR_GET_METHOD), "java.lang.ClassLoader.definePackage(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.net.URL)"); 73- goto EXIT; 74- } 75- ClassLoader_getSystemClassLoader = (*env)->GetStaticMethodID(env, ClassLoader, "getSystemClassLoader", "()Ljava/lang/ClassLoader;"); 76- if (ClassLoader_getSystemClassLoader == NULL) 77- { 78- result->msg_id = MSG_ID_ERR_GET_METHOD; 79- sprintf(result->msg, _(MSG_ID_ERR_GET_METHOD), "java.lang.ClassLoader.getSystemClassLoader()"); 80- goto EXIT; 81- } 82- systemClassLoader = (*env)->CallStaticObjectMethod(env, ClassLoader, ClassLoader_getSystemClassLoader); 83- if (systemClassLoader == NULL) 84- { 85- //ignore 86- } 87- else 88- { 89- // Define package "exewrap.core" 90- jstring packageName = GetJString(env, "exewrap.core"); 91- (*env)->CallObjectMethod(env, systemClassLoader, ClassLoader_definePackage, packageName, NULL, NULL, NULL, NULL, NULL, NULL, NULL); 92- } 93- 9451 // JarInputStream 9552 JarInputStream = (*env)->FindClass(env, "java/util/jar/JarInputStream"); 9653 if (JarInputStream == NULL) 9754 { 98- result->msg_id = MSG_ID_ERR_DEFINE_CLASS; 99- sprintf(result->msg, _(MSG_ID_ERR_DEFINE_CLASS), "java.util.jar.JarInputStream"); 55+ result->msg_id = MSG_ID_ERR_FIND_CLASS; 56+ sprintf(result->msg, _(MSG_ID_ERR_FIND_CLASS), "java.util.jar.JarInputStream"); 10057 goto EXIT; 10158 } 10259 JarInputStream_init = (*env)->GetMethodID(env, JarInputStream, "<init>", "(Ljava/io/InputStream;)V"); @@ -108,17 +65,11 @@ 10865 } 10966 11067 // ByteBufferInputStream 111- if (GetResource("BYTE_BUFFER_INPUT_STREAM", &res) == NULL) 112- { 113- result->msg_id = MSG_ID_ERR_RESOURCE_NOT_FOUND; 114- sprintf(result->msg, _(MSG_ID_ERR_RESOURCE_NOT_FOUND), "RT_RCDATA: BYTE_BUFFER_INPUT_STREAM"); 115- goto EXIT; 116- } 117- ByteBufferInputStream = (*env)->DefineClass(env, "exewrap/core/ByteBufferInputStream", systemClassLoader, res.buf, res.len); 68+ ByteBufferInputStream = (*env)->FindClass(env, "exewrap/core/ByteBufferInputStream"); 11869 if (ByteBufferInputStream == NULL) 11970 { 120- result->msg_id = MSG_ID_ERR_DEFINE_CLASS; 121- sprintf(result->msg, _(MSG_ID_ERR_DEFINE_CLASS), "exewrap.core.ByteBufferInputStream"); 71+ result->msg_id = MSG_ID_ERR_FIND_CLASS; 72+ sprintf(result->msg, _(MSG_ID_ERR_FIND_CLASS), "exewrap.core.ByteBufferInputStream"); 12273 goto EXIT; 12374 } 12475 ByteBufferInputStream_init = (*env)->GetMethodID(env, ByteBufferInputStream, "<init>", "(Ljava/nio/ByteBuffer;)V"); @@ -129,8 +80,8 @@ 12980 goto EXIT; 13081 } 13182 132- // JarInputStream[] jars = new JarInputStream[2]; 133- jars = (*env)->NewObjectArray(env, 2, JarInputStream, NULL); 83+ // JarInputStream[] jars = new JarInputStream[1]; 84+ jars = (*env)->NewObjectArray(env, 1, JarInputStream, NULL); 13485 if (jars == NULL) 13586 { 13687 result->msg_id = MSG_ID_ERR_NEW_OBJECT; @@ -138,42 +89,6 @@ 13889 goto EXIT; 13990 } 14091 141- //util.jar 142- { 143- jobject byteBuffer; 144- jobject byteBufferInputStream = NULL; 145- jobject jarInputStream = NULL; 146- 147- if (GetResource("UTIL_JAR", &res) == NULL) 148- { 149- result->msg_id = MSG_ID_ERR_RESOURCE_NOT_FOUND; 150- sprintf(result->msg, _(MSG_ID_ERR_RESOURCE_NOT_FOUND), "RT_RCDATA: UTIL_JAR"); 151- goto EXIT; 152- } 153- byteBuffer = (*env)->NewDirectByteBuffer(env, res.buf, res.len); 154- if (byteBuffer == NULL) 155- { 156- result->msg_id = MSG_ID_ERR_NEW_OBJECT; 157- sprintf(result->msg, _(MSG_ID_ERR_NEW_OBJECT), "NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity)"); 158- goto EXIT; 159- } 160- byteBufferInputStream = (*env)->NewObject(env, ByteBufferInputStream, ByteBufferInputStream_init, byteBuffer); 161- if (byteBufferInputStream == NULL) 162- { 163- result->msg_id = MSG_ID_ERR_NEW_OBJECT; 164- sprintf(result->msg, _(MSG_ID_ERR_NEW_OBJECT), "exewrap.core.ByteBufferInputStream(java.nio.ByteBuffer)"); 165- goto EXIT; 166- } 167- jarInputStream = (*env)->NewObject(env, JarInputStream, JarInputStream_init, byteBufferInputStream); 168- if (jarInputStream == NULL) 169- { 170- result->msg_id = MSG_ID_ERR_NEW_OBJECT; 171- sprintf(result->msg, _(MSG_ID_ERR_NEW_OBJECT), "java.util.jar.JarInputStream(exewrap.core.ByteBufferInputStream)"); 172- goto EXIT; 173- } 174- (*env)->SetObjectArrayElement(env, jars, 0, jarInputStream); 175- } 176- 17792 // user.jar or user.pack.gz 17893 { 17994 BOOL isPackGz = TRUE; @@ -218,8 +133,8 @@ 218133 GZIPInputStream = (*env)->FindClass(env, "java/util/zip/GZIPInputStream"); 219134 if (GZIPInputStream == NULL) 220135 { 221- result->msg_id = MSG_ID_ERR_DEFINE_CLASS; 222- sprintf(result->msg, _(MSG_ID_ERR_DEFINE_CLASS), "java.util.zip.GZIPInputStream"); 136+ result->msg_id = MSG_ID_ERR_FIND_CLASS; 137+ sprintf(result->msg, _(MSG_ID_ERR_FIND_CLASS), "java.util.zip.GZIPInputStream"); 223138 goto EXIT; 224139 } 225140 GZIPInputStream_init = (*env)->GetMethodID(env, GZIPInputStream, "<init>", "(Ljava/io/InputStream;)V"); @@ -238,17 +153,11 @@ 238153 } 239154 240155 // PackInputStream 241- if (GetResource("PACK_INPUT_STREAM", &res) == NULL) 242- { 243- result->msg_id = MSG_ID_ERR_RESOURCE_NOT_FOUND; 244- sprintf(result->msg, _(MSG_ID_ERR_RESOURCE_NOT_FOUND), "RT_RCDATA: PACK_INPUT_STREAM"); 245- goto EXIT; 246- } 247- PackInputStream = (*env)->DefineClass(env, "exewrap/core/PackInputStream", systemClassLoader, res.buf, res.len); 156+ PackInputStream = (*env)->FindClass(env, "exewrap/core/PackInputStream"); 248157 if (PackInputStream == NULL) 249158 { 250- result->msg_id = MSG_ID_ERR_DEFINE_CLASS; 251- sprintf(result->msg, _(MSG_ID_ERR_DEFINE_CLASS), "exewrap.core.PackInputStream"); 159+ result->msg_id = MSG_ID_ERR_FIND_CLASS; 160+ sprintf(result->msg, _(MSG_ID_ERR_FIND_CLASS), "exewrap.core.PackInputStream"); 252161 goto EXIT; 253162 } 254163 PackInputStream_init = (*env)->GetMethodID(env, PackInputStream, "<init>", "(Ljava/io/InputStream;)V"); @@ -286,65 +195,18 @@ 286195 goto EXIT; 287196 } 288197 } 289- (*env)->SetObjectArrayElement(env, jars, 1, jarInputStream); 198+ (*env)->SetObjectArrayElement(env, jars, 0, jarInputStream); 290199 } 291- 292- // URLConnection 293- if (GetResource("URL_CONNECTION", &res) == NULL) 294- { 295- result->msg_id = MSG_ID_ERR_RESOURCE_NOT_FOUND; 296- sprintf(result->msg, _(MSG_ID_ERR_RESOURCE_NOT_FOUND), "RT_RCDATA: URL_CONNECTION"); 297- goto EXIT; 298- } 299- URLConnection = (*env)->DefineClass(env, "exewrap/core/URLConnection", systemClassLoader, res.buf, res.len); 300- if (URLConnection == NULL) 301- { 302- result->msg_id = MSG_ID_ERR_DEFINE_CLASS; 303- sprintf(result->msg, _(MSG_ID_ERR_DEFINE_CLASS), "exewrap.core.URLConnection"); 304- goto EXIT; 305- } 306- // URLStreamHandler 307- if (GetResource("URL_STREAM_HANDLER", &res) == NULL) 308- { 309- result->msg_id = MSG_ID_ERR_RESOURCE_NOT_FOUND; 310- sprintf(result->msg, _(MSG_ID_ERR_RESOURCE_NOT_FOUND), "RT_RCDATA: URL_STREAM_HANDLER"); 311- goto EXIT; 312- } 313- URLStreamHandler = (*env)->DefineClass(env, "exewrap/core/URLStreamHandler", systemClassLoader, res.buf, res.len); 314- if (URLStreamHandler == NULL) 315- { 316- result->msg_id = MSG_ID_ERR_DEFINE_CLASS; 317- sprintf(result->msg, _(MSG_ID_ERR_DEFINE_CLASS), "exewrap.core.URLStreamHandler"); 318- goto EXIT; 319- } 320- // URLStreamHandlerFactory 321- if (GetResource("URL_STREAM_HANDLER_FACTORY", &res) == NULL) 322- { 323- result->msg_id = MSG_ID_ERR_RESOURCE_NOT_FOUND; 324- sprintf(result->msg, _(MSG_ID_ERR_RESOURCE_NOT_FOUND), "RT_RCDATA: URL_STREAM_HANDLER_FACTORY"); 325- goto EXIT; 326- } 327- URLStreamHandlerFactory = (*env)->DefineClass(env, "exewrap/core/URLStreamHandlerFactory", systemClassLoader, res.buf, res.len); 328- if (URLStreamHandlerFactory == NULL) 329- { 330- result->msg_id = MSG_ID_ERR_DEFINE_CLASS; 331- sprintf(result->msg, _(MSG_ID_ERR_DEFINE_CLASS), "exewrap.core.URLStreamHandlerFactory"); 332- goto EXIT; 333- } 200+ 334201 // ExewrapClassLoader 335- if (GetResource("EXEWRAP_CLASS_LOADER", &res) == NULL) 336- { 337- result->msg_id = MSG_ID_ERR_RESOURCE_NOT_FOUND; 338- sprintf(result->msg, _(MSG_ID_ERR_RESOURCE_NOT_FOUND), "RT_RCDATA: EXEWRAP_CLASS_LOADER"); 339- goto EXIT; 340- } 341- ExewrapClassLoader = (*env)->DefineClass(env, "exewrap/core/ExewrapClassLoader", systemClassLoader, res.buf, res.len); 202+ ExewrapClassLoader = (*env)->FindClass(env, "exewrap/core/ExewrapClassLoader"); 342203 if (ExewrapClassLoader == NULL) 343204 { 344- result->msg_id = MSG_ID_ERR_DEFINE_CLASS; 345- sprintf(result->msg, _(MSG_ID_ERR_DEFINE_CLASS), "exewrap.core.ExewrapClassLoader"); 205+ result->msg_id = MSG_ID_ERR_FIND_CLASS; 206+ sprintf(result->msg, _(MSG_ID_ERR_FIND_CLASS), "exewrap.core.ExewrapClassLoader"); 346207 goto EXIT; 347208 } 209+ 348210 // register native methods 349211 if (register_native(env, ExewrapClassLoader, "WriteConsole", "([BII)V", JNI_WriteConsole) != 0) 350212 { @@ -370,55 +232,39 @@ 370232 sprintf(result->msg, _(MSG_ID_ERR_REGISTER_NATIVE), "SetEnvironment"); 371233 goto EXIT; 372234 } 373- // Create ExewrapClassLoader instance 374- ExewrapClassLoader_init = (*env)->GetMethodID(env, ExewrapClassLoader, "<init>", "(Ljava/lang/ClassLoader;[Ljava/util/jar/JarInputStream;)V"); 375- if (ExewrapClassLoader_init == NULL) 235+ 236+ ExewrapClassLoader_setInputs = (*env)->GetStaticMethodID(env, ExewrapClassLoader, "setInputs", "([Ljava/util/jar/JarInputStream;)V"); 237+ if (ExewrapClassLoader_setInputs == NULL) 376238 { 377- result->msg_id = MSG_ID_ERR_GET_CONSTRUCTOR; 378- sprintf(result->msg, _(MSG_ID_ERR_GET_CONSTRUCTOR), "exewrap.core.ExewrapClassLoader(java.lang.ClassLoader, java.util.jar.JarInputStream[])"); 379- goto EXIT; 380- } 381- // ExewrapClassLoader exewrarpClassLoader = new ExewrapClassLoader(ClassLoader.getSystemClasssLoader()); 382- exewrapClassLoader = (*env)->NewObject(env, ExewrapClassLoader, ExewrapClassLoader_init, systemClassLoader, jars); 383- if (exewrapClassLoader == NULL) 384- { 385- result->msg_id = MSG_ID_ERR_NEW_OBJECT; 386- sprintf(result->msg, _(MSG_ID_ERR_NEW_OBJECT), "exewrap.core.ExewrapClassLoader(java.lang.ClassLoader, java.util.jar.JarInputStream[])"); 387- goto EXIT; 388- } 389- exewrapClassLoader_register = (*env)->GetMethodID(env, ExewrapClassLoader, "register", "()V"); 390- if (exewrapClassLoader_register == NULL) 391- { 392239 result->msg_id = MSG_ID_ERR_GET_METHOD; 393- sprintf(result->msg, _(MSG_ID_ERR_GET_METHOD), "exewrap.core.ExewrapClassLoader.register()"); 240+ sprintf(result->msg, _(MSG_ID_ERR_GET_METHOD), "exewrap.core.ExewrapClassLoader.setInputs(java.util.jar.JarInputStream[])"); 394241 goto EXIT; 395242 } 396- exewrapClassLoader_loadUtilities = (*env)->GetMethodID(env, ExewrapClassLoader, "loadUtilities", "(Ljava/lang/String;)V"); 397- if (exewrapClassLoader_loadUtilities == NULL) 243+ (*env)->CallStaticObjectMethod(env, ExewrapClassLoader, ExewrapClassLoader_setInputs, jars); 244+ 245+ 246+ ExewrapClassLoader_loadUtilities = (*env)->GetStaticMethodID(env, ExewrapClassLoader, "loadUtilities", "(Ljava/lang/String;)V"); 247+ if (ExewrapClassLoader_loadUtilities == NULL) 398248 { 399249 result->msg_id = MSG_ID_ERR_GET_METHOD; 400250 sprintf(result->msg, _(MSG_ID_ERR_GET_METHOD), "exewrap.core.ExewrapClassLoader.loadUtilities(java.lang.String)"); 401251 goto EXIT; 402252 } 403- 404- // exewrapClassLoader.register(); 405- (*env)->CallObjectMethod(env, exewrapClassLoader, exewrapClassLoader_register); 406- 407253 // exewrapClassLoader.loadUtilities(); 408254 { 409255 jstring s = GetJString(env, utilities); 410- (*env)->CallObjectMethod(env, exewrapClassLoader, exewrapClassLoader_loadUtilities, s); 256+ (*env)->CallStaticObjectMethod(env, ExewrapClassLoader, ExewrapClassLoader_loadUtilities, s); 411257 } 412258 413259 // MainClass 414- exewrapClassLoader_getMainClass = (*env)->GetMethodID(env, ExewrapClassLoader, "getMainClass", "(Ljava/lang/String;)Ljava/lang/Class;"); 415- if (exewrapClassLoader_getMainClass == NULL) 260+ ExewrapClassLoader_getMainClass = (*env)->GetStaticMethodID(env, ExewrapClassLoader, "getMainClass", "(Ljava/lang/String;)Ljava/lang/Class;"); 261+ if (ExewrapClassLoader_getMainClass == NULL) 416262 { 417263 result->msg_id = MSG_ID_ERR_GET_METHOD; 418264 sprintf(result->msg, _(MSG_ID_ERR_GET_METHOD), "exewrap.core.ExewrapClassLoader.getMainClass(java.lang.String)"); 419265 goto EXIT; 420266 } 421- MainClass = (*env)->CallObjectMethod(env, exewrapClassLoader, exewrapClassLoader_getMainClass, GetJString(env, GetResource("MAIN_CLASS", NULL))); 267+ MainClass = (*env)->CallStaticObjectMethod(env, ExewrapClassLoader, ExewrapClassLoader_getMainClass, GetJString(env, GetResource("MAIN_CLASS", NULL))); 422268 if (MainClass == NULL) 423269 { 424270 result->msg_id = MSG_ID_ERR_LOAD_MAIN_CLASS; @@ -462,7 +308,7 @@ 462308 BOOL ret = FALSE; 463309 jstring name; 464310 jbyteArray image; 465- jmethodID exewrapClassLoader_setSplashScreenResource; 311+ jmethodID ExewrapClassLoader_setSplashScreenResource; 466312 467313 name = GetJString(env, splash_screen_name); 468314 if (name == NULL) @@ -477,13 +323,13 @@ 477323 } 478324 (*env)->SetByteArrayRegion(env, image, 0, splash_screen_image_len, splash_screen_image_buf); 479325 480- exewrapClassLoader_setSplashScreenResource = (*env)->GetMethodID(env, ExewrapClassLoader, "setSplashScreenResource", "(Ljava/lang/String;[B)V"); 481- if (exewrapClassLoader_setSplashScreenResource == NULL) 326+ ExewrapClassLoader_setSplashScreenResource = (*env)->GetStaticMethodID(env, ExewrapClassLoader, "setSplashScreenResource", "(Ljava/lang/String;[B)V"); 327+ if (ExewrapClassLoader_setSplashScreenResource == NULL) 482328 { 483329 goto EXIT; 484330 } 485331 486- (*env)->CallVoidMethod(env, exewrapClassLoader, exewrapClassLoader_setSplashScreenResource, name, image); 332+ (*env)->CallStaticVoidMethod(env, ExewrapClassLoader, ExewrapClassLoader_setSplashScreenResource, name, image); 487333 488334 ret = TRUE; 489335 --- exewrap/trunk/exewrap/src/message.c (revision 38) +++ exewrap/trunk/exewrap/src/message.c (revision 39) @@ -82,7 +82,7 @@ 8282 msg[MSG_ID_COUNT * MSG_LANG_ID_EN + MSG_ID_ERR_TARGET_VERSION] = 8383 "%s or higher is required to run this program."; 8484 85- msg[MSG_ID_COUNT * MSG_LANG_ID_EN + MSG_ID_ERR_DEFINE_CLASS] = 85+ msg[MSG_ID_COUNT * MSG_LANG_ID_EN + MSG_ID_ERR_FIND_CLASS] = 8686 "Class not found: %s"; 8787 8888 msg[MSG_ID_COUNT * MSG_LANG_ID_EN + MSG_ID_ERR_GET_CONSTRUCTOR] = @@ -182,7 +182,7 @@ 182182 msg[MSG_ID_COUNT * MSG_LANG_ID_JA + MSG_ID_ERR_TARGET_VERSION] = 183183 "このプログラムの実行には%s以上が必要です。"; 184184 185- msg[MSG_ID_COUNT * MSG_LANG_ID_JA + MSG_ID_ERR_DEFINE_CLASS] = 185+ msg[MSG_ID_COUNT * MSG_LANG_ID_JA + MSG_ID_ERR_FIND_CLASS] = 186186 "クラスが見つかりません: %s"; 187187 188188 msg[MSG_ID_COUNT * MSG_LANG_ID_JA + MSG_ID_ERR_GET_CONSTRUCTOR] = Show on old repository browser
__label__pos
0.82277
@misc{rfc7782, series = {Request for Comments}, number = 7782, howpublished = {RFC 7782}, publisher = {RFC Editor}, doi = {10.17487/RFC7782}, url = {https://rfc-editor.org/rfc/rfc7782.txt}, author = {Mingui Zhang and Radia Perlman and Hongjun Zhai and Muhammad Durrani and Sujay Gupta}, title = {{Transparent Interconnection of Lots of Links (TRILL) Active-Active Edge Using Multiple MAC Attachments}}, pagetotal = 22, year = 2016, month = feb, abstract = {TRILL (Transparent Interconnection of Lots of Links) active-active service provides end stations with flow-level load balance and resilience against link failures at the edge of TRILL campuses, as described in RFC 7379. This document specifies a method by which member RBridges (also referred to as Routing Bridges or TRILL switches) in an active-active edge RBridge group use their own nicknames as ingress RBridge nicknames to encapsulate frames from attached end systems. Thus, remote edge RBridges (who are not in the group) will see one host Media Access Control (MAC) address being associated with the multiple RBridges in the group. Such remote edge RBridges are required to maintain all those associations (i.e., MAC attachments) and to not flip-flop among them (as would occur prior to the implementation of this specification). The design goals of this specification are discussed herein.}, }
__label__pos
0.986587
Things to know about Data-Driven Architecture on cloud As data becomes more diverse and valuable, we put more emphasis on data-driven architecture. Developers need to understand the importance of accuracy, consistency, and quality of data. So they can develop quality data pipelines and products on the cloud while focusing on data. This blog explains what data is, how can we enrich our data, how can we analyse our data, and how to best use our data. We will be covering AWS Glue, AWS QuickSight, and AWS Sagemaker. Inspiration for this blog was after reading the Forbes Blog on “The Age Of Analytics And The Importance Of Data Quality”. 1. https://www.forbes.com/sites/forbesagencycouncil/2019/10/01/the-age-of-analytics-and-the-importance-of-data-quality/?sh=76cca4fa5c3c 2. https://www.freecodecamp.org/news/is-data-important-to-your-business/ Q.What is Data? Data is raw information. For example, your daily consumption of coffee. It is raw information about the amount of coffee you have consumed, but if you analyse it and gain insights from it. 1. Types of coffee beans or coffee flavour 2. How much sugar do you put into the coffee? Now that we differentiate between information and data. There are many formats to store and transfer data, these formats depend on the type of data. For example,  1. Write coffee ingredients on a piece of paper i.e unstructured  2. Write it in a .csv file i.e structured  3. A combination of both i.e semi-structured. Q.How to enrich our data? As a data engineer, you would like to maximise the insights you could gather from your data. Some data formats are developer-friendly, and some are not. So we need to convert data to developer-friendly formats, there are many ways of doing it. An example of no/low code could be AWS Glue, AWS Glue is a fully managed ETL (extract, transform, and load) service that makes it simple and cost-effective to categorise your data, clean it, enrich it, and move it reliably between various data stores and data streams. You can store your data using various AWS services and still maintain a unified view of your data using the AWS Glue Data Catalogue. Use Data Catalogue to search and discover the datasets that you own, and maintain the relevant metadata in one central repository.  Image Credits: https://d1.awsstatic.com/aws-glue-graphics/Product-page-diagram_AWS-Glue_Elixir%402x.6511bc93abc20bb7bc8d03ebe2be1cbb7f2623fe.png Q.How does AWS Glue work? You define jobs in AWS Glue to do the work that’s required to extract, transform, and load (ETL) data from a data source to a data target. You perform the following actions: 1. For datastore sources, you define a crawler to populate your AWS Glue Data Catalogue with metadata table definitions. 1. Point your crawler at a data store, and the crawler creates table definitions in the Data Catalogue.  2. AWS Glue can generate a script to transform your data or, you can provide the script in the AWS Glue console or API.( currently in Python and Scala scripts) 3. You can run your job on-demand, or you can set it up to start when a specified trigger occurs. The trigger can be a time-based schedule or an event. You use the AWS Glue console to define and orchestrate your ETL workflow. The console calls several API operations in the AWS Glue Data Catalogue and AWS Glue Jobs system to perform the following tasks: 1. Define AWS Glue objects such as jobs, tables, crawlers, and connections. 2. Schedule when crawlers run. 3. Define events or schedules for job triggers. 4. Search and filter lists of AWS Glue objects. 5. Edit transformation scripts. Image Credits: https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2018/04/17/PartitionedData2.jpg If you don’t prefer a No/Low code solution, you should try Pandas Library. Pandas library is great for data wrangling, and most of the data engineers will have experience with Pandas. For more information, feel free to listen to my session on introduction to AWS Glue where I compare No/Low code solutions to Pandas library: 1. https://www.youtube.com/watch?v=njxWiaqlErQ&t=963s Q.What to do after enriching your data? Data visualisation helps you to visualise your data as maps or graphs and interact with them. This makes it much easier for the human mind to digest the data and thus allowing it to spot patterns and trends in a much better way. This could be either done by standard business analysis tools like Tableau or R or python. A few key benefits are, 1. Identifying important trends depending on the type of visualisation can help you to determine trends over time amongst a data set.  2. Being able to spot and identify relationships within your data is key, it can help you to both drive future business decisions in the right direction and also to make corrective actions elsewhere.  3. Having a quick reference to a visualisation allows the data to collaborate with many recipients.  Image Credits: https://i.pinimg.com/originals/7a/42/8e/7a428e9a180bb7e4911d5eaab8297982.jpg There are a variety of ways to present your data, depending on what type of data you are trying to show. For each use case, there will be a specific type of chart, for example: 1. To present data that shows relationships between data points, use scatter or bubble chart. 2. To compare data between two or more data sets, use either a Bar, Column or Line chart. 3. Looking at the distribution of data across an entire data set, use a histogram. 4. Represent the part-to-whole relationship of a data set, use a pie chart, stacked column chart, 100% stacked column chart, or a treemap. Image Credits: https://az801952.vo.msecnd.net/uploads/b9335f90-bb61-4773-899e-3927c923b9be.png An example of no/low code could be AWS QuickSight Amazon QuickSight allows everyone to understand your data by asking questions in natural language, exploring through interactive dashboards, or looking for patterns and outliers powered by machine learning. Quicksight allows you to share dashboards, email reports, and embedded analytics. By taking your data and visually displaying the questions you want to answer you can gain relevant insights into your company data It allows you to draw various graphs and charts using options in User Interface. There are a lot of different options to work with. Let’s cover a few terminologies 1. Fields: These reflect the columns of the table in the database. 2. Visual Types: This is how your data will be represented. This can be from a simple sum to a chart/graph or even a heat map. 3. Sheets: These allow for many visuals to be stored together on a single page. To keep things simple, we’ll be working with only one sheet. Try changing the Visual Type of this data and see how it’s represented. You might need to add extra fields to the Field wells to make them populate correctly. Image Credits: https://d2908q01vomqb2.cloudfront.net/b6692ea5df920cad691c20319a6fffd7a4a766b8/2017/09/21/quicksight-sept-4.gif QuickSight, by default, has an automatic save feature enabled by default for each analysis. Personally, the case study of Quicksight in the NFL has to be one of the interesting use cases reads. If you don’t prefer a No/Low code solution, you should try looking into MatplotLib, Seaborn, and Bokeh Library. They are great for data visualisation and most of the data engineers will have experience with them. Q.How can we predict an outcome using our data? After Data visualisation helps us understand patterns in data. We would like to predict/classify an outcome based on historical data.  Q.What is Machine learning? Machine learning is a branch of artificial intelligence (AI) and computer science which focuses on the use of data and algorithms to imitate the way that humans learn, gradually improving its accuracy. An example of low code Machine learning solutions. When considering Machine learning solutions, there are many use cases to consider. Let us consider a few, 1. Extract text and data from documents: Rather than building up your Model from scratch, you could use AWS Textract. 1. Amazon Textract extracts text, handwriting, and data from scanned documents.  2. If you want to build Chatbots, then AWS Lex would help you build chatbots. 1. To design, build, test, and deploy conversational interfaces in applications using advanced natural language models. 3. If you want to automate speech recognition, AWS Transcribe.  1. An automatic speech recognition service that makes it easy to add speech to text capabilities to any application. Consider the use case of Alexa. For more information on various machine learning general use case solutions refer to, 1. https://aws.amazon.com/machine-learning/ If you don’t prefer Low code solution, you should try looking into Sagemaker. They are good for computing and deploying your ML models, as you get AWS compute servers. Q.What is a sagemaker? At its core, sagemaker is a fully managed service that provides the tools to build, train and deploy machine learning models. It has some components in it such as managing notebooks and helping label and train models deploy models with a variety of ways to use endpoints. SageMaker algorithms are available via container images. Each region that supports SageMaker has its copy of the images. You will begin by retrieving the URI of the container image for the current session’s region. You can also utilise your own container images for specific ML algorithms. Image Credits: https://programmerprodigycode.files.wordpress.com/2022/03/0bc53-1mfyty2swftpsulqybcgy-w.png Q.How can we host Sagemaker models? SageMaker can host models through its hosting services. The model is accessible to the client through a SageMaker endpoint. The Endpoint is accessible over HTTPS and SageMaker Python SDK. Another way would be using AWS Batch. It manages the processing of large datasets within the limits of specified parameters. When a batch transform job starts, SageMaker initialises compute instances and distributes the inference or pre-processing workload between them. In Batch Transform, you provide your inference data as an S3 URI and SageMaker will care of downloading it, running the prediction and uploading the results afterwards to S3 again. Batch Transform partitions the Amazon S3 objects in the input by key and maps Amazon S3 objects to an instance. To split input files into mini-batches you create a batch transform job, set the SplitType parameter value to Line. You can control the size of the mini-batches by using the BatchStrategy and MaxPayloadInMB parameters.  After processing, it creates an output file with the same name and the .out file extension. The batch transforms job stores the output files in the specified location in Amazon S3, such as s3://awsexamplebucket/output/. Image credits: https://aws.amazon.com/blogs/machine-learning/performing-batch-inference-with-tensorflow-serving-in-amazon-sagemaker/ The predictions in an output file are in the same order as the corresponding records in the input file. To combine the results of many output files into a single output file, set the AssembleWith parameter to Line. For more information refer, 1. https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform.html 2. https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-batch.html 3. https://docs.aws.amazon.com/sagemaker/latest/dg/ex1-model-deployment.html#ex1-batch-transform Q. How to Select the right to compute instance? Choosing a Compute instance completely biased on either price or compute, might not be a good option. As you select a cheaper compute instance, it takes you about 30 mins. But if you would have selected a better compute instance, it takes 10 mins. The second alternative would have been a better alternative economically and time-based. Some points to remember while choosing CPU and GPU will be 1. The CPU time grows proportional to the size of the matrix squared or cubed. 2. The GPU time grows almost linearly with the size of the matrix for the sizes used in the experiment. It can add more compute cores to complete the computation in much shorter times than a CPU. 3. Sometimes the CPU performs better than GPU for these small sizes. In general, GPU excel for large-scale problems. 4. For larger problems, GPUs can offer speedups in the hundreds. For Example, an application used for facial or object detection in an image or a video will need more computing. Hence GPUs might be a better solution. For more information, feel free to listen to my session on introduction to Algorithms and AWS Sagemaker: 1. https://vimeo.com/586886985/7faddfb340 For more information on Sagemaker, 1. https://aws.amazon.com/blogs/aws/sagemaker/ After considering all the no/low code solutions and coding solutions. Let’s consider a use case, If you have a relatively small business with not that much need of customisation, then perhaps no/low code solutions. But if you want to customise your application, you would have to you coding solutions. A point to remember, depending on your datasets size, diversity and quality, you could either go for CPU(less compute) or GPU (more compute). Advertisement Leave a Reply Fill in your details below or click an icon to log in: WordPress.com Logo You are commenting using your WordPress.com account. Log Out /  Change ) Twitter picture You are commenting using your Twitter account. Log Out /  Change ) Facebook photo You are commenting using your Facebook account. Log Out /  Change ) Connecting to %s
__label__pos
0.945935
bound or publishing to a non-loopback address, enforcing bootstrap checks – How to solve related issues bound or publishing to a non-loopback address, enforcing bootstrap checks – How to solve related issues Opster Team Jan-20, Version: 1.7-8.0 Before you begin reading this guide, we recommend you run Elasticsearch Error Check-Up which can resolve issues that cause many errors. This guide will help you check for common problems that cause the log ” bound or publishing to a non-loopback address, enforcing bootstrap checks ” to appear. It’s important to understand the issues related to the log, so to get started, read the general overview on common issues and tips related to the Elasticsearch concepts: bootstrap checks. Advanced users might want to skip right to the common problems section in each concept or try running the Check-Up which analyses ES to pinpoint the cause of many errors and provides suitable actionable recommendations how to resolve them (free tool that requires no installation). Log Context Log “bound or publishing to a non-loopback address, enforcing bootstrap checks” classname is BootstrapChecks.java. We extracted the following from Elasticsearch source code for those seeking an in-depth context : esEnforceBootstrapChecks); throw new IllegalArgumentException(message); } if (enforceLimits) { logger.info("bound or publishing to a non-loopback address; enforcing bootstrap checks"); } else if (enforceBootstrapChecks) { logger.info("explicitly enforcing bootstrap checks"); } for (final BootstrapCheck check : checks) {   Run the Check-Up to get a customized report like this: Analyze your cluster
__label__pos
0.573836
Foenix.com        How many days since July 30, 1912? Question about the past: How many days since July 30, 1912? Here we will calculate how many days since July 30, 1912. We do so by counting EVERY day between today which is and July 30, 1912. In other words, to solve the problem and answer the question, we use the following equation: Today's Date - Past Date = Days since past date Using the formula above with today's date and the past date of July 30, 1912, we get the following: - July 30, 1912 = Thus, the answer to the question, "How many days since July 30, 1912?" is as follows: Days Since How many days since Are you looking for how many days since a different date? No problem. To find how many days since a different date, please go here. July 1912 Calendar Go here to see the calendar for July 1912.   Copyright  |   Privacy Policy  |   Disclaimer  |   Days since 1912  |   Contact
__label__pos
0.805884
Rebuttal on the Worlds “Best” Password Advice It’s not every day I come across something so wrong about password managers that it moves me to write a response. Michael Horowitz writes the article in question, you can read it here The main point of the article is that password managers are bad, and using formula based passwords are good. I’ve already done a post on why formula based passwords systems are not as clever as you think, but this deserves its own response. First off, I mean no disrespect to Michael Horowitz, I much appreciate that he was able to list reasons why not to use a password manager, but the advice he’s giving can leave a person worse off if they just had used a password manager. The Same Old Song And Dance What Michael recommends doing is the same old advice that many people give out when it comes to these formula based passwords. You pick a phrase that you always use along with something that relates to the website. The example phrase or constant as he puts it would be “BabeRuth.” For the thing that relates or the variable will be whatever reminds you of that website. For Amazon, you would use “BabeRuthAmazon” or in one of his examples “BabeRuthJungle” because the jungle reminds you of the Amazon. There are several things wrong with this approach. 1. When (not if) one of your passwords is breached, it’s not hard to figure out your other passwords. It would not be hard to figure that your PayPal password is “BabeRuthPayPal” or your Barnes & Noble password is “BabeRuthBook.” 2. A few websites have strict password rules. Not all of them accept special characters, and some do a max of 12 characters like Walmart, “BabeRuthWalmart” will not work. Also, what do you do if the website requires or does not require a special/number? How do you remember what site needs the special or number as most don’t remind you of the password rules when you sign in to an account? 3. Not only do you need to remember the password rules for every website, but to be the most effective, you need very unique variables. Using the websites name or its initials will make it easy to guess all your other passwords in a plain text breach. You’ll need to make all the variables unique, but the average person will have over 200 online accounts by 2020. Even if you had only 50 passwords how is one to remember all these variables – it’s almost like they need a secure app that allows them to manage and password protect this information. 4. A lot of people will share the same constants and phrases. A lot of people like BabeRuth and a lot of them shop at Amazon too. This is a problem with people; we’re very predictable. I want to dive into Number 4 a little more. We can use https://haveibeenpwned.com/Passwords to see what passwords have been in KNOWN breaches. “BabeRuth” has been found 44 times! “baberuth”, the non-capitalized version has been found 4,102 times. With formula based passwords we run into the problem of people picking the same words as others thus making brute force attacks a lot easier. People share a lot of things in common, and their passwords should not be one of them. Just because you’re adding the websites name to the end of the password doesn’t make it more secure or unique. I bet the 31 people who thought “passwordfacebook” was a great password. Or the 24 who thought they were clever and only did the initials “passwordfb”. Ah! I hear some of you; you would not be so dumb to use “password” or any person’s name. Well… I bet the people who used “pinkamazon” (10) and “pinkadobe” (3) were thinking they were clever too. Why You Should Use A Password Manager Now it’s time for me to answer all the issues he has about using a password manager. 1. “There is a learning curve with all software. Techies underestimate how much of a pain this can be for non-techies.” This one I agree on, but his solution is where I defer from. If a user can use a web browser, then using a password manager is not any harder. If anything, it makes your life easier with autofill. Just because there is a slight learning curve doesn’t mean we should not go after better security. This is like complaining that you have to use a PIN with your ATM card while at the bank. Getting hacked is far more painful then a password manager will ever be. For the 1% who refuses to use a password manager, I have them generate passwords from https://www.dinopass.com/ and write them down. This way, they have completely unique passwords for every account that are easy to type in. They understand paper and pen, and they don’t need to use their brains to come up with some complex formula that they’ll forget anyway. 2. “No software runs on every Operating System or supports every web browser, so you are limited where you can use any one particular password manager.” It’s in the password manager companies best interest to have their software work on the most popular Operating Systems and Browsers. Who’s not running either Windows, Mac, iOS, Android, Chrome, Safari, Firefox, or even Opera? The vast majority of password managers work for those OS’s and Browsers with many of them also offering online access – if you can access a webpage you can access your passwords. 3. “The most secure Operating System most people have access to is a Chromebook running in Guest Mode. A formula works there, a password manager does not” A Chromebook being the most secure OS is debatable, especially since it’s just the Chrome Webbrowser. To answer your question, Chrome is the most popular browser, and every password manager supports it. Like I’ve said before, many of the password managers have a web interface so if you can go to a webpage you can get your passwords. 4. “All software has bugs, password managers included. Not only might you be vulnerable to a bug, but you certainly are on the hook for keeping the password manager software up to date. That alone rules out password managers for some people. A formula will never have a bug and never require an update.” Do you know what has more bugs? A system you derive without anyone checking it out. I bet the author never realized the bug in his password system could reveal all the other passwords he uses. Or how people are more likely to pick an easy to crack/guess constant. The great thing about a password manager is that many of them are open source. That means many eyes are looking at the code for bugs. The ones that are not open source still use code that has been proven for decades called AES encryption. If a password manager company wants to stick around, it’s in their best interest to not screw this up. They will always go for the tried and tested. I have to make a note as he’s given us a link to a password manager that had a bug. So I’ll provide a link too. [link] It was from HP, and it was a keylogger which could easily steal all the manually typed in passwords, the kind of password that Michael tells us to use. If you had a password manager this HP bug would not have been a big deal as password manager autofill without using the keyboard. 5. “With a password manager, you have to trust that it works correctly. The software is a black box to most people. With a formula, you do not need to trust anyone or anything.” I agree that it’s all about trust, but with a formula, you have to trust that no one else uses your words and that the websites you use don’t leak that password that is very similar to all your other passwords. I don’t know about you, but I have a hard time trusting other people and 200 websites I have no control over on how they store my passwords. These websites are like black boxes; you don’t know what they’re doing with your passwords. They could be selling it since it’s a unique way to identify a person across the internet, especially if every password has “BabeRuth” in it. They could even be careless like Facebook recording people’s passwords in plaintext to log files. All it takes is one employee to see that you use “BabeRuthFacebook” so that must mean you used “BabeRuthPayPal” for your PayPal account. Imagine all the other websites making the same mistakes and not even reporting it. I do trust myself with my encrypted password vault full of unique passwords for every account that I can put wherever I want with a master password that I only know. 6. “A formula lets you write down the variable part of the password – safely. That is if you write down that your Amazon password is “jungle” and someone sees this, it’s only half the actual password. No one is hacking a password written down on paper. You can put all your passwords in a book, and if the book is stolen, you are still protected, as long as the fixed part of each password was not written down in the book.” Great minds think alike! I do the same thing in my password managers; I call it salting your passwords. Generate a random password with your password manager and add a word only you would know to the end of it. When you save the password in your password manager leave out the salt. When it’s time to log into that site have the password manager fil in what it has and then add your salt. If you salt your most important passwords, I find there is no reason not to trust a password manager. Even if someone gets your vault of passwords, they still don’t have the real passwords. The great thing about salting is that you don’t need to write it in a book that can be lost or stolen. It’s just one word, and the real power is in the random password your password manager generated. You could even hide the salt in plain sight located in a secure note for the secret family recipe. So many possibilities! 7. “When a password manager generates passwords for you, it may create a password that is too long for the target system, or, that contains characters the target system does not allow. It is much easier to deal with this sort of thing when using a formula.” You got this one backwards. If you generate a password the site doesn’t like you just press a button to change it. Many password managers know this and will default to 12 characters long and no symbols as this is what 98% of all websites want. Some like Apple’s Safari password manager have a huge list of all the most popular websites and their password requirements and know what to generate beforehand. If you’re using a formula of “BabeRuthWalmart”, it won’t work for Walmart as they have a max of 12 characters. So what do you do? You’ll have to change how you do your formulas, and so you don’t forget it you’ll have to write it down. This adds more complexity and things for you to remember. What do you do if you don’t have or lose your book to remember all the nuances of this particular website? Not only that, having to manually type in each character of your password until it accepts one is far more annoying then pressing a single button on a password manager. 8. “Some websites do not allow passwords to be pasted into the login form. That’s a problem for password manager software, not for a formula.” Good thing most password managers don’t paste passwords but instead fill passwords. Pasting is a security issue; any app can spy on the clipboard and steal data. Password managers directly fill from the browser plugin avoiding paste. 9. “A formula is free, some password managers are also free, but some are not.” You already answered it for me. You can use free password managers, and many of them are good like Bitwarden. For when it comes to paying, can you name a service that is more important than the one securing your most important passwords? You’re not paying for an app, your paying for the security and protection that a team of people who’s entire job is passwords and how to keep them safe. With a formula, you’re getting what you paid for – the guy who’s in charge of it is the same guy who forgets why he walked into that room or where he left his keys. 10. “The security of web browser extensions.” The argument is that password manager browser extensions can read and change anything on the webpage. They need to be able to do this so they can fill your passwords and avoid the clipboard vulnerability I’ve discussed before. For someone to make this argument is someone who doesn’t fully understand the security of extensions. It’s insulting to think that password manager companies are not taking steps to protect you and your data. There are levels of encryption and sandboxing in place so that no one but you can see your password data. They have guys who sit in rooms looking for ways to exploit their own extensions. Bounties are given to anyone who can find a way in that there team of guys missed. As I say, you’re not paying for a PW app but instead buying a team whose job is to keep your data safe. If you’re that super worried, you can get a password manager that doesn’t need a browser extension and uses auto-type instead. Or salt your most important passwords as I’ve pointed out before. 11. “When using someone else’s computer, the password manager software is not available.” First, don’t use a computer you don’t trust. It doesn’t matter if you use a password manager or a formula. If you need to use a computer that doesn’t have your password manager on it, there are several options. The first, just use your phone. Every password manager has an option for a mobile app for both iOS and Android. Open the app and type in the password. If this is something you often have to do you can make the password simple, uniqueness is more important than complexity for online accounts. The other option is to log in to your vault from the online portal. LastPass, Bitwarden, and 1Password just to name a few allow you to access your vault from any web browser. All the data is done locally in the browser’s cache and is decrypted and encrypted there too. You can copy and paste the password wherever you want. How often are you away from your computer or phone that you need to log in right away? Why do you need to use a friends computer? Why not use your phone’s web browser to log in with the PW App? Many of the password manager mobile apps have a built-in secure Browser that makes this seamless. What is so important that you can’t do it from your phone or wait till you get home? The real kicker for me is if you do use a formula and take it very seriously you’ll have to store the password requirements and the other variables somewhere. If you don’t have that on you, are you not just as screwed? Would you rather carry around an unprotected notebook of your passwords or a password manager on your phone that can autofill the passwords on your phone’s browser? It seems the people who make this argument haven’t heard they make password manager apps for phones or have web interfaces or they’re only looking for a problem they don’t have. 12. “What if you want to switch away from a password manager you are currently using?” Every password manager has an export button that allows you to move to another password manager. They all have instructions on how to import from another password manager. If you want to switch away, it’s the same song and dance. You export to a CSV file which can be open by any spreadsheet program. With the spreadsheet, you can do whatever you want with the information. You’re not locked into the password manager if that is what you’re hinting at. Just to prove this here is links to the top password managers showing you how to export your data. 13. “All your eggs in one basket? Really? There is a reason this phrase is popular.” You act like this is a bad thing. [link] Who do you trust more, 200 websites you don’t control storing your similar passwords or one single database with all unique passwords that you do control? 1. BabeRuthAmazon 2. BabeRuthFacebook 3. BabeRuthPayPal 4. BabeRuthTwitter . . . 200. BabeRuthOutlook All it takes is ONE website to get breached to know all your passwords. Even if you did use something more complex, they still know the first half of all your passwords. The more of those websites that get breached, the easier it is to figure out your formula. The more websites storing your passwords the more likely you’re to have passwords leaked. If you had used a password manager… 1. CyL8BjH3fyn8JNDR5Bd 2. oyster-uncanny-crispy-irritate 3. xk9q*BPu49,FKv7p 4. oddgeese26 . . . 200. Z,k;e,4mkVUn#mzNRtHNRBkWP#qwp:AAWY9SStHY,FA One account getting breached won’t lead to the others. The passwords share nothing alike and you have the ultimate control on where you get to keep that encrypted database. If you think about it, using a password manager and letting it generate all unique passwords seems to be the most reasonable approach. More Reasons To Use A Password Manager 1. You can store more than passwords. Family recipes, instructions on how to fix the printer, PIN to Safe, Drivers license, Insurance card, a Credit card for easy checkouts (don’t have to store the credit card on a website you don’t trust), Serial numbers, Software Licences, etc. The sky is the limit! 2. Can share passwords securely, something a formula can’t do. 3. Can limit and share passwords to employees in your business. 4. Helps stop phishing attacks, something a formula can’t do. 5. Takes away the stress of thinking about passwords. 6. Can be used if you die or can’t physically use a computer. It’s hard to explain your formula if you’re dead. It goes beyond paying bills, it’s about the little things like the pictures in your Google Photos account or the little notes locked in your phone. 7. No fat finger typing. 8. No wondering if you type the password correctly and then backspacing the whole thing and starting again. 9. No worry about someone or a camera watching you as you type your Facebook password in. Many password managers can open with just your fingerprint or your face, no need to enter any passwords in public. 10. A flash drive or cloud back up is more likely to survive a natural disaster than the piece of paper with parts of your formula on it. The Biggest Reason To Use A Password Manager The biggest reason to use a password manager is to stop password reuse. Password reuse is the biggest threat you’re facing online. Websites get breached and passwords stolen on the regular, and it’s only going to get worse. Telling people to use a formula that reuses parts of your password is not solving the problem, if anything it’s making it worse. Using “BabeRuth” at the start of every password is not unique! Using completely unique passwords for every account is the best thing you can do, and a password manager makes this easy. Need A Password Manager? Here is our picks for password managers. 1. Bitwarden - Best free and overall option. 2. 1Password - Best paid option. 3. Dashlane* - Best for new users as it holds your hands more. 4. Roboform* - Featured packed and been around the longest plus a free option. The only one with a bookmark manager which I've found useful lately. *May receive a commission. Leave a Comment
__label__pos
0.527647
EdgeCaseBerg EdgeCaseBerg - 1 year ago 65 MySQL Question MySQL Null Safe Equals incorrect on Numeric types? This one bit me today and it seems like a bug. It seems like when comparing the result of the LOCATE function in MySQL that it behaves totally different when using the not equals <> versus the null safe version <=> See the session below: $ mysql --version mysql Ver 14.14 Distrib 5.6.25, for osx10.8 (x86_64) using EditLine wrapper mysql> SELECT LOCATE('A', "The Apple"); +--------------------------+ | LOCATE('A', "The Apple") | +--------------------------+ | 5 | +--------------------------+ 1 row in set (0.00 sec) mysql> SELECT LOCATE('A', "The Apple") <=> 0; -- WRONG!? +--------------------------------+ | LOCATE('A', "The Apple") <=> 0 | +--------------------------------+ | 0 | +--------------------------------+ 1 row in set (0.00 sec) mysql> SELECT LOCATE('A', "The Apple") <> 0; +-------------------------------+ | LOCATE('A', "The Apple") <> 0 | +-------------------------------+ | 1 | +-------------------------------+ 1 row in set (0.00 sec) The null safe version returns 0 (false) which seems odd to me. The LOCATE method's documentation doesn't specify what happens with nulls, but I tested it and it does return null for something like LOCATE('A', null) but the real issue seems to be comparing the integer that LOCATE returns to 0 . I checked the documentation on <=> but it just says: NULL-safe equal. This operator performs an equality comparison like the = operator, but returns 1 rather than NULL if both operands are NULL, and 0 rather than NULL if one operand is NULL. Which doesn't really tell me why 0 <=> 5 comes back 0 and 0 <> 5 comes back 1 The only thing I could think of was that MySQL says: These operations work for both numbers and strings. Strings are automatically converted to numbers and numbers to strings as necessary. And maybe there was an automatic cast, but that doesn't make any sense since doing the check directly (typing out 0 <=> 5 ) shows the same issue. Does anyone know what's causing this? Or where in the documentation this is indicated? It seems like a pretty major issue if the null-safe equality operations return invalid results for as simple a comparison as 5 and 0. Answer Source The Null safe equality comparison <=> (spaceship) operator is an equality operator. It works like the = equality comparison operator, except with the bit about not returning NULL. To get "inequality" out of that operator, you would need to negate it, for example SELECT NOT ( 0 <=> 5 ) Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
__label__pos
0.732489
Structure# class Structure[source]# Bases: object Simple structure class that can hold any type of data. Structure is constructed when calling __setitem__ and can grow in complexity. Example: s = Structure() s['_x', 'C_a'] = {'C_a_0':[1,2,3], 'C_a_1': [2,3,4]} s['_x', 'C_b'] = 'C_b' s['_u', 'C_a'] = 'C_a' investigate the indices with s.powerindex. This yield the following: [('_x', 'C_a', 'C_a_0', 0), ('_x', 'C_a', 'C_a_0', 1), ('_x', 'C_a', 'C_a_0', 2), ('_x', 'C_a', 'C_a_1', 0), ('_x', 'C_a', 'C_a_1', 1), ('_x', 'C_a', 'C_a_1', 2), ('_x', 'C_b'), ('_u', 'C_a'), ('_x', 'C_a', 'C_a_0', 0), ('_x', 'C_a', 'C_a_0', 1), ('_x', 'C_a', 'C_a_0', 2), ('_x', 'C_a', 'C_a_1'), ('_x', 'C_b'), ('_u', 'C_a')] Query the structure as follows: s['_x', 'C_a'] >> [1, 2, 3, 2, 3, 4] s['_x', 'C_b'] >> [C_b] Slicing is supported: s['_x', 'C_a', :, 1:] >> [[[2], [3]], [[3], [4]]] and introduces nested lists for each slice element. Methods# Attributes# full# Structure.full# Return all elements of the structure. Elements are returned in an unnested list. get_index# Structure.get_index# Get regular indices ([0,1,2, … N]) for the queried elements. This call mimics the __getitem__ method but returns the indices of the queried elements instead of their values. This is an IndexedProperty and can thus be queried as shown below: Example: # Sample structure: s = Structure() s['_x', 'C_a'] = {'C_a_0':[1,2,3], 'C_a_1': [2,3,4]} s['_x', 'C_b'] = 'C_b' s['_u', 'C_a'] = 'C_a' # Get indices: s.get_index['_x', 'C_a'] s.get_index['_x', 'C_a', :, 1:] The same nested list structure is obtained when using slices.
__label__pos
0.994013
ActiveXperts Network Component Quicklinks ColdFusion UDP Sample Source Code Network Component provides an easy-to-use development interface to a variety of IP protocols. By using Network Component, you can very easily create or enhance applications with network features. Network Component features the following: DNS, FTP, HTTP, HTTPs, ICMP Ping, IP-to-Country, MSN, NTP, RSH, SCP, SFTP, SNMP v1/v2c (Get, GetNext, Set), SNMP Traps, SNMP MIB, SSH, TCP, Telnet, TFTP, UDP, Telnet, Wake-On-LAN and more. Network Component can be well integrated into any development platform that supports ActiveX objects. Step 1: Download and install the Network Component Download Network Component from the ActiveXperts Download Site and start the installation. The installation guides you through the installation process. Step 2: Create a new ColdFusion document Create a new blank webdocument with the ".cfm" extention. First of all we are going to build the form whitch commands and properties of the device can be filled in. Then we are going to make a source code that connects to the device. Step 3: Implementation Establishing the connection and listing the files can be done in three steps: • Collect the ftp-server-address, the username and the password from the user • Establish the connection • List the files Collecting the information can be done using a form. We've made our form look like this: (Click on the picture to enlarge) When we've got this information, we're ready to establish a connection to a server. First of all we need an object witch creates a connection between ColdFusion and the ActiveXperts software. To do that, use the following code: <cfobject class="ax_AxNetwork.Udp" type="com" name="objUdp" Action="Create"> Once the object is created, we're able to use the component. We need to establish a connection, so we're going to use the Network Component method "connect()". Use the following code: objUdp.Connect(strHost,strUsername,strPassword); Now we need to list the files. The Network Component is able to get the first file in the folder using the "FindFirstFile()" method and then the next file using the "FindNextFile()" method. So we're going to list the first file in the folder first, then the next file (the second file) and than the next file (the third file) and so on. Use the following code: objFiles = objUdp.FindFirstFile(); do{ writeoutput ("<tr>"); writeoutput ("<td width=100>"); if(objFiles.IsDirectory()){ writeoutput("Directory:"); } else{ writeoutput("File:"); } writeoutput ("</td>"); writeoutput ("<td>"); writeoutput(objFiles.Name & "<br>"); writeoutput ("</td>"); writeoutput ("</tr>"); objFiles = objUdp.FindNextFile(); } while(objUdp.LastError eq 0); Perhaps you would like to show the content of another folder. Paste the following code, before the listing code. objUdp.ChangeDir(strDirectory); We're displaying the results of the process using the "LastError" method of the Network Component. The method "LastError" displays a number. It's helpfull to know "0" means success. To get the error description use the "GetErrorDescription()" method. In our code we've used these methodes this way: strResult = objUdp.LastError & " : " & objUdp.GetErrorDescription(objUdp.LastError); It can be very helpfull to check for errors before executing some code. Applying this can be done easily: if(objUdp.LastError eq "0"){ Some code } Appendix: Full source code todo You can download the complete sample on our FTP site ftp.activexperts-labs.com/samples/network-component/. There are many other working Network Component scripts on our site and shipped with the product.
__label__pos
0.793569
MathOverflow is a question and answer site for professional mathematicians. Join them; it only takes a minute: Sign up Here's how it works: 1. Anybody can ask a question 2. Anybody can answer 3. The best answers are voted up and rise to the top I have never studied any measure theory, so apologise in advance, if my question is easy: Let $X$ be a measure space. How can I decide whether $L^2(X)$ is separable? In reality, I am interested in Borel sets on a locally compact space $X$. I can also assume that the support of the measure is $X$, if it helps... I cannot even decide at the moment for which locally compact groups $G$ with Haar measure, $L^2(G)$ is separable... share|cite|improve this question 1   Dear BB: perhaps you want the Borel measure to be $\sigma$-regular, which loosely says that everything is determined by measures of compact subsets (which are required to be of finite measure); measures arising from functionals on $C_c(X)$ (e.g., Haar on $G$) are of this type. The precise def'n is on p. 256 of 3rd edition of Lang's real analysis book. A $\sigma$-regular Borel measure on a $\sigma$-finite $X$ is "regular" (Lang, p. 257), so the measure of any Borel set is sup of measures of compacts inside it. Thus, you win if loc. comp. $X$ has a countable base of opens with compact closure. – BCnrd Oct 15 '10 at 17:42      Given the flurry of answers, corrections and deletions to this question (some of them mine), this may be good fodder for mathoverflow.net/questions/23478. – Nate Eldredge Oct 15 '10 at 18:35 1   Thanks, folks!! All voted up and I will chew on the answers for a day before accepting one... – Bugs Bunny Oct 17 '10 at 7:27 up vote 26 down vote accepted Without loss of generality we can assume that the support of the measure equals $X$ (i.e., the measure is faithful), because we can always pass to the subspace defined by the support of the measure. The space $L^2(X)$ is independent of the choice of a faithful measure and depends only on the underlying measurable space of $X$. There is a complete classification of measurable spaces up to isomorphism (for simplicity I only consider measurable spaces that satisfy a certain countability assumption, because only these spaces can have separable $L^2$-spaces): every measurable space canonically decomposes as a disjoint union of its atomic and diffuse parts. The atomic part is simply a disjoint union of points, whereas the diffuse part is a (noncanonical) disjoint union of real lines. Finite nonempty disjoint unions of real lines are isomorphic to the countable union of real lines, but otherwise the cardinality of the family determines the diffuse part uniquely. Thus isomorphism classes of measurable spaces are in bijection with pairs of cardinal numbers $(m,n)$, where n is either zero or infinite. (Here $m$ is the number of points in the atomic part and $n$ is the number of real lines in the diffuse part.) $L^p(X)$ (for $p\geq 1$) is separable if and only if both $m$ and $n$ are at most countable. Thus there are two families of measurable spaces whose $L^p$-spaces are separable: 1. Finite or countable disjoint unions of points; 2. Disjoint unions of the real line and a space of the type 1. Equivalent reformulations of the above condition: 1. $L^p(X)$ is separable if and only if $X$ admits a faithful finite measure. 2. $L^p(X)$ is separable if and only if $X$ admits a faithful $σ$-finite measure. 3. $L^p(X)$ is separable if and only if every measure on $X$ is $σ$-finite. (Here I disallow nonsemifinite measures, i.e., measures that are equal to infinity on a set of nonzero measure. Note also that X is assumed to satisfy the countability property mentioned above.) The underlying measurable space of a locally compact group $G$ satisfies the above conditions if and only if $G$ is second countable. The underlying measurable space of a paracompact Hausdorff smooth manifold $M$ satisfies the above conditions if and only if $M$ is second countable, i.e., the number of its connected components is finite or countable. More information on this subject can be found in this answer: Is there an introduction to probability theory from a structuralist/categorical perspective? Bruckner, Bruckner, and Thomson discuss separability of $L^p$-spaces in Section 13.4 of their textbook Real Analysis: http://classicalrealanalysis.info/documents/BBT-AlllChapters-Landscape.pdf share|cite|improve this answer 2   Thanks. This confused me at first because some authors use "measurable space" to refer to just a set $X$ equipped with a $\sigma$-algebra of measurable sets, whereas yours (as described in the link) also specifies the $\sigma$-ideal of measure zero sets. The former obviously would not suffice to determine the separability of $X$ (consider $[0,1]$ with its Borel $\sigma$-algebra and either Lebesgue or counting measure). – Nate Eldredge Oct 16 '10 at 14:28 1   Another question though: how does one define the support of a measure on an abstract measurable space (to ensure that it is "faithful")? The definition I know involves taking a closure, but here I suppose $X$ need not come with a topology. – Nate Eldredge Oct 16 '10 at 14:30 1   Dmitri: It's a great answer, but I can't reconcile my compact counterexample with your statement that $L^2(G)$ will be separable if $G$ is $\sigma$-compact. Where did I go wrong? – Byron Schmuland Oct 16 '10 at 15:04 1   @Nate: The support of a measure m on a measurable space is defined as follows. Consider the Boolean algebra of all measurable sets modulo null sets (i.e., two measurable sets are equivalent if their symmetric difference is a measure 0 set). This Boolean algebra is complete, as described in the link. Now take the supremum of all elements p of this algebra such that m vanishes on p. The complement of this supremum is the support of m. It is extremely important to factor out the null sets, otherwise the above procedure doesn't make sense. – Dmitri Pavlov Oct 16 '10 at 15:09 1   @Nate: Every σ-finite space is localizable, but not every localizable space is σ-finite. A space is σ-finite if and only if it satisfies one of the equivalent statements above, which means that both m and n must be at most countable. The first six paragraphs of my answer in the link are devoted to an explanation of localizability. Most of the results mentioned there are proved in the following paper: Irving Segal, “Equivalences of measure spaces”. – Dmitri Pavlov Oct 18 '10 at 15:56 $\sigma$-finiteness of the measure has nothing to do. The only property which matters is the separability of the measure space itself, which (modulo some technicalities) means that there exists a countable family of measurable sets which separate points of $X$ (mod 0). Measure spaces with this property are called Lebesgue spaces (essentially, these are the only measure spaces one meets in the "real life"). Note that such a family of separating sets gives rise to an isomorphism of the original space with the countable product of 2-point sets. Any Polish space (separable, metrizable, complete) endowed with a purely non-atomic Borel probability measure is isomorphic to the unit interval with the Lebesgue measure on it. In the same way, a Polish space endowed with a $\sigma$-finite purely non-atomic measure is isomorphic to the real line with the Lebesgue measure on it. In the "Borel language" one talks about so-called standard Borel spaces. Any standard Borel space endowed with a $\sigma$-finite measure on the Borel $\sigma$-algebra is a Lebesgue space. $L^2$ on any Lebesgue space (be it finite or $\sigma$-finite) is separable in view of the above isomorphisms. On the other hand, if one takes a measure space which is not separable - like the uncountable product measure in the previous answer - then $L^2$ on this space is not separable either. ADD My answer was partially prompted by several comments which have since disappeared - otherwise I would have organized it in a somewhat different way. Unfortunately, the whole discussion illustrates the deplorable situation with teaching measure theory, as a result of which people, for instance, don't realize that in the measure category there is no difference between circles and intervals. A well-kept secret is the fact that there is (up to isomorphism) only one "reasonable" non-atomic probability space, and, consequently, only one reasonable non-atomic $\sigma$-finite space. There is a good Wikipedia article about it. share|cite|improve this answer      Since there are a lot of conflicting statements here, perhaps you could give a reference? – Nate Eldredge Oct 15 '10 at 18:33 In addition to the measure $\mu$ being $\sigma$-finite, I think you also need some conditions on the measurable space $(X,{\cal A})$. Proposition 3.4.5 of Cohn's book Measure Theory says that $L^p(X,{\cal A},\mu)$ ($1\leq p < \infty$) is separable if $\mu$ is $\sigma$-finite and $\cal A$ is countably generated. For example, it holds if $X$ is a complete separable metric space, and $\cal A$ is the Borel $\sigma$-algebra. However, even for a compact group, you can make counterexamples like $[-1/2,1/2]^{[0,1]}$, an uncountable product of a circles. For the product measure, $\mu=\lambda^{[0,1]}$, the coordinate functions are orthogonal in $L^2$ but there are uncountably many. I haven't checked the details, so take my answer with a grain of salt! share|cite|improve this answer      Your circles look a lot like intervals! :) – Mariano Suárez-Alvarez Oct 15 '10 at 18:01      Ha! I want the coordinate functions to be real-valued, but I want the topological circle. So I mentally put in or leave out details. No wonder my students find my lectures confusing! :) – Byron Schmuland Oct 15 '10 at 18:04      Notice that separability is a condition you put on a topological space, while one would want conditions on the measured space for $L^2$ to be separable. – Mariano Suárez-Alvarez Oct 15 '10 at 18:10      Well, the measure condition is that $\cal A$ is countably generated. The topological condition of separability was an example only. I will edit my answer. – Byron Schmuland Oct 15 '10 at 18:13 I have just found an old article which contains the following result: for a locally compact group $G$, its topological weight $w(G)$ [the minimal cardinality of a topology base] is equal to the dimension of $L^2(G)$. Whence $L^2(G)$ is separable iff $G$ is second countable. This is Theorem 2 in: de Vries, J. The local weight of an effective locally compact transformation group and the dimension of $L^2(G)$. Colloq. Math. 39 (1978), no.2, 319-323. Since I spent a considerable time searching for such a reference, I post it here. Worth noting also that the case of a compact $G$ is contained in Hewitt-Ross, Theorem 28.2. share|cite|improve this answer Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.860941
Presentation is loading. Please wait. Presentation is loading. Please wait. Negative Numbers Anton Rabkin. Negative Numbers A negative number is any number that is less than zeroless thanzero Negative numbers are usually written. Similar presentations Presentation on theme: "Negative Numbers Anton Rabkin. Negative Numbers A negative number is any number that is less than zeroless thanzero Negative numbers are usually written."— Presentation transcript: 1 Negative Numbers Anton Rabkin 2 Negative Numbers A negative number is any number that is less than zeroless thanzero Negative numbers are usually written with a minus sign in frontminus sign A number that is not negative is called positive Zero is neither positive nor negative 3 Negative Numbers In mathematics, every real number other than zero is either positive or negativemathematicsreal number Negative numbers can be thought of as resulting from the subtraction of a larger number from a smaller.subtraction For example, negative three is the result of subtracting three from zero: 0 − 3 = −3 4 Number Line / Scale 5 Subtract Larger Numbers 6 Celsius and Centigrade Celsius = Centigrade Temperature scale, in which water freezes at 0° and boils at 100° Celsius degrees Named after the person who invented the scale Centigrade degrees Means "100 divisions" 7 Negative numbers ! Download ppt "Negative Numbers Anton Rabkin. Negative Numbers A negative number is any number that is less than zeroless thanzero Negative numbers are usually written." Similar presentations Ads by Google
__label__pos
0.999949
echarts画图实例讲解 前两天分享了一个项目(http://hyuhan.com/2016/11/17/A-data-display-platform/),里面用到了echarts(一个纯Javascript的图表库)来画图,项目中用到了它的字符云图,地图,柱状图,饼图等,今天就给大家分享一些一些实现的细节。建议先去看看五分钟上手Echarts再来看这篇博客。 地图 Echarts百度地图扩展,可以在百度地图上进一步展现点图,线图,热力图等,我主要在百度地图上展现的是气泡图。 引入百度地图 • 首先引入百度地图的jssdk,需要使用在百度地图开发者平台申请的ak • 然后引入Echarts • 最后引入百度地图扩展bmap(已经打包在echarts包中) <script src="http://api.map.baidu.com/api?v=2.0&ak=你的ak"></script> <script src="echarts/dist/echarts.min.js"></script> <script src="echarts/dist/extension/bmap.min.js"></script> 设置参数 百度地图引入之后,主要就是设置参数了,以我画的最喜爱建筑分布图为例: option = { // 设置标题样式 title: { // 标题文本 text: '学生最喜爱学校建筑分布', // 标题离容器左侧的距离,center表示水平居中 left: 'center', top: 15, // 标题文本的样式设置 textStyle: { fontSize: 24, fontFamily: 'Helvetica', fontWeight: 400 } }, // 提示框设置为由数据项图形触发 tooltip: { trigger: 'item' }, // 添加保存为图片和数据视图工具工具栏 toolbox: { feature: { saveAsImage: {}, dataView: {} }, right: 15, top: 10 }, // 加载bmap组件 bmap: { // 百度地图中心经纬度(设置为你需要的地图中心即可) center: [114.427877, 30.517249], // 百度地图缩放比例(按需配置) zoom: 15, // 是否开启拖拽缩放 roam: true, // 设置百度地图样式(可参考http://developer.baidu.com/map/jsdevelop-11.htm) mapStyle: { style: 'light' } }, series: [ { name: '最喜爱建筑', // 图标类型设置为气泡图 type: 'scatter', // 设置坐标系为前面提到的bmap coordinateSystem: 'bmap', // 数据 data: [{}], // 气泡标记大小 symbolSize: , label: { normal: { formatter: '{b}', position: 'right', show: true }, emphasis: { show: true } }, itemStyle: { normal: { color: 'rgba(11, 110, 72, 1)' } } }, ] } 另外给大家推荐一个百度的拾取坐标系统,挺好用的。 字符云图 之前一直觉得字符云是个很酷炫的东西,所以这次也就强行把它用上了,嘿嘿。里面的数据是我根据群聊记录分析出来的高频词汇。Echarts的字符云是基于wordcloud2.js的。 引入字符云 直接下载js文件并引入 <script src="echarts.min.js"></script> <script src="echarts-wordcloud.min.js"></script> webpack引入 npm install echarts-wordcloud import echarts from 'echarts' import 'echarts-wordcloud' 设置参数 option = { title: { text: title, textStyle: { fontSize: 26, fontFamily: 'Helvetica', fontWeight: 400 }, left: 'center', top: 20 }, toolbox: { feature: { saveAsImage: {}, dataView: {} }, right: 20, top: 20 }, series: [{ // 设置图表类型为'wordCloud' type: 'wordCloud', // 设置cloud的形状 shape: 'cardioid', // shape: 'pentagon', // shape: 'circle', left: 'center', top: 30, width: '75%', height: '80%', // 设置字符字体大小的范围 sizeRange: [12, 75], // 设置字符旋转的角度范围 rotationRange: [-90, 90], rotationStep: 45, // 字符间距 gridSize: 8, // 字符字体样式 textStyle: { normal: { fontFamily: 'Microsoft Yahei', fontWeight: 'bold', // 字符字体颜色用一个函数随机设置 color: function() { return 'rgb(' + [ Math.round(Math.random() * 160), Math.round(Math.random() * 160), Math.round(Math.random() * 160) ].join(',') + ')' } }, emphasis: { shadowBlur: 10, shadowColor: '#333' } }, // data必选包含name和value选项,name即为显示的字符,value越大字符字体大小越大 data: [{ name: '', value: , textStyle: { normal: {}, emphasis: {} } },{...},...] }] } 画热力图 根据班级群聊数据分析出来的同学之间亲密度,思前想后最后决定用热力图。热力图不需要额外的插件,直接讲参数设置。 参数设置 option = { title: { text: '通信1502班同学关系密切度分析图(仅通过群聊数据分析)', // 子标题 subtext: '数值越大两者越亲密', subtextStyle: { fontSize: 16 }, left: 'center', top: 4, textStyle: { fontSize: 22, fontFamily: 'Helvetica', fontWeight: 400 } }, tooltip: { trigger: 'item' }, toolbox: { feature: { saveAsImage: {}, dataView: {} }, right: 15 }, grid: { height: '78%', bottom: '14%' }, // x轴设置 xAxis: { // 坐标轴为类目轴 type: 'category', // 数组,x轴显示的刻度标签 data: [...], // 刻度标签相关设置 axisLabel: { // 如果水平放不下,可以旋转 rotate: 60, // 刻度标签显示间隔 interval: 0 }, splitArea: { show: true } }, yAxis: { type: 'category', data: [...], splitArea: { show: true } }, // 视觉映射组件,也就是项目展示中热力图最小面现实的那个组件 visualMap: { // 组件允许的最小值和最大值 min: 0, max: 100, calculable: true, // 组件高度 itemheight: 300, // 组件水平放置 orient: 'horizontal', left: 'center', bottom: '3%' }, series: [ { name: '亲密度', // 图标类型为heatmap type: 'heatmap', // 二维数组,每个数据项都是一个一维的数组,前两个值表示直角坐标系上的x,y,第三个至表示大小。 data: [[0,0,2],[]...], label: { normal: { show: true } }, itemStyle: { emphasis: { shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] } 饼图和条形图比较基础,可以参考官方实例,建议仔细阅读官方配置文档,可以自己画出各种有趣的图形来。 推荐阅读更多精彩内容
__label__pos
0.990482
AminetAminet Search: 84091 packages online About Recent Browse Search Upload Setup Services dev/moni/mon165.lha Mirror:Random Showing:m68k-amigaosgeneric No screenshot available Short:Amiga Monitor, a monitor/debugger Author:trossi at jyu.fi (Timo Rossi) Uploader:trossi jyu fi (Timo Rossi) Version:1.65 Architecture:m68k-amigaos Date:1994-05-22 Download:http://aminet.net/dev/moni/mon165.lha - View contents Readme:http://aminet.net/dev/moni/mon165.readme Downloads:5207 Amiga Monitor v1.65 instructions ================================ This is a machine code monitor/debugger program for the Amiga. The first version was created many years ago, and many of the features and commands of the monitor were made similar to those of the monitors available for the Commodore 64. However, because the Amiga is a quite different machine many new commands and features were needed. Later versions of the monitor add many more useful features, such as expressions and variables. This version is quite close to an actual symbolic debugger as it can read symbol table information from executable files and display them in disassembly listings. It also has a built-in Scripts. Version history: 1.65 -> - loading symbols is a little faster (but not much, memory allocation limits the speed more than disk i/o) - current address is set to the starting address of '[' and '<' commands. - hunk number/offset is shown in disassembly output. - '&' (alloc-abs) doesn't allow odd addresses. - memory list shows block numbers, and they can be used in the mem-free (')' command. - added 'i'-command. - added AmigaGuide-format document. - address range syntax addr..endaddr and addr:length 1.64 -> - now works again on OS 1.3. there was a bug in version checking... 1.63 -> - now should properly count labels when displaying disassembly one screen at a time. 1.62 -> - fixed a problem with breakpoints on 68040 machines 1.61 -> - breakpoint list shows counts correctly. - better error messages with b and br commands. 1.60 -> - command line setting from monitor command line works again (was broken in 1.59) - lib/dev etc. now return zero on error only if option flag #6 is set, otherwise they fail. - added board()-function to the expression parser. - disassembler now displays short branches as '.b' and 68000 long branches as '.w'. It also understands 68020+ long branches (.l) - now supports ReadArgs() command line parsing. - rb-command now works properly 1.59 -> - added 've'-command (list autoconfig devices) - 'no auto stackreset'-option flag and 'rs'-command to reset the stack pointer - automatically initializes a0/d0 to point to an empty command line when 'l'-command is used to load a new executable file. 1.58 -> - changed window position/size logic. now monitor window should open to the visible part of a bigger-than-display screen. 1.57 -> - memory display displays only the requested memory block (the last line is not always full) 1.56 -> - memory display stops at end of hunk (disassembly already did that) - memory allocation error now stops script execution - added %s and %x formats to the mf-command 1.55 -> - uses TC_TrapData instead of TC_UserData again... - now the `(' command cannot allocate negative amounts of memory... - now the assembler understands `.b' as short branch specifier and `.w' as long branch specifier. - now frees memory properly in `u' command. 1.54 -> - added poke[w,l] commands 1.53 -> - better error reporting with scripts. 1.52 -> - scripts (exec/quit/if/goto/echo commands) - -command can be used to execute any cli/shell command. 1.51 -> - no longer lists bss hunks as split in strange ways (one lsl.l #2,d0 was missing in version 1.50) 1.50 -> - now mf-command requires space after command, else -> m fxxxx - show seglist displays info about split data/bss hunks - internal source reorganization 1.49 -> - hunk type display also shows chip/fast - some changes in symbol handling - internal source reorganization - disassembly stops at hunk end 1.48 -> - address register relative symbol support (rb-command) 1.47 -> - symbol support - variables now case sensitive - hunk type display in `sl'-command 1.46 -> - added breakpoint counts. 1.45 -> - small change in help text. 1.44 -> - added task/library/device/resource/port/semaphore list viewing commands. 1.43 -> - added formatted memory dump command - now gives error message if cannot allocate audio channels in digisound play command. - display can be stopped/started with ctrl-s/ctrl-q - spaces can be used in `set register' command before the equal sign. 1.42 -> - better option handling - understands 2.0 shell window close gadget - redirection to file now appends if possible - modulo operator now `%' 1.41 -> - fixed a bug that prevented some assembler instructions working. 1.40 -> - cd works correctly again (in 1.37..1.39 it ignored first letter of dir name...) 1.39 -> - interrupting `c' or `h' commands no longer causes error conditions. - added option flag 2 to select whether characters $a0-$ff are printable in `m' command memory dump. 1.38 -> - return from `j' or `g' commands with rts now works (was a major bug in 1.37) - input routine no longer acts strangely if shift-cursor-down or ESC-cursor/function/help is pressed. - command line automatically set if file name given on the monitor command line. - many little changes in assembler. most of these not visible to the user. 1.37 -> lots of new features... - major source code reorganization - extended checksum commands - calculator `ascii' output - memoryinfo displays hunk offsets - breakpoint numbers - added `port()' to expression parser 1.34 -> - added `narrow disassembly' option. - digisound player now defaults to play the sample once. 1.32 -> - now opens own window only if started with `run' or window width and height are given on the command line. can be used from serial terminal with AUX: shell. 1.31 -> - it is now not possible to accidentally try to assemble code to an odd address. 1.30 -> - many internal changes: global variable base register changed, uses new library call macros... 1.29 -> - added lib(), dev(), res() and task() to expression parser. 1.28 -> - modified patchtrace to work also when vector base is relocated. - small changes in initial window placement and size 1.27 -> - disk block/bootblock checksum functions and jump/go/trace etc. now check properly for odd addresses. - `odd address'-error message - skip instruction-command - Exit() now returns control back to the monitor. 1.26 -> - added hend() and nhunks-functions to the expression parser. - added command line options for window width and height - a file name to LoadSeg() can be given in the command line - new filename parse routine, now names with spaces in them must be in quotes 1.25 -> - (internal change) now uses TC_Userdata instead of TC_TrapData because TC_TrapData is marked as private in some prerelease 1.4/2.0 includes. - `'-command now first tries to start a shell, then a CLI. - disk read/write commands can be used with hard disks etc. - fixed condition code register setting with go and jump commands. 1.24 -> - corrected a small bug in the assembler/disassembler mnemonic tables (trap and tas-instructions were accidentally exchanged...) 1.23 -> - quicktrace-command - now reserves separate areas of stack for the monitor itself and the program being debugged. 1.22 -> - better handling of stack pointer with jump & go-commands - extended trace command - memory display can be used at odd addresses - generally cleaned up the source code - variables are now case-insensitive. 1.20 -> - added the `[register]'-syntax in the expression parser 1.19 -> - disassembler now uses new routines. this makes the monitor executable little smaller than 1.17 1.17 -> - monitor is now re-entrant and can be made resident - transfer no longer crashes if you transfer from location zero - default base is again hexadecimal 1.15 -> - some minor bug fixes in assembler (move sp,usp or exg Rx,sp did not work) - `memory info'-command - underscores are allowed in variable names - variable list is kept in alphabetical order 1.12 -> - expressions can now be used instead of numbers. also included calculator-command. - variables can be used in expressions. - user-defineable default number base, default is now decimal. - hunt-command no longer finds anything in the monitor code/data areas - show seglist now displays hunk numbers - chip memory allocation syntax has been changed. 1.08 -> - the monitor works ok with 68010/68020 processors. older versions left sometimes extra data in supervisor stack. 1.07 -> - The disassembler and assembler handle exg Dn,An correctly (previously the data and address register numbers were reversed) - The disassembler no more displays any invalid codes as valid instructions (On the 68000 processor, of course. The monitor does not currently support 68010/68020 extra instructions). - The pc-relative indexed addressing mode now works with the assembler. - Some little bugs were fixed in the assembler. + And/or-instructions work with a pc-relative source operand. + cmpm works with all sizes + most(if not all...) of the bugs that caused the assembler to assemble invalid instructions have been fixed. - `sp' can be used instead of `a7' in the assembler and the disassmbler displays a7 as `sp'. - The assembler now unserstands blo/bhs, slo/shs and dblo/sbhs and assembles them as bcs/bcc, scs/scc and dbcs/dbcc - The disassembler displays address-register relative offsets and short absolute addresses as signed numbers. - The monitor works now better with 60-column default font (TOPAZ60). - Disk read/write commands can be used with non-chip memory - Play digisound command has an optional parameter to specify how many times the sample is played. - A new command has been added to specify a command line for programs executed under the control of the monitor. - Breakpoints work even if you jump into the code at to breakpoint. The breakpoint does not activate until the instruction at the break position is executed, so you don't get immediately interrupted. (internally the monitor uses the trace-exception to skip the breakpoint at the first time...) 1.06 and older... - prehistoric versions... Contents of dev/moni/mon165.lha PERMISSION UID GID PACKED SIZE RATIO METHOD CRC STAMP NAME ---------- ----------- ------- ------- ------ ---------- ------------ ---------- [generic] 18863 28024 67.3% -lh5- 565e May 21 1994 mon [generic] 18267 50376 36.3% -lh5- ac67 May 21 1994 mon.doc [generic] 19288 54240 35.6% -lh5- 14e9 May 21 1994 mon.guide [generic] 116 116 100.0% -lh0- b6f3 May 21 1994 patchtrace ---------- ----------- ------- ------- ------ ---------- ------------ ---------- Total 4 files 56534 132756 42.6% May 22 1994 Aminet © 1992-2023 Urban Müller and the Aminet team. Aminet contact address: <aminetaminet net>
__label__pos
0.970182
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Join the Stack Overflow community to: 1. Ask programming questions 2. Answer and help your peers 3. Get recognized for your expertise I'm trying to implement Huffman coding by saving letters and their corresponding values into a map then inserting the map into a priority queue. I am getting a parameter conversion error when I try to declare my queue. What exactly am I supposed to put as the parameters? What I have here was my best guess. void main() { ifstream doc("doc.txt"); map<char, int> C; char letter; while(!doc.eof()){ doc.get(letter); if(letter >= 'a' && letter <= 'z') C[letter]++; } priority_queue<int, map<char,int>, greater<int> > Q(C); //also tried greater<map<char,int>> /*map<char, int>::const_iterator it; for(it = C.begin(); it != C.end(); it++) cout<<it->first<<" "<<it->second<<endl;*/ } I feel kind of dumb asking this but thorough googling did not get me the answer. Thanks a lot for the help! share|improve this question You cannot use a map as the underlying container for a priority_queue: the priority_queue must be free to reorder things in the container, which is not allowed for maps. Only vector and deque can be used (from the standard containers). So, the container type would be something like vector<pair<char, int> >. Then, you need a less/greater operation that only takes the second field of the pair into account. share|improve this answer      thanks a lot, Martin! – Bobby Dec 19 '10 at 21:39 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.725786
Bug #42500 Sysext form output not adjustable via ts in 4.7.5 Added by Bernhard Eckl over 5 years ago. Updated almost 3 years ago. Status: Closed Priority: Should have Assignee: - Category: - Target version: - Start date: 2012-10-29 Due date: % Done: 0% TYPO3 Version: 4.7 PHP Version: Tags: Complexity: Is Regression: No Sprint Focus: Description In T3 4.7.4 I used the following typoscript to adjust the output of the form sysext: ### Mailform ### tt_content.mailform.10.20 = tt_content.mailform.20.params.form = class="ym-form" #tt_content.mailform.20.stdWrap.dataWrap = <div class="ym-form">|</div> tt_content.mailform.20.stdWrap.wrap = <fieldset class="ym-form"> | </fieldset> tt_content.mailform.20.params.input = class="ym-fbox-text" #tt_content.mailform.20.params.password = class="mf-pass" tt_content.mailform.20.params.textarea = class="ym-fbox-text" #tt_content.mailform.20.params.check = class="mf-check" #tt_content.mailform.20.params.radio = class="mf-radio" tt_content.mailform.20.params.select = class="ym-fbox-select" tt_content.mailform.20.params.file = class="mf-file" tt_content.mailform.20.params.reset = class="ym-button" tt_content.mailform.20.params.submit = class="ym-button" #tt_content.mailform.20.layout = <div class="ym-fbox-text">###LABEL### ###FIELD###</div> #tt_content.mailform.20.COMMENT.layout = <div class="csc-mailform-label1">###LABEL###</div> tt_content.mailform.20.RADIO.layout = <div class="ym-fbox-check">###LABEL### <span class="csc-mailform-radio">###FIELD###</span></div> #tt_content.mailform.20.LABEL.layout = <div class="csc-mailform-field2">###LABEL### <span class="csc-mailform-label">###FIELD###</span></div> ### Mailform End ### But since 4.7.5, this does not work anymore. I also could not find any documentation about this. form-confirmation.png View (28.7 KB) Bernhard Eckl, 2013-05-13 20:55 Related issues Related to TYPO3 Core - Bug #31951: Own checkbox layout breaks HTML mail Resolved 2011-11-20 History #1 Updated by Georg Ringer over 5 years ago • Status changed from New to Needs Feedback can you specify what exactly doesn't work anymore and how this can be reproduced? #2 Updated by Bernhard Eckl over 5 years ago The whole typoscript above does not have any affect in 4.7.5 (maybe a few lines still work, I’m not 100% sure). E.g. this doesn’t have any affet in the frontend: tt_content.mailform.20.params.submit = class="ym-button" #3 Updated by Fabien Udriot over 5 years ago Checkout manual in SYSEXT:form/Documentation/Manual/en/manual.sxw. Wouldn't it be more this kind of configuration of the FORM object to tamper? [...] Update: I am also facing the problem that the mailform configuration is not applied (running a 4.7.5 TYPO3 too). I haven't dug more than that. #4 Updated by Tomas Havner about 5 years ago Try: tt_content.mailform.20 { stdWrap.wrap > layout { form ( <form class="form-horizontal"> <containerWrap /> </form> ) containerWrap ( <section> <elements /> </section> ) elementWrap ( <div> <element /> </div> ) mandatory ( <sup class="ym-required"> <mandatoryvalue /> </sup> ) error ( <strong class="ym-message"> <errorvalue /> </strong> ) textline ( <div class="control-group"> <label class="control-label"><label /></label> <div class="controls"><input /></div> </div> ) textarea ( <div class="ym-fbox-text"> <label /> <textarea /> </div> ) select ( <div class="ym-fbox-select"> <label /> <select> <elements /> </select> </div> ) checkbox ( <div class="ym-fbox-check"> <input /> <label /> </div> ) radio ( <div class="ym-fbox-check"> <input /> <label /> </div> ) button ( <div class="ym-fbox-button"> <input /> </div> ) reset ( <div class="ym-fbox-button"> <input /> </div> ) submit ( <div class="ym-fbox-button"> <input /> </div> ) } } /Tomas #5 Updated by Bernhard Eckl almost 5 years ago Does not work. Any other ideas, is there somebody who knows how it works actually? In my case I want to add the classes needed to apply css for the yaml css framework (without changing all the css). I think this should also get integrated into the manual to know how to adjust the output (if it is already known). Here is also described how it worked in the past: http://forge.typo3.org/issues/42500 #6 Updated by Bernhard Eckl almost 5 years ago I just tested the typoscript of Tomas Havner again in the new T3 6.1 and it works now (I also found the part in the manual now). BUT: If confirmation is activated, the confirmation page is broken, the text in the form is not displayed and it is not possible to send the form. Here is the html output of the confirmation page and enclosed also a screenshot (confirmation page should not use the typoscript for the layout): <section> <div class="csc-form-2 csc-form-element csc-form-element-textline"> <div class="ym-fbox-text"> <label>Vorname</label> <div class="controls"> <input/> </div> </div> </div> <div class="csc-form-3 csc-form-element csc-form-element-textline"> <div class="ym-fbox-text"> <label>Nachname</label> <div class="controls"> <input/> </div> </div> </div> <div class="csc-form-4 csc-form-element csc-form-element-textline"> <div class="ym-fbox-text"> <label>Firma</label> <div class="controls"> <input/> </div> </div> </div> <div class="csc-form-5 csc-form-element csc-form-element-textline"> <div class="ym-fbox-text"> <label>E-Mail</label> <div class="controls"> <input/> </div> </div> </div> <div class="csc-form-6 csc-form-element csc-form-element-textline"> <div class="ym-fbox-text"> <label>Betreff</label> <div class="controls"> <input/> </div> </div> </div> <div class="csc-form-7 csc-form-element csc-form-element-textarea"> <div class="ym-fbox-text"> <label>Nachricht</label> <textarea/> </div> </div> </section> <form class="csc-form-confirmation" method="post" action="kontakt/"> <fieldset> <ol> <li class="csc-form-confirmation-false"> <input type="submit" value="Zurück zum Formular" name="tx_form[confirmation-false]" /> </li> <li class="csc-form-confirmation-true"> <input type="submit" value="Bestätigen" name="tx_form[confirmation-true]" /> </li> </ol> </fieldset> </form> #7 Updated by Alexander Opitz over 4 years ago • Status changed from Needs Feedback to New • Is Regression set to No #8 Updated by Bernhard Eckl almost 4 years ago Again I had the same problem and solved it by hardcoding into the ext (quick and dirty). The thing is, that for confirmation and mail there should be other typoscript arrays. Changes (T3 4.7, brackets are replaced by this board…): Classes/View/Confirmation: line 137 return '&lt;form class="csc-form-confirmation ym-form" method="post" action="' . $action . '"&gt;'.$this->localCobj->cObjGetSingle($type, $value); (The form tag should be at the beginning, otherwise some classes of CSS frameworks are not working) Classes/View/Mail/Html/Element/Abstract.php: line 221-223 $layout = str_replace('&lt;input /&gt;', '&lt;/td&gt;&lt;td&gt;&lt;inputvalue /&gt;', $layout); $layout = str_replace('&lt;textarea /&gt;', '&lt;/td&gt;&lt;td&gt;&lt;inputvalue /&gt;', $layout); $layout = str_replace('&lt;div class="ym-fbox-text clearfix"&gt;', '&lt;td class="labeltd" style="width: 200px;" &gt;', $layout); $layout = str_replace('&lt;/div&gt;', '&lt;/td&gt;', $layout); And in case elementWrap: $layout = str_replace('&lt;div&gt;', '&lt;tr&gt;', $layout); $layout = str_replace('&lt;/div&gt;', '&lt;/tr&gt;', $layout); And in containerWrap: $layout = str_replace('&lt;section&gt;', '&lt;tr&gt;', $layout); $layout = str_replace('&lt;/section&gt;', '&lt;/tr&gt;', $layout); Classes/View/Confirmation/Element/Abstract.php: lines 225-226 $layout = str_replace('&lt;input /&gt;', '&lt;inputvalue /&gt;', $layout); $layout = str_replace('&lt;textarea /&gt;', '&lt;inputvalue /&gt;', $layout); This works with the following typoscript: tt_content.mailform.20 { #stdWrap.wrap > layout { form ( <form class="ym-form ym-columnar"> <containerWrap /> </form> ) containerWrap ( <section> <elements /> </section> ) elementWrap ( <div> <element /> </div> ) mandatory ( <sup class="ym-required"> <mandatoryvalue /> </sup> ) error ( <strong class="ym-message"> <errorvalue /> </strong> ) textline ( <div class="ym-fbox-text clearfix"> <label /> <input /> </div> ) textarea ( <div class="ym-fbox-text clearfix"> <label /> <textarea /> </div> ) select ( <div class="ym-fbox-select"> <label /> <select> <elements /> </select> </div> ) checkbox ( <div class="ym-fbox-check"> <input /> <label /> </div> ) radio ( <div class="ym-fbox-check"> <label /> <input /> </div> ) button ( <div class="ym-fbox-button"> <label /> <input /> </div> ) reset ( <div class="ym-fbox-button"> <label /> <input /> </div> ) submit ( <div class="ym-fbox-button"> <label /> <input /> </div> ) } } So please add additional Typoscript layout options for confirmation and for mail (input can not be used for confirmation and mail, there it should be inputvalue, this is the main problem). #9 Updated by Bernhard Eckl over 3 years ago I just had a new project starting with TYPO3 6.2, I also switched to Bootstrap, and I also used extension bootstrap_package. So with this system there is still the same problem (problem can be easily reproduced, the current Demo is based on that version and bootstrap_package, you just have to change the form to get a mail (then you can see that the mail content is buggy) and activate confirmation page (then you can see the broken confirmation page). This is because bootstrap_package has some typoscript for styling the form, but the same problem occurs as I mentioned. Please can someone fix that?! I don’t want to be a lonely talker… #10 Updated by Frans Saris over 3 years ago I think this one can be closed now #31951 is reloved. #11 Updated by Frans Saris over 3 years ago • Status changed from New to Needs Feedback #12 Updated by Riccardo De Contardi almost 3 years ago • Status changed from Needs Feedback to Closed If you think that this is the wrong decision or experience this issue again, then please write to the mailing list typo3.teams.bugs with issue number and an explanation or open a new ticket and add a relation to this ticket number. Also available in: Atom PDF
__label__pos
0.65365
Cut The Knot! An interactive column using Java applets by Alex Bogomolny Pick's Theorem May 1998 Georg Alexander Pick, born in 1859 in Vienna, perished around 1943 in the Theresienstadt concentration camp. [9] First published in 1899, the theorem was brought to broad attention in 1969 through the popular Mathematical Snapshots by H. Steinhaus. The theorem gives an elegant formula for the area of simple lattice polygons, where "simple", as usual, only means the absence of self-intersection. Polygons covered by the theorem have their vertices located at nodes of a square grid or lattice whose nodes are spaced at distance 1 from their immediate neighbors. The formula does not require math proficiency beyond middle grade school and can be easily verified with the help of a geoboard. Pick's Theorem Let P be a lattice polygon. Assume there are I(P) lattice points in the interior of P, and B(P) lattice points on its boundary. Let A(P) denote the area of P. Then A(P) = I(P) + B(P)/2 - 1 As of 2018, Java plugins are not supported by any browsers (find out more). This Wolfram Demonstration, Pick's Theorem, shows an item of the same or similar topic, but is different from the original Java applet, named 'Pick'. The originally given instructions may no longer correspond precisely. (The applet uses an adaptation of a scan conversion algorithm from [13]. The book is replete with ideas. It just appears that this one was not worked out completely. The applet also appears on a separate page from where it could be lifted for use by teachers on their own pages.) With Pick's theorem one may determine area of a (polygonal) portion of a map. On a transparent paper draw a grid to scale and superimpose the grid over the map. Count the number of nodes inside and on the boundary of the map region. Apply Pick's formula with the selected scale. More importantly, there are links to several other beautiful results. Pick's formula is equivalent to the celebrated Euler's formula [7]. It also implies the basic property of the Farey Series. The Farey series FN of order n is the ascending sequence of irreducible fractions m/n between 0 and 1 whose denominators do not exceed N. A fraction m/n belongs to FN iff 0 ≤ m ≤ N, gcd(m,n) = 1, where gcd(m,n) is the greatest common divisor of m and n. For example, F5 is 0/1, 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5, 1/1 Farey series is characterized by two wonderful equivalent properties. G.H. Hardy who prided himself in not having done anything "useful", found it worthwhile to include three different proofs of the basic property of the Farey series in his and E.M. Wright's book. (This is a classical work with the Index located not at the end of the book but, in a contemporary manner, elsewhere on the Web. You'll have to look hard to find it there as the url has been changing.) The sequence of denominators of terms in the Farey series is palindromic. The proof may not be immediately obvious. But, as is often the case, having a bigger picture proves useful. The Farey series are embedded into the Stern-Brocot tree for which this property comes almost for free. The area measurement application of Pick's theorem I mentioned above comes from the real world experience. Grünbaum and Shepard quote D.W. DeTemple who attended a presentation on application of mathematics in the forest industry: Although the speaker was not aware that he was essentially using Pick's formula, I was delighted to see that one of my favorite mathematical results was not only beautiful, but even useful. I am rather curious whether the forester shared in the delight. There is no surprise in that mathematics is useful. Even G.H. Hardy will be remembered in part because of the Hardy-Weinberg law which became centrally important in the study of many genetic problems [6]. I am charmed by the title of an undergraduate text, Applied Abstract Algebra (R. Lidl and G. Pilz, Springer-Verlag, 1997, 2nd edition.) What would Hardy say? The goal of course is to pass the delight on. References 1. A.H. Beiler, Recreations in The Theory of Numbers, Dover, 1966 2. M. Bruckheimer and A. Arcavi, Farey Series and Pick's Area Theorem, The Mathematical Intelligencer v 17 (1995), no 4, pp 64-67. 3. J. Cofman, Numbers and Shapes Revisited, Clarendon Press, 1995 4. J. Conway and R. Guy, The Book of Numbers, Copernicus, 1996 5. H.S.M. Coxeter, Introduction to Geometry, John Wiley & Sons, NY, 1961 6. Encyclopædia Britannica 7. W.W. Funkenbusch, From Euler's Formula to Pick's Formula Using an Edge Theorem, The Am Math Monthly v 81 (1974), pp 647-648 8. R. Graham, D. Knuth, O. Patashnik, Concrete Mathematics, 2nd edition, Addison-Wesley, 1994. 9. B.Grünbaum and G.C.Shepard, Pick's Theorem, The Am Math Monthly v 100(1993), pp 150-161 10. G.H. Hardy, A Mathematician's Apology, Cambridge University Press, 1994. 11. G.H. Hardy and E.M. Wright, An Introduction to the Theory of Numbers, Oxford University Press, Fifth Edition, 1sshu996 12. R. Honsberger, Ingenuity in Mathematics, MAA, 1970 13. T. Pavlidis, Algortihms for Graphics and Image Processing, Computer Science Press, 1982 14. H. Steinhaus, Mathematical Snapshots, Dover, 1999 15. D.E. Varberg, Pick's Theorem Revisited, The Am Math Monthly v 92(1985), pp 584-587 On Internet 1. Euler's Formula, Proof 10: Pick's Theorem 2. Farey Sequence 3. Farey Series 4. Geoboards in Classroom 5. Pick's Theorem 6. Stern-Brocot Tree 68226408 |Contact| |Front page| |Contents| Copyright © 1996-2018 Alexander Bogomolny
__label__pos
0.616073
Cara Mendeteksi hardware komputer (spesifikasi hardware) menggunakan PC Wizard Ketika kita hendak ingin membeli komputer kita pasti ingin mengetahui bahwa pc/ laptop yang dibeli spesifikasinya sesuai dengan yang tercantum pada brosur penjualan/ banner yang terpasang di pc/ laptop. Terdapat banyak cara untuk Mendeteksi spesifikasi hardware komputer dari cara yang manual, cara menggunakan software yang gratis dan dengan cara menggunakan software yang berbayar. Pada postingna kali ini saya akan membahas mengenai cara mendeteksi hardware komputer dengan menggunakan software yang gratis yang bernama PC Wizard, yang membuat software PC Wizard into sama dengan team yang membuat software gratis lainnya seperti hwmonitor, cpuz, serta beberapa software lainnya yang digunakanuntuk mendeteksi hardware komputer. Dengan menggunakan PC Wizard kita dapat mendeteksi hardware computer dengan hasil yang cukup komplit, berikut ini adalah contoh tampilan dari PC Wizard: Cara Mendeteksi hardware komputer (spesifikasi hardware) menggunakan PC Wizard Jika anda tertarik dan ingin menggunakan software di atas dapat mendownloadnya disini: PC Wizard. Software PC wizard ini bisa di jalankan dengan baik di Windows XP. Selain cara tersebut terdapat cara.lain yang dapat digunakan untuk mengetahui hardware computer silahkan anda baca artikel berikut ini: - Mengetahui spesifikasi hardware menggunakan speccy. - Cara mengetahui spesifikasi hardware komputer menggunakan Direct Diagnostic dan CPUZ. - Mendeteksi hardware yang tidak dikenali windows menggunakan Unkown Device Indentifier. - Menggunakan GPU-Z untuk mengetahui spesifikasi VGA. - Cara manual yaitu dengan cara membongkar/ melepas casing komputer dan mengecek komponen computer satu persatu. Setiap cara yang digunakan untuk mendeteksi hardware computer, tiap-tiap metode memiliki kelebihan dan kekurangan, tetapi jika berbagai metode tersebut digabungkan dapat saling melengkapi. Demikian yang dapat saya sampiakan mengenai Cara Mendeteksi hardware komputer (spesifikasi hardware) menggunakan PC Wizard semoga dapat bermanfaat. Berlangganan Artikel Melalui Email! Suka dengan artikel kami? Daftarkan email anda di sini untuk mendapatkan artikel terbaru
__label__pos
0.998365
Guest Find the quadratic polynomial if its zeroes are 0, √5. Find the quadratic polynomial if its zeroes are 0, √5. Grade:12 1 Answers Harshit Singh askIITians Faculty 5963 Points 3 years ago Dear Student A quadratic polynomial can be written using the sum and product of its zeroes is: x^2– (α + β)x + αβ Where α and β are the roots of the polynomial. Here, α = 0 and β = √5 So, the polynomial will be: x^2– (0 + √5)x + 0(√5) ⇒ x^2– √5x Thanks Think You Can Provide A Better Answer ? ASK QUESTION Get your questions answered by the expert for free
__label__pos
0.999658
001package org.cpsolver.ifs.assignment.context; 002 003import org.cpsolver.ifs.assignment.Assignment; 004import org.cpsolver.ifs.assignment.DefaultSingleAssignment; 005import org.cpsolver.ifs.model.Value; 006import org.cpsolver.ifs.model.Variable; 007 008/** 009 * A simple assignment context holder implementation used by the {@link DefaultSingleAssignment} class. 010 * {@link CanHoldContext} are used when possible, storing contexts in arrays of length 1 (one context per 011 * {@link HasAssignmentContext} class). 012 * 013 * @see AssignmentContext 014 * @see AssignmentContextReference 015 * @see AssignmentContextHolder 016 * 017 * @version IFS 1.3 (Iterative Forward Search)<br> 018 * Copyright (C) 2014 Tomáš Müller<br> 019 * <a href="mailto:[email protected]">[email protected]</a><br> 020 * <a href="http://muller.unitime.org">http://muller.unitime.org</a><br> 021 * <br> 022 * This library is free software; you can redistribute it and/or modify 023 * it under the terms of the GNU Lesser General Public License as 024 * published by the Free Software Foundation; either version 3 of the 025 * License, or (at your option) any later version. <br> 026 * <br> 027 * This library is distributed in the hope that it will be useful, but 028 * WITHOUT ANY WARRANTY; without even the implied warranty of 029 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 030 * Lesser General Public License for more details. <br> 031 * <br> 032 * You should have received a copy of the GNU Lesser General Public 033 * License along with this library; if not see <a href='http://www.gnu.org/licenses'>http://www.gnu.org/licenses</a>. 034 * @param <V> Variable 035 * @param <T> Value 036 **/ 037public class DefaultSingleAssignmentContextHolder<V extends Variable<V, T>, T extends Value<V, T>> extends AssignmentContextHolderMap<V, T> { 038 039 public DefaultSingleAssignmentContextHolder() { 040 } 041 042 @Override 043 @SuppressWarnings("unchecked") 044 public <U extends AssignmentContext> U getAssignmentContext(Assignment<V, T> assignment, AssignmentContextReference<V, T, U> reference) { 045 if (reference.getParent() instanceof CanHoldContext) { 046 AssignmentContext[] contexts = ((CanHoldContext)reference.getParent()).getContext(); 047 if (contexts[0] == null) 048 contexts[0] = reference.getParent().createAssignmentContext(assignment); 049 return (U)contexts[0]; 050 } else { 051 return super.getAssignmentContext(assignment, reference); 052 } 053 } 054 055 @Override 056 public <C extends AssignmentContext> void clearContext(AssignmentContextReference<V, T, C> reference) { 057 if (reference.getParent() instanceof CanHoldContext) { 058 AssignmentContext[] contexts = ((CanHoldContext)reference.getParent()).getContext(); 059 contexts[0] = null; 060 } else { 061 super.clearContext(reference); 062 } 063 } 064}
__label__pos
0.965755
Dismiss Notice Join Physics Forums Today! The friendliest, high quality science and math community on the planet! Everyone who loves science is here! Does a subsequence only have to have some terms 1. Feb 16, 2005 #1 Does a subsequence only have to have "some" terms This is an example from my text, which I do not understand. Suppose (s_n)is a sequence of POSITIVE numbers such that inf{s_n | n in NaturalNumbers} = 0. The sequence need not converge or even be bounded , but it has a subsequence that converges monotonically. They then give a recursive process on how to pick the elements of the subsequence. My problem is as follows. Suppose the sequence is: s_n = (n - 10)^2 This is a shifted parabola (but sequence) that has an inf = 0. A subsequence must have infinite terms, correct? I can see how you can pick terms starting from the left hand side of the vertex, and pick a monotone decreasing terms up to the vertex (0, 0), but what about after that? s_n starts moving back up and goes to +infinity. So past a certain point, we can't pick anymore points off s_n for our subsequence and keep the monotonicity of it. So what am I missing? Does a subsequence only have to have "some" terms from the main sequence it is a subsequence of?   2. jcsd 3. Feb 16, 2005 #2 learningphysics User Avatar Homework Helper But this isn't a sequence of positive numbers s_10=0.   4. Feb 16, 2005 #3 HallsofIvy User Avatar Science Advisor Do you see why that's important? If you allowed 0 in the sequence or if the inf was a positive number, then a sequence that included inf but all other numbers might be far away from it which would violate your conclusion. The inf of the sequence is 0 but 0 itself cannot be in the sequence! Given any integer n, let ε= 1/n. Are there any members of the sequence less than ε?   Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook Loading...
__label__pos
0.996741
A monetary and historical view of the taxes which impede the education of the people. However, additionally it is concerned with happiness and relationships, the problems and problems of on a regular basis life in communities, and questions around how persons are finest to live their lives. God solutions the questions proper in the context. Evil that he is aware of, that he’s satisfied, he might commit given the best circumstances. The fitting knowledge administration software will enable staff to simply and quickly seek for content, ask questions, find consultants, and store documents and videos. Knowledge switch is the process by which experienced staff share or distribute their knowledge, abilities and behaviors to the workers changing them. In case you need an example of express knowledge, merely open your knowledge management platform and have a look round. The example of Job and the phrases of Jesus Himself inform us otherwise. It is evident from the phrases above like discover, instruct, perceive, perceive that only people, and no other animate beings, can study the knowledge referred to here. It’s the comprehension that the human mind and mind can attain to, however limited to human intellectual capability and understanding. Note that because of luck, a belief may be unjustified yet true; and due to human fallibility, a belief will be justified but false. We should answer the question: How can good lead to demise? In Genesis 2:17, the great is associated with the Tree of Knowledge of fine and Evil that leads to demise. In the ultimate many years of 20th century, the knowledge financial system turned tremendously associated with sectors based mostly in research-intensive and high-technology industries because of the steadily increased demand for refined science-based improvements. You can use the knowledge trade framework (KEF) to explore data and explanations of the other ways universities collaborate with exterior partners, from businesses to neighborhood groups, for the advantage of the financial system and society. Work to create the KEF started in 2017, when the Minister of State for Universities, Science, Research and Innovation commissioned the upper Education Funding Council for England (HEFCE) to offer more information about HEP achievements in serving the financial system and society for the advantage of the general public, enterprise and communities. The KEF evaluate report detailing the findings of the evaluate with recommendations for future development was revealed in February 2022. We subsequently sought feedback from the sector on specific proposals for changes to the second iteration of the KEF by way of a KEF options survey, along with future course of travel for the KEF dashboard design and narrative. The review also demonstrated a preference for narrative statement updates to solely happen on a 2 or 3 year cycle. For these causes KEF2 continues to show the narrative statements included in the primary iteration of the KEF. Following publication of the first iteration of KEF ends in March 2021, we reviewed the KEF based mostly on suggestions from the sector and customers. You can read extra about the event of the KEF and discover associated documentation. Within the Enneads, epistêmê is indirectly related to technê. In one place, Aristotle says that what distinguishes experience (empeiria) from technê is that the latter has a rational account, which explains what it does. One implication of Noam Chomsky’s innatism, if right, is that at the very least a part of human knowledge consists in cognitive predispositions, which are triggered and developed by the surroundings, but not decided by it. Analysis of the survey outcomes, choices for the design of KEF2 and future iterations are set out in the KEF2 decisions document. But a representation with these targets can not single out any specific set of inferences to recommend, for 2 reasons. Just think of the 2 commandments in the brand new Covenant. Since their corn will ripen at totally different times, the two farmers can ensure full harvests for themselves by serving to one another when their crops ripen, and each know this. Those that may determine it out will derive as a lot energy and profit as information and information brought in their turn. Each innovation will itself be equivalent to an input underneath the law of diminishing marginal returns. If I predict on Monday that on Tuesday my head will hurt, that claim is falsified both if I have no headache on Tuesday, or if, on Tuesday, there is someone who is by convention picked out as my continuant whose head does not harm. It’s apparent how, given flux, a present-tense claim like “Item X is present” can shortly stop to be true, because e.g., “Item Y is present” involves exchange it.
__label__pos
0.677905
bs4 timeline Bootstrap snippet. bs4 timeline, this snippet was created to help web designers, front-end developers and back-end developer save time. Use it in your project and build your app faster, You can also download the HTML, CSS, and JS code. tags: timeline,list HTML code Copy, paste, change, customize and run the following HTML code to get a result like the one shown in the preview selection <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"> <div class="container"> <ul class="timeline"> <li> <!-- begin timeline-time --> <div class="timeline-time"> <span class="date">today</span> <span class="time">04:20</span> </div> <!-- end timeline-time --> <!-- begin timeline-icon --> <div class="timeline-icon"> <a href="javascript:;">&nbsp;</a> </div> <!-- end timeline-icon --> <!-- begin timeline-body --> <div class="timeline-body"> <div class="timeline-header"> <span class="userimage"><img src="http://bootdey.com/img/Content/avatar/avatar1.png" alt=""></span> <span class="username"><a href="javascript:;">John Smith</a> <small></small></span> <span class="pull-right text-muted">18 Views</span> </div> <div class="timeline-content"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc faucibus turpis quis tincidunt luctus. Nam sagittis dui in nunc consequat, in imperdiet nunc sagittis. </p> </div> <div class="timeline-likes"> <div class="stats-right"> <span class="stats-text">259 Shares</span> <span class="stats-text">21 Comments</span> </div> <div class="stats"> <span class="fa-stack fa-fw stats-icon"> <i class="fa fa-circle fa-stack-2x text-danger"></i> <i class="fa fa-heart fa-stack-1x fa-inverse t-plus-1"></i> </span> <span class="fa-stack fa-fw stats-icon"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-thumbs-up fa-stack-1x fa-inverse"></i> </span> <span class="stats-total">4.3k</span> </div> </div> <div class="timeline-footer"> <a href="javascript:;" class="m-r-15 text-inverse-lighter"><i class="fa fa-thumbs-up fa-fw fa-lg m-r-3"></i> Like</a> <a href="javascript:;" class="m-r-15 text-inverse-lighter"><i class="fa fa-comments fa-fw fa-lg m-r-3"></i> Comment</a> <a href="javascript:;" class="m-r-15 text-inverse-lighter"><i class="fa fa-share fa-fw fa-lg m-r-3"></i> Share</a> </div> <div class="timeline-comment-box"> <div class="user"><img src="http://bootdey.com/img/Content/avatar/avatar6.png"></div> <div class="input"> <form action=""> <div class="input-group"> <input type="text" class="form-control rounded-corner" placeholder="Write a comment..."> <span class="input-group-btn p-l-10"> <button class="btn btn-primary f-s-12 rounded-corner" type="button">Comment</button> </span> </div> </form> </div> </div> </div> <!-- end timeline-body --> </li> <li> <!-- begin timeline-time --> <div class="timeline-time"> <span class="date">24 February 2014</span> <span class="time">08:17</span> </div> <!-- end timeline-time --> <!-- begin timeline-icon --> <div class="timeline-icon"> <a href="javascript:;">&nbsp;</a> </div> <!-- end timeline-icon --> <!-- begin timeline-body --> <div class="timeline-body"> <div class="timeline-header"> <span class="userimage"><img src="http://bootdey.com/img/Content/avatar/avatar1.png" alt=""></span> <span class="username">Richard Leong</span> <span class="pull-right text-muted">1,282 Views</span> </div> <div class="timeline-content"> <p class="lead"> <i class="fa fa-quote-left fa-fw pull-left"></i> Quisque sed varius nisl. Nulla facilisi. Phasellus consequat sapien sit amet nibh molestie placerat. Donec nulla quam, ullamcorper ut velit vitae, lobortis condimentum magna. Suspendisse mollis in sem vel mollis. <i class="fa fa-quote-right fa-fw pull-right"></i> </p> </div> <div class="timeline-footer"> <a href="javascript:;" class="m-r-15 text-inverse-lighter"><i class="fa fa-thumbs-up fa-fw fa-lg m-r-3"></i> Like</a> <a href="javascript:;" class="m-r-15 text-inverse-lighter"><i class="fa fa-comments fa-fw fa-lg m-r-3"></i> Comment</a> <a href="javascript:;" class="m-r-15 text-inverse-lighter"><i class="fa fa-share fa-fw fa-lg m-r-3"></i> Share</a> </div> </div> <!-- end timeline-body --> </li> <li> <!-- begin timeline-time --> <div class="timeline-time"> <span class="date">10 January 2014</span> <span class="time">20:43</span> </div> <!-- end timeline-time --> <!-- begin timeline-icon --> <div class="timeline-icon"> <a href="javascript:;">&nbsp;</a> </div> <!-- end timeline-icon --> <!-- begin timeline-body --> <div class="timeline-body"> <div class="timeline-header"> <span class="userimage"><img src="http://bootdey.com/img/Content/avatar/avatar1.png" alt=""></span> <span class="username">Lelouch Wong</span> <span class="pull-right text-muted">1,021,282 Views</span> </div> <div class="timeline-content"> <h4 class="template-title"> <i class="fa fa-map-marker text-danger fa-fw"></i> 795 Folsom Ave, Suite 600 San Francisco, CA 94107 </h4> <p>In hac habitasse platea dictumst. Pellentesque bibendum id sem nec faucibus. Maecenas molestie, augue vel accumsan rutrum, massa mi rutrum odio, id luctus mauris nibh ut leo.</p> <p class="m-t-20"> <img src="http://bootdey.com/img/Content/avatar/avatar7.png" alt=""> </p> </div> <div class="timeline-footer"> <a href="javascript:;" class="m-r-15 text-inverse-lighter"><i class="fa fa-thumbs-up fa-fw fa-lg m-r-3"></i> Like</a> <a href="javascript:;" class="m-r-15 text-inverse-lighter"><i class="fa fa-comments fa-fw fa-lg m-r-3"></i> Comment</a> <a href="javascript:;" class="m-r-15 text-inverse-lighter"><i class="fa fa-share fa-fw fa-lg m-r-3"></i> Share</a> </div> </div> <!-- end timeline-body --> </li> <li> <!-- begin timeline-icon --> <div class="timeline-icon"> <a href="javascript:;">&nbsp;</a> </div> <!-- end timeline-icon --> <!-- begin timeline-body --> <div class="timeline-body"> Loading... </div> <!-- begin timeline-body --> </li> </ul> </div> CSS code Copy, paste, change, customize and run the following CSS code to get a result Like the one shown in the preview selection body{ margin-top:20px; background:#eee; } .timeline { list-style-type: none; margin: 0; padding: 0; position: relative } .timeline:before { content: ''; position: absolute; top: 5px; bottom: 5px; width: 5px; background: #2d353c; left: 20%; margin-left: -2.5px } .timeline>li { position: relative; min-height: 50px; padding: 20px 0 } .timeline .timeline-time { position: absolute; left: 0; width: 18%; text-align: right; top: 30px } .timeline .timeline-time .date, .timeline .timeline-time .time { display: block; font-weight: 600 } .timeline .timeline-time .date { line-height: 16px; font-size: 12px } .timeline .timeline-time .time { line-height: 24px; font-size: 20px; color: #242a30 } .timeline .timeline-icon { left: 15%; position: absolute; width: 10%; text-align: center; top: 40px } .timeline .timeline-icon a { text-decoration: none; width: 20px; height: 20px; display: inline-block; border-radius: 20px; background: #d9e0e7; line-height: 10px; color: #fff; font-size: 14px; border: 5px solid #2d353c; transition: border-color .2s linear } .timeline .timeline-body { margin-left: 23%; margin-right: 17%; background: #fff; position: relative; padding: 20px 25px; border-radius: 6px } .timeline .timeline-body:before { content: ''; display: block; position: absolute; border: 10px solid transparent; border-right-color: #fff; left: -20px; top: 20px } .timeline .timeline-body>div+div { margin-top: 15px } .timeline .timeline-body>div+div:last-child { margin-bottom: -20px; padding-bottom: 20px; border-radius: 0 0 6px 6px } .timeline-header { padding-bottom: 10px; border-bottom: 1px solid #e2e7eb; line-height: 30px } .timeline-header .userimage { float: left; width: 34px; height: 34px; border-radius: 40px; overflow: hidden; margin: -2px 10px -2px 0 } .timeline-header .username { font-size: 16px; font-weight: 600 } .timeline-header .username, .timeline-header .username a { color: #2d353c } .timeline img { max-width: 100%; display: block } .timeline-content { letter-spacing: .25px; line-height: 18px; font-size: 13px } .timeline-content:after, .timeline-content:before { content: ''; display: table; clear: both } .timeline-title { margin-top: 0 } .timeline-footer { background: #fff; border-top: 1px solid #e2e7ec; padding-top: 15px } .timeline-footer a:not(.btn) { color: #575d63 } .timeline-footer a:not(.btn):focus, .timeline-footer a:not(.btn):hover { color: #2d353c } .timeline-likes { color: #6d767f; font-weight: 600; font-size: 12px } .timeline-likes .stats-right { float: right } .timeline-likes .stats-total { display: inline-block; line-height: 20px } .timeline-likes .stats-icon { float: left; margin-right: 5px; font-size: 9px } .timeline-likes .stats-icon+.stats-icon { margin-left: -2px } .timeline-likes .stats-text { line-height: 20px } .timeline-likes .stats-text+.stats-text { margin-left: 15px } .timeline-comment-box { background: #f2f3f4; margin-left: -25px; margin-right: -25px; padding: 20px 25px } .timeline-comment-box .user { float: left; width: 34px; height: 34px; overflow: hidden; border-radius: 30px } .timeline-comment-box .user img { max-width: 100%; max-height: 100% } .timeline-comment-box .user+.input { margin-left: 44px } .lead { margin-bottom: 20px; font-size: 21px; font-weight: 300; line-height: 1.4; } .text-danger, .text-red { color: #ff5b57!important; } Similar snippets Bootstrap snippet bs4 project list with progress bs4 project list with progress View Bootstrap snippet bs4 Horizontal timeline bs4 Horizontal timeline View Bootstrap snippet bs4 account tickets bs4 account tickets View About this snippet Creator: Dey Dey Bootstrap version: 4.1.1 Created: Jun 17th 2018, 21:09 Views: 2.1K Rated 5/5 based on 17 reviews
__label__pos
0.638772
Back to index courier  0.68.2 rematch.h Go to the documentation of this file. 00001 #ifndef rematch_h 00002 #define rematch_h 00003 00004 00005 #include "config.h" 00006 #include <sys/types.h> 00007 // #include <unistd.h> 00008 00010 // 00011 // ReMatch is an abstract class used in matching text against regular 00012 // expression. The matched text may come from a memory buffer, or a file. 00013 // The matching logic does not care, and uses an abstracted data source, 00014 // represented by this class, which supplies the text being matched, 00015 // character by character. 00016 // 00017 // Also, in order to support the '!' operator, GetCurrentPos() and 00018 // SetCurrentPos() functions must be implemented as a rudimentary "seek" 00019 // mechanism. 00020 // 00022 00023 class ReMatch { 00024 public: 00025 ReMatch() {} 00026 virtual ~ReMatch(); 00027 00028 virtual int NextChar()=0; 00029 virtual int CurrentChar()=0; 00030 virtual off_t GetCurrentPos()=0; 00031 virtual void SetCurrentPos(off_t)=0; 00032 } ; 00033 #endif
__label__pos
0.866421
Click here to Skip to main content 11,706,799 members (50,330 online) Click here to Skip to main content Add your own alternative version VB6 - C# Interop Form Toolkit , 2 Oct 2006 CPOL 122.4K 2.6K 25 Interop Form Toolkit was released few days ago. It allows an easy creation of mixed VB6/VB.NET application. One thing it is missing is the ability to do it in C#. interopformcsbinaries.zip Binaries InteropFormAddIn.AddIn InteropFormAddIn.dll VB6 Interop Form Library C#.zip C# Interop Form.zip interopformcssource.zip Source InteropFormAddIn InteropFormAddIn.AddIn InteropFormAddIn.csproj.user ��using System; using Extensibility; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.CommandBars; using System.Resources; using System.Reflection; using System.Globalization; using System.Collections.Generic; using System.Windows.Forms; using System.IO; using System.CodeDom; using System.CodeDom.Compiler; using Microsoft.CSharp; using Microsoft.InteropFormTools; namespace InteropFormAddIn { /// <summary>The object for implementing an Add-in.</summary> /// <seealso class='IDTExtensibility2' /> public class Connect : IDTExtensibility2, IDTCommandTarget { /// <summary>Implements the constructor for the Add-in object. Place your initialization code within this method.</summary> public Connect() { this._attrTypeForm = typeof(InteropFormAttribute); this._attrTypeInitializer = typeof(InteropFormInitializerAttribute); this._attrTypeProperty = typeof(InteropFormPropertyAttribute); this._attrTypeMethod = typeof(InteropFormMethodAttribute); this._attrTypeEvent = typeof(InteropFormEventAttribute); this._supportedTypes = null; this.EVENT_ARGS_COMMENT = String.Format("{0}{1}{2}{3}{4}", new object[] {Resource.EVENT_ARGS_COMMENT1, "\r\n", Resource.EVENT_ARGS_COMMENT2, "\r\n", Resource.EVENT_ARGS_COMMENT3 }); try { this.LoadSupportedTypes(); } catch (Exception exception1) { //ProjectData.SetProjectError(exception1); this.DisplayError(Resource.LoadSupportedTypesErrMsg); //ProjectData.ClearProjectError(); } } private void LoadSupportedTypes() { this._supportedTypes = new List<System.Type>(); this._supportedTypes.Add(typeof(int)); this._supportedTypes.Add(typeof(string)); this._supportedTypes.Add(typeof(bool)); this._supportedTypes.Add(typeof(object)); } /// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary> /// <param term='application'>Root object of the host application.</param> /// <param term='connectMode'>Describes how the Add-in is being loaded.</param> /// <param term='addInInst'>Object representing this Add-in.</param> /// <seealso class='IDTExtensibility2' /> public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom) { _applicationObject = (DTE2)application; _addInInstance = (AddIn)addInInst; if(connectMode == ext_ConnectMode.ext_cm_UISetup) { object []contextGUIDS = new object[] { }; Commands2 commands = (Commands2)_applicationObject.Commands; string toolsMenuName; try { //If you would like to move the command to a different menu, change the word "Tools" to the // English version of the menu. This code will take the culture, append on the name of the menu // then add the command to that menu. You can find a list of all the top-level menus in the file // CommandBar.resx. ResourceManager resourceManager = new ResourceManager("InteropFormAddIn.CommandBar", Assembly.GetExecutingAssembly()); CultureInfo cultureInfo = new System.Globalization.CultureInfo(_applicationObject.LocaleID); string resourceName = String.Concat(cultureInfo.TwoLetterISOLanguageName, "Tools"); toolsMenuName = resourceManager.GetString(resourceName); } catch { //We tried to find a localized version of the word Tools, but one was not found. // Default to the en-US word, which may work for the current culture. toolsMenuName = "Tools"; } //Place the command on the tools menu. //Find the MenuBar command bar, which is the top-level command bar holding all the main menu items: Microsoft.VisualStudio.CommandBars.CommandBar menuBarCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["MenuBar"]; //Find the Tools command bar on the MenuBar command bar: CommandBarControl toolsControl = menuBarCommandBar.Controls[toolsMenuName]; CommandBarPopup toolsPopup = (CommandBarPopup)toolsControl; //This try/catch block can be duplicated if you wish to add multiple commands to be handled by your Add-in, // just make sure you also update the QueryStatus/Exec method to include the new command names. try { //Add a command to the Commands collection: Command command = commands.AddNamedCommand2(_addInInstance, "InteropFormAddIn", Resource.COMMAND_DISPLAY_NAME, Resource.COMMAND_DISPLAY_NAME, true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton); //Add a control for the command to the tools menu: if((command != null) && (toolsPopup != null)) { command.AddControl(toolsPopup.CommandBar, 1); } } catch(System.ArgumentException) { //If we are here, then the exception is probably because a command with that name // already exists. If so there is no need to recreate the command and we can // safely ignore the exception. } } } /// <summary>Implements the OnDisconnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being unloaded.</summary> /// <param term='disconnectMode'>Describes how the Add-in is being unloaded.</param> /// <param term='custom'>Array of parameters that are host application specific.</param> /// <seealso class='IDTExtensibility2' /> public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom) { } /// <summary>Implements the OnAddInsUpdate method of the IDTExtensibility2 interface. Receives notification when the collection of Add-ins has changed.</summary> /// <param term='custom'>Array of parameters that are host application specific.</param> /// <seealso class='IDTExtensibility2' /> public void OnAddInsUpdate(ref Array custom) { } /// <summary>Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification that the host application has completed loading.</summary> /// <param term='custom'>Array of parameters that are host application specific.</param> /// <seealso class='IDTExtensibility2' /> public void OnStartupComplete(ref Array custom) { } /// <summary>Implements the OnBeginShutdown method of the IDTExtensibility2 interface. Receives notification that the host application is being unloaded.</summary> /// <param term='custom'>Array of parameters that are host application specific.</param> /// <seealso class='IDTExtensibility2' /> public void OnBeginShutdown(ref Array custom) { } /// <summary>Implements the QueryStatus method of the IDTCommandTarget interface. This is called when the command's availability is updated</summary> /// <param term='commandName'>The name of the command to determine state for.</param> /// <param term='neededText'>Text that is needed for the command.</param> /// <param term='status'>The state of the command in the user interface.</param> /// <param term='commandText'>Text requested by the neededText parameter.</param> /// <seealso class='Exec' /> public void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus status, ref object commandText) { if(neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone) { if(commandName == "InteropFormAddIn.Connect.InteropFormAddIn") { status = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported|vsCommandStatus.vsCommandStatusEnabled; return; } } } /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary> /// <param term='commandName'>The name of the command to execute.</param> /// <param term='executeOption'>Describes how the command should be run.</param> /// <param term='varIn'>Parameters passed from the caller to the command handler.</param> /// <param term='varOut'>Parameters passed from the command handler to the caller.</param> /// <param term='handled'>Informs the caller if the command was handled or not.</param> /// <seealso class='Exec' /> public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled) { handled = false; if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault) { if(commandName == "InteropFormAddIn.Connect.InteropFormAddIn") { handled = true; this.CreateInteropFormProxiesForSolution(); } } } private void CreateInteropFormProxiesForSolution() { this._applicationObject.StatusBar.Text = Resource.ADDIN_STATUS_GENERATING; foreach (Project project1 in this._applicationObject.Solution.Projects) { if ((project1.ProjectItems != null) && (project1.ProjectItems.Count > 0)) { this.CreateInteropFormProxiesForProject(project1, project1.ProjectItems); } } this._applicationObject.StatusBar.Text = Resource.ADDIN_STATUS_GENERATED_OK; } private void CreateInteropFormProxiesForProject(Project currentAssembly, ProjectItems projItemCollection) { IsVB = (String.Compare(currentAssembly.CodeModel.Language, Resource.LanguageVB, false) == 0); foreach (ProjectItem item1 in projItemCollection) { try { if ((String.Compare(item1.Kind, Resource.DOCUMENT_TYPE, false) == 0) && (item1.FileCodeModel != null)) { List<CodeClass> list1 = this.GetInteropFormClasses(currentAssembly, item1); this.CreateInteropFormProxiesForDocument(list1, currentAssembly, item1); continue; } if ((item1.ProjectItems != null) && (item1.ProjectItems.Count > 0)) { this.CreateInteropFormProxiesForProject(currentAssembly, item1.ProjectItems); } continue; } catch (Exception exception2) { //ProjectData.SetProjectError(exception2); Exception exception1 = exception2; string text1 = Resource.ADDIN_STATUS_GENERATED_ERROR1; if ((currentAssembly != null) && (currentAssembly.Name != null)) { text1 += String.Format(Resource.ADDIN_STATUS_GENERATED_ERROR2, currentAssembly.Name); } this.DisplayError(String.Format(Resource.ADDIN_STATUS_GENERATED_ERROR_FULL, currentAssembly.Name)); //ProjectData.ClearProjectError(); continue; } } } private void DisplayError(string errorMessage) { MessageBox.Show(errorMessage, Resource.DISPLAY_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } private CodeSnippetStatement GetStatementInitializeForm(string typeName) { CodeSnippetStatement statement1 = new CodeSnippetStatement(String.Format(CultureInfo.InvariantCulture, "\t\t\tFormInstance = {0} {1}(){2}", statementNew, typeName, statementTerminator)); return statement1; } private CodeSnippetStatement GetStatementCastFormInstance(CodeClass interopFormClass) { string statementFormat = (IsVB) ? "\t\t\tDim castFormInstance As {0} = FormInstance" : "\t\t\t{0} castFormInstance = ({0})FormInstance;"; CodeSnippetStatement statement = new CodeSnippetStatement( String.Format(CultureInfo.InvariantCulture, statementFormat, interopFormClass.FullName)); return statement; } private CodeSnippetStatement GetStatementRegisterForm() { CodeSnippetStatement statement = new CodeSnippetStatement( String.Format(CultureInfo.InvariantCulture, "\t\t\tRegisterFormInstance(){0}", statementTerminator)); return statement; } private CodeSnippetStatement GetStatementMethod(CodeFunction method, CodeMemberMethod method1, out bool shouldReturn) { shouldReturn = false; string text1; if (method.FunctionKind == vsCMFunction.vsCMFunctionFunction && method.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid) { if (!this.IsSupported(method.Type)) { this.DisplayWarning(String.Format(Resource.MethodErrMsg1, method.Type.AsFullName, method.Name)); shouldReturn = true; return null; } method1.ReturnType = new CodeTypeReference(method.Type.AsFullName); text1 = String.Format("\t\t\t{0} ", statementReturn); } else { text1 = "\t\t\t"; } text1 += "castFormInstance." + method.Name + "("; bool flag1 = false; foreach (CodeParameter parameter1 in method.Parameters) { if (!this.IsSupported(parameter1.Type)) { this.DisplayWarning(String.Format(Resource.MethodErrMsg2, parameter1.Type.AsFullName, method.Name)); shouldReturn = true; return null; } CodeParameterDeclarationExpression expression2 = new CodeParameterDeclarationExpression(parameter1.Type.AsFullName, parameter1.Name); method1.Parameters.Add(expression2); if (flag1) { text1 += ", "; } text1 += parameter1.Name; flag1 = true; } text1 = text1 + ")" + statementTerminator; CodeSnippetStatement methodStatement = new CodeSnippetStatement(text1); return methodStatement; } private CodeDomProvider GetProvider() { if (IsVB) return new Microsoft.VisualBasic.VBCodeProvider(); return new CSharpCodeProvider(); } private void CreateInteropFormProxiesForDocument(List<CodeClass> interopFormClasses, Project currentAssembly, ProjectItem interopFormDoc) { ProjectItem item2 = null; if (interopFormClasses.Count <= 0) return; FileInfo info1 = new FileInfo(interopFormDoc.get_FileNames(0)); DirectoryInfo info3 = new DirectoryInfo(info1.DirectoryName + @"\" + Resource.INTEROP_FORM_PROXY_FOLDER_NAME); foreach (ProjectItem item3 in currentAssembly.ProjectItems) { if ((String.Compare(item3.Kind, Resource.FOLDER_TYPE, false) == 0) && (String.Compare(item3.Name, Resource.INTEROP_FORM_PROXY_FOLDER_NAME, false) == 0)) { item2 = item3; break; } } if (item2 == null) { if (!info3.Exists) { item2 = currentAssembly.ProjectItems.AddFolder(info3.Name, "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}"); } else { info3.Delete(true); item2 = currentAssembly.ProjectItems.AddFolder(info3.Name, "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}"); } } string text1 = info3.FullName + @"\" + info1.Name.Replace(info1.Extension, ".wrapper" + info1.Extension); FileInfo info2 = new FileInfo(text1); foreach (ProjectItem item4 in item2.ProjectItems) { if (String.Compare(item4.Kind, Resource.DOCUMENT_TYPE, false) != 0 || String.Compare(item4.Name, info2.Name, false) != 0) continue; ; ProjectItem item1 = item4; if (currentAssembly.DTE.SourceControl.IsItemUnderSCC(text1) && !item4.Collection.ContainingProject.DTE.SourceControl.IsItemCheckedOut(text1)) { item4.Collection.ContainingProject.DTE.SourceControl.CheckOutItem(text1); } break; } if (info2.Exists) { info2.Delete(); } CodeCompileUnit unit1 = new CodeCompileUnit(); CodeNamespaceImport import1 = new CodeNamespaceImport(this._attrTypeForm.Namespace); System.CodeDom.CodeNamespace namespace1 = new System.CodeDom.CodeNamespace(); namespace1.Name = "Interop"; unit1.Namespaces.Add(namespace1); namespace1.Imports.Add(import1); foreach (CodeClass class1 in interopFormClasses) { string text2 = class1.FullName; CodeTypeDeclaration declaration1 = new CodeTypeDeclaration(class1.Name); namespace1.Types.Add(declaration1); declaration1.IsClass = true; declaration1.IsPartial = true; CodePrimitiveExpression expression2 = new CodePrimitiveExpression(true); CodeSnippetExpression expression1 = new CodeSnippetExpression("System.Runtime.InteropServices.ClassInterfaceType.AutoDual"); declaration1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.ClassInterface", new System.CodeDom.CodeAttributeArgument[] { new System.CodeDom.CodeAttributeArgument(expression1) })); declaration1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.ComVisible", new System.CodeDom.CodeAttributeArgument[] { new System.CodeDom.CodeAttributeArgument(expression2) })); declaration1.BaseTypes.Add(new CodeTypeReference(typeof(InteropFormProxyBase).Name)); CodeTypeDeclaration declaration2 = new CodeTypeDeclaration("I" + declaration1.Name + "EventSink"); declaration2.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.InterfaceTypeAttribute", new System.CodeDom.CodeAttributeArgument[] { new System.CodeDom.CodeAttributeArgument(new CodeSnippetExpression("System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIDispatch")) })); declaration2.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.ComVisible", new System.CodeDom.CodeAttributeArgument[] { new System.CodeDom.CodeAttributeArgument(expression2) })); declaration2.IsInterface = true; CodeConstructor constructor1 = new CodeConstructor(); CodeSnippetStatement statement1 = GetStatementInitializeForm(text2); CodeSnippetStatement statement2 = GetStatementRegisterForm(); constructor1.Statements.Add(statement1); constructor1.Statements.Add(statement2); constructor1.Attributes = MemberAttributes.Public; declaration1.Members.Add(constructor1); if (class1.Members.Count > 0) { foreach (CodeElement element1 in class1.Members) { switch (element1.Kind) { case vsCMElement.vsCMElementFunction: CodeFunction2 function1 = (CodeFunction2)element1; if (function1.Access == vsCMAccess.vsCMAccessPublic) { foreach (CodeElement element2 in function1.Attributes) { if (this.AttributesMatch(element2, this._attrTypeInitializer)) { this.AddInitializeMethodForConstructor(declaration1, class1, function1); break; } if (this.AttributesMatch(element2, this._attrTypeMethod)) { this.AddMethod(declaration1, class1, function1); break; } } } break; case vsCMElement.vsCMElementProperty: CodeProperty property1 = (CodeProperty)element1; if (property1.Access == vsCMAccess.vsCMAccessPublic) { foreach (CodeElement element3 in property1.Attributes) { if (this.AttributesMatch(element3, this._attrTypeProperty)) { this.AddProperty(declaration1, class1, property1); break; } } } break; case vsCMElement.vsCMElementEvent: CodeEvent event1 = (CodeEvent)element1; if (event1.Access == vsCMAccess.vsCMAccessPublic) { foreach (CodeElement element3 in event1.Attributes) { if (this.AttributesMatch(element3, this._attrTypeEvent)) { this.AddEvent(currentAssembly, declaration1, class1, event1, declaration2); break; } } } break; } } } if (declaration2.Members.Count > 0) { namespace1.Types.Add(declaration2); declaration1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.ComSourceInterfaces", new System.CodeDom.CodeAttributeArgument[] { new System.CodeDom.CodeAttributeArgument(new CodeTypeOfExpression(declaration2.Name)) })); } } StreamWriter writer1 = new StreamWriter(info2.Create()); writer1.AutoFlush = true; CodeDomProvider provider = GetProvider(); CodeGeneratorOptions options1 = new CodeGeneratorOptions(); provider.GenerateCodeFromCompileUnit(unit1, writer1, options1); writer1.Close(); writer1.Dispose(); item2.ProjectItems.AddFromFile(info2.FullName); } private void AddEvent(Project currentAssembly, CodeTypeDeclaration proxyClass, CodeClass interopFormClass, CodeEvent evt, CodeTypeDeclaration proxyClassEventSinkInterface) { CodeDelegate2 delegate1 = null; try { delegate1 = (CodeDelegate2)currentAssembly.CodeModel.CodeTypeFromFullName(evt.Type.AsFullName); } catch (Exception exception2) { //ProjectData.SetProjectError(exception2); Exception exception1 = exception2; foreach (CodeElement element1 in evt.ProjectItem.FileCodeModel.CodeElements) { if (element1.IsCodeType) { CodeType type1 = (CodeType)element1; foreach (CodeElement element2 in type1.Children) { if ((element2.Kind == vsCMElement.vsCMElementDelegate) & (String.Compare(element2.FullName, evt.Type.AsFullName, false) == 0)) { delegate1 = (CodeDelegate2)element2; } } continue; } } //ProjectData.ClearProjectError(); } if (delegate1 == null) { this.DisplayWarning(string.Format(Resource.EventErrMsg, evt.Name, evt.Type.AsFullName)); } else { CodeMemberMethod method1 = null; foreach (CodeTypeMember member1 in proxyClass.Members) { if (String.Compare(member1.Name, "HookCustomEvents", false) == 0) { method1 = (CodeMemberMethod)member1; } } if (method1 == null) { method1 = new CodeMemberMethod(); method1.Name = "HookCustomEvents"; method1.Attributes = MemberAttributes.Family | MemberAttributes.Override; method1.Statements.Add(this.GetStatementCastFormInstance(interopFormClass)); proxyClass.Members.Add(method1); } CodeMemberEvent event1 = new CodeMemberEvent(); event1.Attributes = MemberAttributes.Public; event1.Type = new CodeTypeReference(evt.Type.AsFullName); event1.Name = evt.Name; CodeMemberMethod method3 = new CodeMemberMethod(); method3.Name = evt.Name; CodeTypeDelegate delegate2 = new CodeTypeDelegate(evt.Name + "Handler"); bool flag1 = false; CodeMemberMethod method2 = new CodeMemberMethod(); method2.Name = "castFormInstance_" + evt.Name; CodeDelegateInvokeExpression expression1 = new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), event1.Name)); foreach (CodeParameter parameter1 in delegate1.Parameters) { CodeParameterDeclarationExpression expression2; CodeArgumentReferenceExpression expression3; CodeParameterDeclarationExpression expression4; if ((parameter1.Type.CodeType != null) && this.IsEventArgs(parameter1.Type.CodeType)) { if (!flag1) { proxyClass.Members.Add(delegate2); event1.Type = new CodeTypeReference(delegate2.Name); } expression4 = new CodeParameterDeclarationExpression("System.EventArgs", parameter1.Name); expression2 = new CodeParameterDeclarationExpression(parameter1.Type.AsFullName, parameter1.Name); expression3 = new CodeArgumentReferenceExpression(expression4.Name); event1.Comments.Add(new CodeCommentStatement(this.EVENT_ARGS_COMMENT)); method3.Comments.Add(new CodeCommentStatement(this.EVENT_ARGS_COMMENT)); } else { if (!this.IsSupported(parameter1.Type)) { this.DisplayWarning(String.Format(Resource.EventErrMsg2, parameter1.Type.AsFullName, evt.Name)); return; } expression4 = new CodeParameterDeclarationExpression(parameter1.Type.AsFullName, parameter1.Name); expression2 = new CodeParameterDeclarationExpression(parameter1.Type.AsFullName, parameter1.Name); expression3 = new CodeArgumentReferenceExpression(expression4.Name); } method3.Parameters.Add(expression4); delegate2.Parameters.Add(expression4); method2.Parameters.Add(expression2); expression1.Parameters.Add(expression3); } method2.Statements.Add(expression1); method1.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new CodeVariableReferenceExpression("castFormInstance"), event1.Name), new CodeDelegateCreateExpression(event1.Type, new CodeThisReferenceExpression(), method2.Name))); proxyClassEventSinkInterface.Members.Add(method3); proxyClass.Members.Add(method2); proxyClass.Members.Add(event1); } } private bool IsEventArgs(CodeType parmType) { if (String.Compare(parmType.FullName, "system.eventargs", true) == 0) return true; foreach (CodeElement element1 in parmType.Bases) { if (String.Compare(element1.FullName, "system.eventargs", true) == 0) return true; if (element1.IsCodeType && this.IsEventArgs((CodeType)element1)) return true; } return false; } private bool IsSupported(CodeTypeRef typeToCheck) { foreach (System.Type type1 in this._supportedTypes) { if (String.Compare(typeToCheck.AsFullName, type1.FullName, false) == 0) return true; } return false; } private void DisplayWarning(string errorMessage) { MessageBox.Show(errorMessage, Resource.DISPLAY_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } private void AddProperty(CodeTypeDeclaration proxyClass, CodeClass interopFormClass, CodeProperty prop) { CodeMemberProperty property1 = new CodeMemberProperty(); property1.Name = prop.Name; property1.Attributes = MemberAttributes.Public; property1.Type = new CodeTypeReference(prop.Type.AsFullName); if (!this.IsSupported(prop.Type)) { this.DisplayWarning(String.Format(Resource.PropertyErrMsg, prop.Type.AsFullName, property1.Name)); return; } if (prop.Getter != null) { property1.HasGet = true; property1.GetStatements.Add(this.GetStatementCastFormInstance(interopFormClass)); property1.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("castFormInstance"), prop.Name))); } if (prop.Setter != null) { property1.HasSet = true; property1.SetStatements.Add(this.GetStatementCastFormInstance(interopFormClass)); property1.SetStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("castFormInstance"), prop.Name), new CodePropertySetValueReferenceExpression())); } proxyClass.Members.Add(property1); } private void AddMethod(CodeTypeDeclaration proxyClass, CodeClass interopFormClass, CodeFunction method) { CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = method.Name; method1.Attributes = MemberAttributes.Public; CodePrimitiveExpression expression1 = new CodePrimitiveExpression(true); method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Diagnostics.DebuggerStepThrough")); method1.Statements.Add(this.GetStatementCastFormInstance(interopFormClass)); bool lShouldReturn; CodeSnippetStatement methodStatement = GetStatementMethod(method, method1, out lShouldReturn); if (lShouldReturn) return; method1.Statements.Add(methodStatement); proxyClass.Members.Add(method1); } private void AddInitializeMethodForConstructor(CodeTypeDeclaration proxyClass, CodeClass interopFormClass, CodeFunction method) { CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "Initialize"; method1.Attributes = MemberAttributes.Public; method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Diagnostics.DebuggerStepThrough")); string text1 = String.Format(CultureInfo.InvariantCulture, "\t\t\tFormInstance = {0} {1}(", statementNew, interopFormClass.FullName); bool flag1 = false; foreach (CodeParameter parameter1 in method.Parameters) { if (!this.IsSupported(parameter1.Type)) { this.DisplayWarning(String.Format(Resource.InitMethodErrMsg, parameter1.Type.AsFullName, parameter1.Name, parameter1.Type.AsFullName)); return; } CodeParameterDeclarationExpression expression1 = new CodeParameterDeclarationExpression(parameter1.Type.AsFullName, parameter1.Name); method1.Parameters.Add(expression1); if (flag1) { text1 += ", "; } text1 += parameter1.Name; flag1 = true; } text1 = text1 + ")" + statementTerminator; method1.Statements.Add(new CodeSnippetStatement( String.Format("\t\t\tUnregisterFormInstance(){0}", statementTerminator))); method1.Statements.Add(new CodeSnippetStatement(text1)); method1.Statements.Add(new CodeSnippetStatement( String.Format("\t\t\tRegisterFormInstance(){0}", statementTerminator))); proxyClass.Members.Add(method1); } private bool AttributesMatch(CodeElement ce, System.Type attrType) { bool flag2 = false; string text1 = String.Empty; if (ce == null) return flag2; if (!String.IsNullOrEmpty(ce.Name)) { text1 = ce.Name; flag2 = (String.Compare(text1, attrType.Name, true) == 0) || (String.Compare(text1, attrType.Name.Replace("Attribute", ""), true) == 0); } if (!flag2 && !String.IsNullOrEmpty(ce.Name)) { text1 = ce.FullName; flag2 = (String.Compare(text1, attrType.FullName, true) == 0) || (String.Compare(text1, attrType.FullName.Replace("Attribute", ""), true) == 0); } return flag2; } private List<CodeClass> GetInteropFormClasses(Project assemblyProj, ProjectItem projItem) { List<CodeClass> list2 = new List<CodeClass>(); if (projItem.FileCodeModel != null) { this.FindInteropFormClasses(assemblyProj, projItem.FileCodeModel.CodeElements, list2); } return list2; } private void FindInteropFormClasses(Project currentAssembly, CodeElements codeElements, List<CodeClass> interopFormClasses) { if (codeElements == null) return; foreach (CodeElement element1 in codeElements) { if ((element1.Kind == vsCMElement.vsCMElementAttribute) && this.AttributesMatch(element1, this._attrTypeForm)) { CodeClass class1 = (CodeClass)codeElements.Parent; interopFormClasses.Add(class1); } if (element1.Children.Count > 0) { this.FindInteropFormClasses(currentAssembly, element1.Children, interopFormClasses); } } } private DTE2 _applicationObject; private AddIn _addInInstance; private System.Type _attrTypeEvent; private System.Type _attrTypeForm; private System.Type _attrTypeInitializer; private System.Type _attrTypeMethod; private System.Type _attrTypeProperty; private List<System.Type> _supportedTypes; private string EVENT_ARGS_COMMENT; public bool IsVB { get { return m_isVB; } set { if (value) { statementTerminator = String.Empty; statementNew = "New"; statementReturn = "Return"; } else { statementTerminator = ";"; statementNew = "new"; statementReturn = "return"; } m_isVB = value; } } private bool m_isVB; private string statementTerminator; private string statementNew; private string statementReturn; } } By viewing downloads associated with this article you agree to the Terms of Service and the article's licence. If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it. License This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Share About the Author Leon Langleyben Web Developer Israel Israel Leon works as Chief Architect at SRL Group. He leads architectural design and development of various enterprise level projects. You can meet him on user groups, conferences and forums dedicated to Architecture, ASP.NET, Team System etc. or join him for the next white water rafting adventure You may also be interested in... | Advertise | Privacy | Terms of Use | Mobile Web02 | 2.8.150819.1 | Last Updated 2 Oct 2006 Article Copyright 2006 by Leon Langleyben Everything else Copyright © CodeProject, 1999-2015 Layout: fixed | fluid
__label__pos
0.520154
// Free Ski Tree // GM2D.com haxe code for simple game. // I am placing this code, and associated "tiles.png" in the public domain. // Since we are dealing with flash version 9, the general graphics // classes are in the "flash.display" package. import flash.display.Sprite; import flash.display.BitmapData; import flash.display.Bitmap; import flash.geom.Rectangle; import flash.geom.Point; import flash.events.Event; import flash.events.KeyboardEvent; import flash.ui.Keyboard; import flash.text.TextField; import flash.text.TextFormat; import flash.filters.GlowFilter; /* The Blob class (BLitter OBject) is a rectangle of pixels that can be quickyly and easily copied to the screen. Perhaps a better name would be Sprite, but that would be too confusing. The main purpose of this class is to do a "copyPixels", and it just gathers the required data together to make this very easy. */ class Blob { var mArena:BitmapData; var mBits:BitmapData; var mRect:Rectangle; var mPoint:Point; // The "hotspot" is the logical origin of the object, with respect // to the top left of its bitmap rectangle. This allows you to deal // with the position of the object, without having to worry about drawing // offsets etc. var mHotX:Float; var mHotY:Float; // Passing the arena into the constructor is not really required, // but doing this reduces the number of params we have to pass into // the Draw function; public function new(inArena:BitmapData,inBits:BitmapData,inX:Int, inY:Int, inW:Int, inH:Int, ?inHotX:Null, ?inHotY:Null) { mArena = inArena; mBits = inBits; mRect = new Rectangle(inX,inY,inW,inH); mPoint = new Point(0,0); // If null is provided, assume the centre. mHotX = inHotX==null ? inW/2 : inHotX; mHotY = inHotY==null ? inH/2 : inHotY; } public function draw(inX:Float,inY:Float) { mPoint.x = inX-mHotX; mPoint.y = inY-mHotY; mArena.copyPixels(mBits,mRect,mPoint,null,null,true); } } // All games would probably have some kind of state like this... enum SkiState { FirstRun; Playing; Dead; } // Array of the x-coordinate of the trees. typedef TreeRow = Array; // This is our main class, and in this case, it contains the whole game. // It extends the standard flash "Sprite" class, which allows child objects // and events. No need for a MovieClip, because we are not using the flash // timelining code. class Ski extends Sprite { // Using "copyPixels" we draw into this bitmap... var mArena:BitmapData; // What to do on an update... var mState : SkiState; // Our basic drawing objects var mTree:Blob; var mPlayerDown:Blob; var mPlayerLeft:Blob; var mPlayerRight:Blob; // Contains the state (whether currently pressed/down) of every key var mKeyDown:Array; // Time of last step - for calculating time deltas... var mLastStep:Float; // We increate game speed by increasing steps-per-second. // Note that this is independent of the flash frame rate, since we can // do multiple steps per flash redraw. var mStepsPerSecond:Float; // An array of trees to ski past. Other arrangements are possible, // for example only traking the visible trees and creating new // ones randomly as we go var mTrees:Array; // All position are in "field" coordinates, which are logical pixels. // We use the modulo operator (%) to wrap the trees around static var mFieldHeight = 10000; var mPlayerX:Float; var mPlayerY:Float; // Curreny play var mScore:Float; // Current session var mTopScore:Float; // GUI items var mScoreText:TextField; var mTopScoreText:TextField; // All the graphics are provided in the input image (BitmapData). function new(inBitmap:BitmapData) { // Since this class inherits from Sprite, we must call this. super(); // Haxe does not automatically add the main class to the stage (it adds // a "boot" object to the stage, which becomes "flash.Lib.current"). // In order to see anything, this class must be on the stage, so we // add ourselves as child to the haxe boot class. Subsequent objects // (eg, the TextFields) get added to ourselves. flash.Lib.current.addChild(this); mKeyDown = []; // These two lines of code are the key to the "copyPixels" method of // flash game creation. // First, an offscreen buffer (BitmapData) is created to hold all the graphics. // Then an instance of this is placed on the stage. We can then simply change // the offscreen buffer and have the changes visible. This does not necessarily // have to be the same size as the game, but in this case it is. mArena = new BitmapData(640,480); addChild(new Bitmap(mArena) ); // Create or Blobs (aka sprites) as subrects of the input images. // The rectanges were calculated when the image was created. If there were // many more Blobs, some external data file would be a better way of // getting the rectangles. mTree = new Blob(mArena,inBitmap,4,0,54,64,null,62); mPlayerLeft = new Blob(mArena,inBitmap,110,16,26,40); mPlayerDown = new Blob(mArena,inBitmap,70,12,26,46); mPlayerRight = new Blob(mArena,inBitmap,148,16,26,40); // I have chosen to add the event listeners to stage rather then // other display objects. Since there are no objects that will take // keyboard focus, all the key events will go to the stage. // It is best to have a single OnEnter and do all the updates from there, // so it may as well be on the stage. stage.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyDown ); stage.addEventListener(KeyboardEvent.KEY_UP, OnKeyUp ); stage.addEventListener(Event.ENTER_FRAME, OnEnter); // Allocate row mTrees = []; mTrees[mFieldHeight-1] = null; // Fill up tree array. // This will be constant throughout the session, so the player can learn // the best way down. A random number "seed" could be used if you wanted // the game to be the same on different machines. for(i in 0...500) { // Randomise x position. Make sure they overlap the edges so that // there is no advantage from shooting down the edge. var x = (Math.random()*700)-30; // Leave a gap for the top 250 rows so the player can start in piece. var y = Std.int(Math.random()*(mFieldHeight-250)) + 250; if (mTrees[y]==null) mTrees[y] = []; mTrees[y].push(x); } // The "GUI" consists of two TextFields overlapping the arena. // These do not use "copyPixels", but take advantage of some of the // other benefits provided by flash display list model. // In a "real" game, you should use a custom embedded font, rather than // some crappy default. mScoreText = new TextField(); mScoreText.x = 10; mScoreText.y = 10; var format:TextFormat = new TextFormat(); format.font = "Arial"; format.bold = true; format.color = 0xffffff; format.size = 20; mScoreText.defaultTextFormat = format; mScoreText.text = "Score:0"; mScoreText.width = 640; mScoreText.filters = [ new GlowFilter(0x0000ff, 1.0, 3, 3, 3, 3, false, false) ]; addChild(mScoreText); mTopScoreText = new TextField(); mTopScoreText.x = 100; mTopScoreText.y = 10; format.color = 0xffffff; mTopScoreText.defaultTextFormat = format; mTopScoreText.filters = [ new GlowFilter(0xff0000, 1.0, 3, 3, 3, 3, false, false) ]; addChild(mTopScoreText); // Just something small to aspire too... mTopScore = 0; CheckTopScore(1000); mLastStep = haxe.Timer.stamp(); Reset(); // Slightly different message at the beginning mState = SkiState.FirstRun; } // Update the top score at the end of the game, if required. function CheckTopScore(inScore:Float) { if (inScore>mTopScore) { mTopScore = inScore; var s = Std.int(mTopScore * 0.1); mTopScoreText.text = "TopScore:" + s + "0"; var w = mTopScoreText.textWidth; mTopScoreText.width = w + 20; mTopScoreText.x = 620 - w; } } // Get ready to start the game again function Reset() { mPlayerX = 320; mPlayerY = 20; mScore = 0; mStepsPerSecond = 100; } // Update one step. // Is this case, we will descend one line. // When the game speeds up, this will get called more often. function Update() { // Actually need to move down ? if (mState==SkiState.Playing) { // This small bit of code defined the whole "mechanic" of the game. // Other things could be done here, eg acceleration or a "one button" // mode where you either go left-or-right, but not down. // Also, mouse support could be added here. var dx = mKeyDown[ Keyboard.LEFT ] ? -1 : mKeyDown[ Keyboard.RIGHT ] ? 1 : 0; // This effectively defines the angle you go at when you turn mPlayerX += dx * 0.3; // Limit to screen if (mPlayerX<12) mPlayerX = 12; if (mPlayerX>628) mPlayerX = 628; // Going down... mPlayerY += 1; // Loop around, to keep numbers from overflowing. if (mPlayerY > mFieldHeight) mPlayerY -= mFieldHeight; // 1 Point per row mScore += 1.0; // Get faster as we get more points mStepsPerSecond = 100 + mScore * 0.01; // Check death... var row = mTrees[Std.int(mPlayerY)]; if (row!=null) for(x in row) if ( Math.abs(x-mPlayerX) < 15 ) { // We are dead. Stop scoring. CheckTopScore(mScore); mState = SkiState.Dead; } } } // Update the graphics based on class variables. // Note that this will be called less frequently than the "Update" call. // inExtra is not used in this example, because scrolling seems smooth enough. function Render(inExtra:Float) { // Offset all the object to keep th apparent position on the player // the same. This creates a "virtual viewport" for rendering. var scroll_y = mPlayerY - 60; // The "copyPixels" method works by clearing the buffer and then drawing // the bitmaps into the offscreen buffer. mArena.fillRect(new Rectangle(0,0,640,480),0xe0e0ff); var blob = mKeyDown[ Keyboard.LEFT ] ? mPlayerLeft : mKeyDown[ Keyboard.RIGHT ] ? mPlayerRight : mPlayerDown; blob.draw(mPlayerX, mPlayerY - scroll_y); // These bounds ensure the to and the bottom of all potentially visible // sprites are rendered. for(y in -10...(480+80)) { // Given the pixel position, back-calculate the field row position // based on the scroll position. var field_y = Std.int(scroll_y + y) % mFieldHeight; var row = mTrees[field_y]; if (row!=null) { for(x in row) mTree.draw(x,y); } } // Update the gui message. if (mState==SkiState.FirstRun) { mScoreText.text = "Press any key to start"; } else if (mState==SkiState.Playing) { // Round scores to nearest 10 for display purposes var s = Std.int(mScore * 0.1); mScoreText.text = "Score:" + s + "0"; } else { var s = Std.int(mScore * 0.1); if (mScore>=mTopScore) mScoreText.text = "Top Score! " + s + "0" + " Press [space] to go again"; else mScoreText.text = "You scored " + s + "0" + " Press [space] to try again"; } } // Respond to a key-down event. function OnKeyDown(event:KeyboardEvent) { // When a key is held down, multiple KeyDown events are generated. // This check means we only pick up the first one. if (!mKeyDown[event.keyCode]) { // Most of the game runs off the "mKeyDown" state, but the in beginning we // use the transition event... if (mState == SkiState.FirstRun) mState = SkiState.Playing; else if (mState == SkiState.Dead && event.keyCode==Keyboard.SPACE) { Reset(); mState = SkiState.Playing; } // Store for use in game mKeyDown[event.keyCode] = true; } } // Key-up event function OnKeyUp(event:KeyboardEvent) { // Store for use in game mKeyDown[event.keyCode] = false; } // This function gets called once per flash frame. // This will be approximately the rate specified in the swf, but usually a // bit slower. For accurate timing, we will not rely on flash to call us // consistently, but we will do our own timing. function OnEnter(e:flash.events.Event) { var now = haxe.Timer.stamp(); // Do a number of descrete steps based on the mStepsPerSecond. var steps = Math.floor( (now-mLastStep) * mStepsPerSecond ); // Since the mStepsPerSecond may change in the Update call, make sure // we do all our calculations before we call Update. mLastStep += steps / mStepsPerSecond; var fractional_step = (now-mLastStep) * mStepsPerSecond; for(i in 0...steps) Update(); // This helps flash efficiently update the bitmap, batching the changes mArena.lock(); // fractional_step is something we don't use, but it could be used to do some // dead-reckoning in the render code to smooth out the display. Render(fractional_step); // This completes the batching mArena.unlock(); } // Haxe will always look for a static function called "main". static public function main() { // There are a number of ways to get bitmap data into flash. // In this case, we're loading it from a file that is placed next to the // game swf. Other ways will be described later. // Since the downloding of the bitmap from a remote location may take some // time, flash uses an asynchronous api to delivier the data. // This means that the request is sent and the data only becomes valid when // the callback is called. A loading screen would be appropriate here, but // that's beond the scope of this example, as is appropriate error checking. // Create the request object... var loader = new flash.display.Loader(); // When the image is ready, instanciate the game class... loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, function(_) { new Ski(untyped loader.content.bitmapData); }); // Fire off the request and wait... loader.load(new flash.net.URLRequest("tiles.png")); } }
__label__pos
0.966333
pagutils.dll Process name: PagUtils Application using this process: PagUtils Recommended: Check your system for invalid registry entries. pagutils.dll Process name: PagUtils Application using this process: PagUtils Recommended: Check your system for invalid registry entries. pagutils.dll Process name: PagUtils Application using this process: PagUtils Recommended: Check your system for invalid registry entries. What is pagutils.dll doing on my computer? pagutils.dll is a PagUtils belonging to PagUtils from Panda Software Non-system processes like pagutils.dll originate from software you installed on your system. Since most applications store data in your system's registry, it is likely that over time your registry suffers fragmentation and accumulates invalid entries which can affect your PC's performance. It is recommended that you check your registry to identify slowdown issues. pagutils.dll In order to ensure your files and data are not lost, be sure to back up your files online. Using a cloud backup service will allow you to safely secure all your digital files. This will also enable you to access any of your files, at any time, on any device. Is pagutils.dll harmful? pagutils.dll has not been assigned a security rating yet. pagutils.dll is unrated Can I stop or remove pagutils.dll? Most non-system processes that are running can be stopped because they are not involved in running your operating system. Scan your system now to identify unused processes that are using up valuable resources. pagutils.dll is used by 'PagUtils'.This is an application created by 'Panda Software'. To stop pagutils.dll permanently uninstall 'PagUtils' from your system. Uninstalling applications can leave invalid registry entries, accumulating over time. Is pagutils.dll CPU intensive? This process is not considered CPU intensive. However, running too many processes on your system may affect your PC’s performance. To reduce system overload, you can use the Microsoft System Configuration Utility to manually find and disable processes that launch upon start-up. Why is pagutils.dll giving me errors? Process related issues are usually related to problems encountered by the application that runs it. A safe way to stop these errors is to uninstall the application and run a system scan to automatically identify any PC issues. Process Library is the unique and indispensable process listing database since 2004 Now counting 140,000 processes and 55,000 DLLs. Join and subscribe now! Toolbox ProcessQuicklink
__label__pos
0.955622
Source code Revision control Copy as Markdown Other Tools /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: set ts=8 sts=2 et sw=2 tw=80: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef debugger_DebugAPI_inl_h #define debugger_DebugAPI_inl_h #include "debugger/DebugAPI.h" #include "gc/GC.h" #include "vm/GeneratorObject.h" #include "vm/PromiseObject.h" // js::PromiseObject #include "vm/Stack-inl.h" namespace js { /* static */ bool DebugAPI::stepModeEnabled(JSScript* script) { return script->hasDebugScript() && stepModeEnabledSlow(script); } /* static */ bool DebugAPI::hasBreakpointsAt(JSScript* script, jsbytecode* pc) { return script->hasDebugScript() && hasBreakpointsAtSlow(script, pc); } /* static */ bool DebugAPI::hasAnyBreakpointsOrStepMode(JSScript* script) { return script->hasDebugScript(); } /* static */ void DebugAPI::onNewGlobalObject(JSContext* cx, Handle<GlobalObject*> global) { MOZ_ASSERT(!global->realm()->firedOnNewGlobalObject); #ifdef DEBUG global->realm()->firedOnNewGlobalObject = true; #endif if (!cx->runtime()->onNewGlobalObjectWatchers().isEmpty()) { slowPathOnNewGlobalObject(cx, global); } } /* static */ void DebugAPI::notifyParticipatesInGC(GlobalObject* global, uint64_t majorGCNumber) { JS::AutoAssertNoGC nogc; Realm::DebuggerVector& dbgs = global->getDebuggers(nogc); if (!dbgs.empty()) { slowPathNotifyParticipatesInGC(majorGCNumber, dbgs, nogc); } } /* static */ bool DebugAPI::onLogAllocationSite(JSContext* cx, JSObject* obj, Handle<SavedFrame*> frame, mozilla::TimeStamp when) { // slowPathOnLogAllocationSite creates GC things so we must suppress GC here. gc::AutoSuppressGC nogc(cx); Realm::DebuggerVector& dbgs = cx->global()->getDebuggers(nogc); if (dbgs.empty()) { return true; } RootedObject hobj(cx, obj); return slowPathOnLogAllocationSite(cx, hobj, frame, when, dbgs, nogc); } /* static */ bool DebugAPI::onLeaveFrame(JSContext* cx, AbstractFramePtr frame, const jsbytecode* pc, bool ok) { MOZ_ASSERT_IF(frame.isInterpreterFrame(), frame.asInterpreterFrame() == cx->interpreterFrame()); MOZ_ASSERT_IF(frame.hasScript() && frame.script()->isDebuggee(), frame.isDebuggee()); /* Traps must be cleared from eval frames, see slowPathOnLeaveFrame. */ mozilla::DebugOnly<bool> evalTraps = frame.isEvalFrame() && frame.script()->hasDebugScript(); MOZ_ASSERT_IF(evalTraps, frame.isDebuggee()); if (frame.isDebuggee()) { ok = slowPathOnLeaveFrame(cx, frame, pc, ok); } MOZ_ASSERT(!inFrameMaps(frame)); return ok; } /* static */ bool DebugAPI::onNewGenerator(JSContext* cx, AbstractFramePtr frame, Handle<AbstractGeneratorObject*> genObj) { if (frame.isDebuggee()) { return slowPathOnNewGenerator(cx, frame, genObj); } return true; } /* static */ bool DebugAPI::checkNoExecute(JSContext* cx, HandleScript script) { if (!cx->realm()->isDebuggee() || !cx->noExecuteDebuggerTop) { return true; } return slowPathCheckNoExecute(cx, script); } /* static */ bool DebugAPI::onEnterFrame(JSContext* cx, AbstractFramePtr frame) { MOZ_ASSERT_IF(frame.hasScript() && frame.script()->isDebuggee(), frame.isDebuggee()); if (MOZ_UNLIKELY(frame.isDebuggee())) { return slowPathOnEnterFrame(cx, frame); } return true; } /* static */ bool DebugAPI::onResumeFrame(JSContext* cx, AbstractFramePtr frame) { MOZ_ASSERT_IF(frame.hasScript() && frame.script()->isDebuggee(), frame.isDebuggee()); if (MOZ_UNLIKELY(frame.isDebuggee())) { return slowPathOnResumeFrame(cx, frame); } return true; } /* static */ NativeResumeMode DebugAPI::onNativeCall(JSContext* cx, const CallArgs& args, CallReason reason) { if (MOZ_UNLIKELY(cx->realm()->isDebuggee())) { return slowPathOnNativeCall(cx, args, reason); } return NativeResumeMode::Continue; } /* static */ bool DebugAPI::onDebuggerStatement(JSContext* cx, AbstractFramePtr frame) { if (MOZ_UNLIKELY(cx->realm()->isDebuggee())) { return slowPathOnDebuggerStatement(cx, frame); } return true; } /* static */ bool DebugAPI::onExceptionUnwind(JSContext* cx, AbstractFramePtr frame) { if (MOZ_UNLIKELY(cx->realm()->isDebuggee())) { return slowPathOnExceptionUnwind(cx, frame); } return true; } /* static */ void DebugAPI::onNewWasmInstance(JSContext* cx, Handle<WasmInstanceObject*> wasmInstance) { if (cx->realm()->isDebuggee()) { slowPathOnNewWasmInstance(cx, wasmInstance); } } /* static */ void DebugAPI::onNewPromise(JSContext* cx, Handle<PromiseObject*> promise) { if (MOZ_UNLIKELY(cx->realm()->isDebuggee())) { slowPathOnNewPromise(cx, promise); } } /* static */ void DebugAPI::onPromiseSettled(JSContext* cx, Handle<PromiseObject*> promise) { if (MOZ_UNLIKELY(promise->realm()->isDebuggee())) { slowPathOnPromiseSettled(cx, promise); } } /* static */ void DebugAPI::traceGeneratorFrame(JSTracer* tracer, AbstractGeneratorObject* generator) { if (MOZ_UNLIKELY(generator->realm()->isDebuggee())) { slowPathTraceGeneratorFrame(tracer, generator); } } } // namespace js #endif /* debugger_DebugAPI_inl_h */
__label__pos
0.999896
Does Windows 7 support other languages naturally? I am currently using a Windows XP - chinese edition. I bought it overseas a few years ago. I wonder how well Windonws 7 can support chinese? At the early years of Windows XP, an english version was not compatible with chinese websites and documents. And the language pack only did the very basic things - it just did not work. I had to look for a chinese version. So, my questions will be: Can Windows 7 do the same work as XP does? Can it display chinese naturally? Or Do i have to find a chinese version? Furthermore, does the student upgrade offer do the same thing as the normal version? Thanks all. Rui   Question Info Last updated March 20, 2018 Views 780 Applies to: Answer If you don't have a Chinese version you will need Windows 7 Ultimate to switch languages. When switching to a different language with a MUI the entire interface is changed. To install a different language - Multilingual User Interface (MUI) - you need to have Windows 7 Ultimate. If you don't have Ultimate you can do an Anytime Upgrade to Ultimate. There are 35 languages to chose from, they are listed under "Language Packs" at this website: http://technet.microsoft.com/en-us/library/dd744369%28WS.10%29.aspx   Anytime Upgrade to Windows 7 Ultimate  Type Anytime Upgrade in the Search programs and files box in the Start menu and click on the Windows Anytime Upgrade icon.  From there, you can buy an Anytime Upgrade to Windows 7 Ultimate. Then your can enter your Anytime Upgrade product key and perform a simple upgrade to Windows 7 Ultimate so you can install a different language. All programs and files will stay on the computer.    Windows Anytime Upgrade is only available for online purchase in Australia, Belgium, Canada, Germany, France, Italy, Japan, the Netherlands, Spain, Sweden, Switzerland, the United Kingdom, and the United States. If you're in a different country check local stores and see if it's available. If you can't buy an Anytime Upgrade you will need to buy Windows 7 Ultimate, or buy Windows 7 in the language you need.    http://windows.microsoft.com/en-us/windows7/products/windows-anytime-upgrade     Install New Multilingual User Interface (MUI) in Windows 7 Ultimate:    1. Start -> All Programs --> Windows Update --> Optional Updates.  2. Open optional Updates and go to the section Windows 7 Language Packs.  3. Tick the Multilingual User Interface (MUI) you want and click OK  4. Proceed with Install Updates      How to change the Windows 7 Display Language:    1. Go to Start -> Control Panel -> Clock, Language, and Region / Change the display language  2. Switch the display language in the Choose a display language drop down menu.  3. Click OK  4. Log off for the changes to take effect (This will affect only the user profile under which you are currently logged on).        Have Questions About Installing Windows 7? FAQ - Common Windows 7 Installation Questions & Answers MCC 2011 TrekDozer Sharing bits of knowledge. Did this solve your problem? Sorry this didn't help. Great! Thanks for marking this as the answer. How satisfied are you with this reply? Thanks for your feedback, it helps us improve the site. How satisfied are you with this response? Thanks for your feedback.  
__label__pos
0.545524
Note: When submitting names for an Enterprise Data Quality Professional, only include constituent records that you would like updated.  If you have Non-Address related information (care of/ attention) in your addresses, this information could be removed during the update process.  You will also want to remove any records that are marked as Deceased. 1. Create a query of the constituents to include in the screening. 2. Create a constituent export in comma separated values (CSV) format based on the query created in step 1. 3. On the Output tab, select: • Constituent Information, First Name • Constituent Information, Middle Name • Constituent Information, Last Name • Constituent Information, Organization Name • Constituent Information, Key Indicator • Constituent Information, Import ID • Address, Preferred Address, Address Line 1 • Address, Preferred Address, Address Line 2 • Address, Preferred Address, City • Address, Preferred Address, State • Address, Preferred Address, ZIP • Address, Preferred Address, Import ID 4. Transfer the file to our FTP site 5. Email [email protected] when the file has been successfully transferred, indicating that you have uploaded your file for Enterprise Data Quality processing. Note: You will need to run AddressFinder once your EDQ Pro results are imported to standardize all addresses.  You are granted a free AddressFinder screening with your purchase of EDQ Pro.
__label__pos
0.546372
AppDynamics Extension for AWS API Gateway Monitoring Use Case Captures statistics for APIs in the API Gateway from Amazon CloudWatch and displays them in the AppDynamics Metric Browser. Prerequisites 1. Before the extension is installed, the prerequisites mentioned here need to be met. Please do not proceed with the extension installation if the specified prerequisites are not met. 2. The following permissions are needed to the AWS user whose accessKey and secretKey ae going to be used in the extension. cloudwatch:ListMetrics, cloudwatch:GetMetricStatistics The alternative to providing keys in the extension is installing the machine agent with the extension on an AWS EC2 instance and providing the instance with a role that has the above permissions. Installing the extension 1. Download and unzip the AWSAPIGatewayMonitor-version.zip file into <MACHINE_AGENT_HOME>/monitors/ directory. 2. Configure the extension by referring to the below section. 3. Restart the machine agent. Configuring the extension using config.yml Configure the AWS API Gateway monitoring extension by editing the config.yml file in <MACHINE_AGENT_HOME>/monitors/AWSAPIGatewayMonitor/ 1. Edit the file config.yml located at <MachineAgent_Dir>/monitors/AWSAPIGatewayMonito The metricPrefix of the extension has to be configured as specified here. Please make sure that the right metricPrefix is chosen based on your machine agent deployment, otherwise this could lead to metrics not being visible in the controller. 2. Configure the cloud watch monitoring level. This is required to reduce the number of API calls to cloudwatch. Basic will fire CloudWatch API calls every 5 minutes. Detailed will fire CloudWatch API calls every 1 minutes cloudWatchMonitoring: "Basic" If you want to run the extension with a further delay, comment the "cloudWatchMonitoring" and use the following field which takes in the number of minutes after which the extension should call the cloudwatch metrics. cloudWatchMonitoringInterval:10 3. Configure the AWS account by specifying the awsAccessKey, awsSecretKey of the AWS account. displayAccountName(required) and regions(required) also needs to be configured. For example, accounts: - awsAccessKey: "XXXXXXXX1" awsSecretKey: "XXXXXXXXXX1" displayAccountName: "TestAccount_1" regions: ["us-east-1","us-west-1","us-west-2"] NOTE: If you have the machine agent with extension installed on an AWS EC2 instance which has an assigned role with appropriate permissions as specified in the prerequisites section, then the awsAccessKey and awsSecretKey fields should be left empty as follows: accounts: - awsAccessKey: "" awsSecretKey: "" displayAccountName: "TestAccount_1" regions: ["us-east-1","us-west-1","us-west-2"] 4. If you know for which Apis you need the metrics for, the you can monitor only those Apis. This can be done by secifying the patterns of the Api names that needs to be minitored For example, If you want only Apis who name is exactly "sample" as well as the Apis with the name starting with demo, then you can configure it as below apiNames: ["^sample$", "^demo"] Metrics The following metrics are available at each API level: • 4XXError : The number of client-side errors captured in a specified period. • 5XXError : The number of server-side errors captured in a given period. • CacheHitCount : The number of requests served from the API cache in a given period. • CacheMissCount : The number of requests served from the back end in a given period, when API caching is enabled. • Count : The total number API requests in a given period. • IntegrationLatency : The time between when API Gateway relays a request to the back end and when it receives a response from the back end. • Latency : The time between when API Gateway receives a request from a client and when it returns a response to the client. The latency includes the integration latency and other API Gateway overhead. Apart from the above metrics, the extension also gives a metric called "API calls" at the extension level, that gives out the number of cloudwatch API calls per minutes from the extension. Advanced Configuration Prerequisites: You need to have events service setup and working before you do the following. Configuration steps: To get configuration metrics related to AWS API Gateway on your analytics platform, please follow the below steps: • 1. In the config.yml, uncomment the following section and enable the different metrics you want. #eventsService: # enableTraditionalMetrics: false # enableApiMetrics: false # enableResourceMetrics: false # enableStageMetrics: false # credentials: # controllerEventsServiceHost: "" # controllerEventsServicePort: 9080 # enableSSL: false # controllerGlobalAccountName: "" # eventsAPIKey: "" • 2. For example, if you want to enable the resource metrics, change the enableResourceMetrics field to true. Do the same for enableTraditionalMetrics, enableApiMetrics, enableResourceMetrics, enableStageMetrics as per you requirement. enableTraditionalMetrics: false enableApiMetrics: false enableResourceMetrics: false enableStageMetrics: false • 3. Fill out the credentials section with the events service host credentials. "controllerEventsServiceHost" is the host that contains the events service. "controllerEventsServicePort" is the port of the events service. "controllerGlobalAccountName" is the Global Account Name that can be found from License -> Account in the controller. You need to create an eventsAPIKey for the extension. This can be done from the analytics section on the controller. credentials: controllerEventsServiceHost: "" controllerEventsServicePort: 9080 enableSSL: false controllerGlobalAccountName: "" eventsAPIKey: "" • 4. Once all the details are filled and the extension is restarted, you can see the configuration metrics in the analytics section of the controller. The tables that contain the data are: AWSAPIGatewayMonitor_traditionalMetrics AWSAPIGatewayMonitor_APIMetrics AWSAPIGatewayMonitor_ResourceMetrics AWSAPIGatewayMonitor_StageMetrics WorkBench Workbench is an inbuilt feature provided with each extension in order to assist you to fine tune the extension setup before you actually deploy it on the controller. Please review the following document on How to use the Extensions WorkBench Troubleshooting Please follow the steps specified in the Troubleshooting document to debug problems faced while using the extension. Contributing Always feel free to fork and contribute any changes directly via GitHub. Compatibility Current Version: 2.0.1 Controller compatibility: 4.4 or later Last Update: 03/22/2019
__label__pos
0.828065
Layers Layers - 1 year ago 81 PHP Question In PHP does return false bubble up? I have a class with some methods in php. One public method calls a protected method. If the protected method returns false will the public method return false and not continue? public static function a() { $class = getClass(); // some more code... } protected static function getClass() { $classList = self::find_by_sql(" SELECT * FROM ".self::$table_name." WHERE Class_Closed = FALSE ORDER BY Start_Date ASC ;"); if (empty($classList)) { return false; } else { return $classList[0]; } } Answer Source No. $class will have a false value but you still need to return it from YourClass::a() if you want the method to terminate and return that value immediately. return only is in scope of the function/method it is called from. public static function a(){ $class = getClass(); if (!$class) { return false; // or return $class; } some more code... } Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
__label__pos
0.999962
Sign up × Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required. In a Markov chain $(X_t)$, is it possible to find an initial distribution for $X_0$, s.t. the distribution of $X_t$ doesn't converge in some sense (such as wrt total variation) as $t \to \infty$? The MC can be continuous or discrete-time, finite or infinite-state, homogeneous or inhomogeneous, .... But it will be the best that the MC is as special as possible, e.g., discrete-time, finite-state, homogeneous, .... Thanks and regards! share|cite|improve this question 1 Answer 1 up vote 2 down vote accepted Suppose the finitely many states of a Markov chain are partitioned into "even" states and "odd" states, and whenever you're in an "even" state you always go from there to an "odd" state and vice-versa. Then there's no limiting distribution if the initial distribution makes the sum of the probabilities of all the even states equal to $1$. share|cite|improve this answer      Thanks! I see. This example is not an aperiodic MC. Otherwise and if the MC is irreducible, there will be a limiting distribution for all initial distributions. – Tim Dec 10 '12 at 4:20      I was wondering what condition can make every initial distribution has a limit distribution? Note that the limit distributions for different initial distributions may be different. – Tim Dec 10 '12 at 14:07 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.841557
The name of this blog, Rainbow Juice, is intentional. The rainbow signifies unity from diversity. It is holistic. The arch suggests the idea of looking at the over-arching concepts: the big picture. To create a rainbow requires air, fire (the sun) and water (raindrops) and us to see it from the earth. Juice suggests an extract; hence rainbow juice is extracting the elements from the rainbow, translating them and making them accessible to us. Juice also refreshes us and here it symbolises our nutritional quest for understanding, compassion and enlightenment. Wednesday 27 January 2021 Unnatural Us What drives the development of technology?  Some suggest it is our desire to innovate.  Others claim that it is simply our curiosity. Or is it something more?  Curiosity may be a driver behind science: the desire to discover how the world works.  Technology, however, is not about understanding how the world works.  Technology seeks to change how the world works.  Technology seeks to “improve” our lives by making things quicker, easier, better (an ill-defined term if ever there was one), more comfortable. How did we come to thinking that what the earth provides is insufficient?  How did we decide that the world needs to be improved?  How did we conclude that we (as human beings) needed to be “perfected”?  In short, why do we wish to be unnatural? Why is it that we want to reconstruct ourselves?  What is wrong with us, as we are?  What is wrong with taking our lives at a slower pace?  What is wrong with discomfort?  What is wrong with nature, or our “natural” state? Perhaps in our human evolutionary journey some technology was useful.  Technological innovation allowed us to feed ourselves, shelter ourselves, and provide healing when we harmed ourselves. But sometime (certainly since the beginning of the Industrial Revolution in western cultures) we crossed beyond the bounds of useful technology and tipped into unnecessary and unhealthy technological development.  Now, a few hundred years (a blink in the age of homo sapiens) later we are suffering the harmful consequences. Our communication is quicker, almost instantaneous, yet our ability to understand and empathise with one another is deteriorating.  We can travel from A to B without having to expend human energy, yet our obesity rates are skyrocketing, and fitness levels dropping alarmingly. We can watch a TV show or a movie anywhere and anytime we like, yet we no longer participate in life’s magnificent opportunities.  We can sit in a factory, a laboratory, or a boardroom for eight or more hours a day, yet we cannot find time to sit beneath a tree, or on a hillside to watch the sunrise or sunset. Technology has taken us to the bottom of the oceans and out to the moon, yet our rates of depression, anxiety, and alienation show no signs of bottoming-out. Technology has taught us that we can be in control of nature, and ourselves, yet we have not learnt to let go of the need to control. How did we come to this wish to be unnatural?  I am reminded Henry David Thoreau’s words, some one hundred years ago:  “Our inventions are wont to be pretty toys, which distract us from serious things.  They are an improved means to an unimproved end.” No comments: Post a Comment This blogsite is dedicated to positive dialoque and a respectful learning environment. Therefore, I retain the right to remove comments that are: profane, personal attacks, hateful, spam, offensive, irrelevant (off-topic) or detract in other ways from these principles.
__label__pos
0.713362
Fix : double destroy in context remove [babeltrace.git] / lib / context.c 1 /* 2 * context.c 3 * 4 * Babeltrace Library 5 * 6 * Copyright 2011-2012 EfficiOS Inc. and Linux Foundation 7 * 8 * Author: Mathieu Desnoyers <[email protected]> 9 * Julien Desfossez <[email protected]> 10 * 11 * Permission is hereby granted, free of charge, to any person obtaining a copy 12 * of this software and associated documentation files (the "Software"), to deal 13 * in the Software without restriction, including without limitation the rights 14 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 15 * copies of the Software, and to permit persons to whom the Software is 16 * furnished to do so, subject to the following conditions: 17 * 18 * The above copyright notice and this permission notice shall be included in 19 * all copies or substantial portions of the Software. 20 */ 21 22 #include <babeltrace/babeltrace.h> 23 #include <babeltrace/context.h> 24 #include <babeltrace/context-internal.h> 25 #include <babeltrace/trace-handle.h> 26 #include <babeltrace/trace-handle-internal.h> 27 #include <babeltrace/trace-collection.h> 28 #include <babeltrace/format.h> 29 #include <babeltrace/babeltrace-internal.h> 30 #include <stdlib.h> 31 #include <string.h> 32 #include <assert.h> 33 34 #include <fts.h> 35 #include <fcntl.h> /* For O_RDONLY */ 36 37 #include <glib.h> 38 39 struct bt_context *bt_context_create(void) 40 { 41 struct bt_context *ctx; 42 43 ctx = g_new0(struct bt_context, 1); 44 ctx->refcount = 1; 45 /* Negative handle id are errors. */ 46 ctx->last_trace_handle_id = 0; 47 48 /* Instanciate the trace handle container */ 49 ctx->trace_handles = g_hash_table_new_full(g_direct_hash, 50 g_direct_equal, NULL, 51 (GDestroyNotify) bt_trace_handle_destroy); 52 53 ctx->current_iterator = NULL; 54 ctx->tc = g_new0(struct trace_collection, 1); 55 init_trace_collection(ctx->tc); 56 57 return ctx; 58 } 59 60 int bt_context_add_trace(struct bt_context *ctx, const char *path, 61 const char *format_name, 62 void (*packet_seek)(struct stream_pos *pos, size_t index, 63 int whence), 64 struct mmap_stream_list *stream_list, 65 FILE *metadata) 66 { 67 struct trace_descriptor *td; 68 struct format *fmt; 69 struct bt_trace_handle *handle; 70 int ret; 71 72 fmt = bt_lookup_format(g_quark_from_string(format_name)); 73 if (!fmt) { 74 fprintf(stderr, "[error] [Context] Format \"%s\" unknown.\n\n", 75 format_name); 76 ret = -1; 77 goto end; 78 } 79 if (path) { 80 td = fmt->open_trace(path, O_RDONLY, packet_seek, NULL); 81 if (!td) { 82 fprintf(stderr, "[warning] [Context] Cannot open_trace of the format %s .\n\n", 83 path); 84 ret = -1; 85 goto end; 86 } 87 } else { 88 td = fmt->open_mmap_trace(stream_list, packet_seek, metadata); 89 if (!td) { 90 fprintf(stderr, "[error] [Context] Cannot open_trace of the format %s .\n\n", 91 path); 92 ret = -1; 93 goto end; 94 } 95 } 96 97 /* Create an handle for the trace */ 98 handle = bt_trace_handle_create(ctx); 99 if (handle < 0) { 100 fprintf(stderr, "[error] [Context] Creating trace handle %s .\n\n", 101 path); 102 ret = -1; 103 goto end; 104 } 105 handle->format = fmt; 106 handle->td = td; 107 handle->timestamp_begin = fmt->timestamp_begin(td, handle); 108 handle->timestamp_end = fmt->timestamp_end(td, handle); 109 strncpy(handle->path, path, PATH_MAX); 110 handle->path[PATH_MAX - 1] = '\0'; 111 112 if (fmt->set_handle) 113 fmt->set_handle(td, handle); 114 if (fmt->set_context) 115 fmt->set_context(td, ctx); 116 117 /* Add new handle to container */ 118 g_hash_table_insert(ctx->trace_handles, 119 (gpointer) (unsigned long) handle->id, 120 handle); 121 ret = trace_collection_add(ctx->tc, td); 122 if (ret == 0) 123 return handle->id; 124 end: 125 return ret; 126 } 127 128 void bt_context_remove_trace(struct bt_context *ctx, int handle_id) 129 { 130 struct bt_trace_handle *handle; 131 132 handle = g_hash_table_lookup(ctx->trace_handles, 133 (gpointer) (unsigned long) handle_id); 134 assert(handle != NULL); 135 136 /* Remove from containers */ 137 trace_collection_remove(ctx->tc, handle->td); 138 /* Close the trace */ 139 handle->format->close_trace(handle->td); 140 141 /* Remove and free the handle */ 142 g_hash_table_remove(ctx->trace_handles, 143 (gpointer) (unsigned long) handle_id); 144 145 } 146 147 static 148 void bt_context_destroy(struct bt_context *ctx) 149 { 150 finalize_trace_collection(ctx->tc); 151 152 /* Remote all traces. The g_hash_table_destroy will call 153 * bt_trace_handle_destroy on each elements. 154 */ 155 g_hash_table_destroy(ctx->trace_handles); 156 157 /* ctx->tc should always be valid */ 158 assert(ctx->tc != NULL); 159 g_free(ctx->tc); 160 g_free(ctx); 161 } 162 163 void bt_context_get(struct bt_context *ctx) 164 { 165 ctx->refcount++; 166 } 167 168 void bt_context_put(struct bt_context *ctx) 169 { 170 ctx->refcount--; 171 if (ctx->refcount == 0) 172 bt_context_destroy(ctx); 173 } This page took 0.053207 seconds and 5 git commands to generate.
__label__pos
0.999533
Properties Label 2-1638-1.1-c1-0-22 Degree $2$ Conductor $1638$ Sign $-1$ Analytic cond. $13.0794$ Root an. cond. $3.61655$ Motivic weight $1$ Arithmetic yes Rational no Primitive yes Self-dual yes Analytic rank $1$ Origins Related objects Downloads Learn more Normalization:   Dirichlet series L(s)  = 1  − 2-s + 4-s + 0.561·5-s − 7-s − 8-s − 0.561·10-s − 2.56·11-s + 13-s + 14-s + 16-s − 5.68·17-s + 7.68·19-s + 0.561·20-s + 2.56·22-s + 1.43·23-s − 4.68·25-s − 26-s − 28-s + 5.68·29-s − 10.2·31-s − 32-s + 5.68·34-s − 0.561·35-s − 3.43·37-s − 7.68·38-s − 0.561·40-s − 7.12·41-s + ⋯ L(s)  = 1  − 0.707·2-s + 0.5·4-s + 0.251·5-s − 0.377·7-s − 0.353·8-s − 0.177·10-s − 0.772·11-s + 0.277·13-s + 0.267·14-s + 0.250·16-s − 1.37·17-s + 1.76·19-s + 0.125·20-s + 0.546·22-s + 0.299·23-s − 0.936·25-s − 0.196·26-s − 0.188·28-s + 1.05·29-s − 1.84·31-s − 0.176·32-s + 0.974·34-s − 0.0949·35-s − 0.565·37-s − 1.24·38-s − 0.0887·40-s − 1.11·41-s + ⋯ Functional equation \[\begin{aligned}\Lambda(s)=\mathstrut & 1638 ^{s/2} \, \Gamma_{\C}(s) \, L(s)\cr =\mathstrut & -\, \Lambda(2-s) \end{aligned}\] \[\begin{aligned}\Lambda(s)=\mathstrut & 1638 ^{s/2} \, \Gamma_{\C}(s+1/2) \, L(s)\cr =\mathstrut & -\, \Lambda(1-s) \end{aligned}\] Invariants Degree: \(2\) Conductor: \(1638\)    =    \(2 \cdot 3^{2} \cdot 7 \cdot 13\) Sign: $-1$ Analytic conductor: \(13.0794\) Root analytic conductor: \(3.61655\) Motivic weight: \(1\) Rational: no Arithmetic: yes Character: Trivial Primitive: yes Self-dual: yes Analytic rank: \(1\) Selberg data: \((2,\ 1638,\ (\ :1/2),\ -1)\) Particular Values \(L(1)\) \(=\) \(0\) \(L(\frac12)\) \(=\) \(0\) \(L(\frac{3}{2})\) not available \(L(1)\) not available Euler product    \(L(s) = \displaystyle \prod_{p} F_p(p^{-s})^{-1} \) $p$$F_p(T)$ bad2 \( 1 + T \) 3 \( 1 \) 7 \( 1 + T \) 13 \( 1 - T \) good5 \( 1 - 0.561T + 5T^{2} \) 11 \( 1 + 2.56T + 11T^{2} \) 17 \( 1 + 5.68T + 17T^{2} \) 19 \( 1 - 7.68T + 19T^{2} \) 23 \( 1 - 1.43T + 23T^{2} \) 29 \( 1 - 5.68T + 29T^{2} \) 31 \( 1 + 10.2T + 31T^{2} \) 37 \( 1 + 3.43T + 37T^{2} \) 41 \( 1 + 7.12T + 41T^{2} \) 43 \( 1 + 10.5T + 43T^{2} \) 47 \( 1 + 47T^{2} \) 53 \( 1 - 4.24T + 53T^{2} \) 59 \( 1 - 14.2T + 59T^{2} \) 61 \( 1 + 5.68T + 61T^{2} \) 67 \( 1 - 1.12T + 67T^{2} \) 71 \( 1 + 8T + 71T^{2} \) 73 \( 1 - 0.561T + 73T^{2} \) 79 \( 1 + 2.87T + 79T^{2} \) 83 \( 1 + 17.1T + 83T^{2} \) 89 \( 1 + 10T + 89T^{2} \) 97 \( 1 + 18.4T + 97T^{2} \) show more show less    \(L(s) = \displaystyle\prod_p \ \prod_{j=1}^{2} (1 - \alpha_{j,p}\, p^{-s})^{-1}\) Imaginary part of the first few zeros on the critical line −8.943546469941654705387114337009, −8.368753807190748414751207446163, −7.33181853461224455582846520339, −6.82486306202951059930453674231, −5.75786970631544080979429890362, −5.04332455074417045923424864103, −3.67375410635739582237562205909, −2.72240667229055867481077864761, −1.60297949560182135315821130298, 0, 1.60297949560182135315821130298, 2.72240667229055867481077864761, 3.67375410635739582237562205909, 5.04332455074417045923424864103, 5.75786970631544080979429890362, 6.82486306202951059930453674231, 7.33181853461224455582846520339, 8.368753807190748414751207446163, 8.943546469941654705387114337009 Graph of the $Z$-function along the critical line
__label__pos
0.831958
//+------------------------------------------------------------------+ //| _i_EF_distance.mq4 | //| Copyright © 2006, Doji Starr | //| | //+------------------------------------------------------------------+ #property copyright "Copyright © 2006, Doji Starr" #property indicator_chart_window #property indicator_buffers 1 #property indicator_color1 Aqua // input params extern int Length = 10; extern double Power = 2; // vars int i, c, startBar; double coef, norm; // buffers double buf_el[], buf_co[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { IndicatorBuffers(2); SetIndexBuffer(0,buf_el); SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(1,buf_co); return(0); } //+------------------------------------------------------------------+ //| Custom indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { if (Bars <= Length) return(0); int bar; int counted_bars = IndicatorCounted(); if (counted_bars < 1) { // filling initial values in buffers for (bar=Bars-1; bar>=Bars-Length*2; bar--) { buf_el[bar] = Close[bar]; buf_co[bar] = 0.0; } startBar = Bars-Length*2-1; } else startBar = Bars-counted_bars-1; for (bar=startBar; bar>=0; bar--) { buf_co[bar] = 0.0; for (i=Length-1; i>=0; i--) buf_co[bar] += MathAbs(MathPow(Close[bar]-Close[bar+i], Power)); norm = 0.0; buf_el[bar] = 0.0; for (i=Length-1; i>=0; i--) { norm += buf_co[bar+i]; buf_el[bar] += buf_co[bar+i] * Close[bar+i]; } if (norm != 0) buf_el[bar] /= norm; else buf_el[bar] = 0.0; //Print(norm); } return(0); }
__label__pos
0.998303
yeti logo icon Close Icon contact us Yeti postage stamp We'll reply within 24 hours. Thank you! Your message has been received! A yeti hand giving a thumb's up Oops! Something went wrong while submitting the form. 9 Vital Insights for IoT Software Development and Connected Technology (Part 2) By Summer Swann - September 22, 2023 An IoT software development wizard Welcome to Part Two in our series  Building a Connected App: 9 Vital Insights for IoT Software Development. If you haven’t read part one, you can find it here. As mentioned in part one, creating a successful connected app is an incredibly involved process that goes far beyond merely ensuring functionality. In fact, a great deal of behind the scenes work goes into ensuring your app achieves seamless functionality and a high level of user satisfaction. Below, we outline crucial elements to consider during the IoT software development process. Ensuring that each of these areas are carefully considered throughout your app build will allow you to build a connected product that users can’t get enough of. 9 Vital Insights for IoT Software Development + Connected Apps Device Compatibility and Variability Connected software should be designed to support a wide range of compatibility and variability, including the ability to support various types of devices, and seamlessly integrate with various firmware versions. Supporting various device types and models The world of connected devices is evolving at a rapid pace, resulting in frequent hardware updates and a near constant introduction of newer device models. This continuous growth of   means that consumers often expect to have the ability to utilize multiple devices for their purposes. For these reason, connected software must be designed to support a wide range of device types and models. Whether it's smartphones, tablets, wearables, or smart home devices, compatibility across diverse devices is essential - and your development team should ensure that your software is able to function effectively across different devices and screen sizes, as well as the ability to maintain constant functionality and usability across various user interfaces. Differences in hardware capabilities and specifications Not all devices are created equal. When it comes to various types of devices, such as phones, tablets, laptops etc, there is often quite a bit of variation when it comes to their hardware capabilities (various sensors, GPS, cameras etc). If you are planning to build your software in a way that allows it to be accessed by a variety of device types, it’s crucial that your IoT software development team accounts for those differences while building your software. If your software doesn't perform well on a particular device due to its limited hardware capabilities, users will have a frustrating experience, leading to negative user experiences. Additionally, you’ll want to ensure that your connected software is designed to seamlessly integrate with firmware updates and new firmware versions. In addition to firmware versions, you’ll also want to ensure backward compatibility with older device models. Accommodating these older devices ensures that users with legacy devices will still have the ability to benefit from the software's functionality. Graceful degradation is another important aspect to consider, as this allows the software to adjust its features or performance based on the capabilities of the device, guaranteeing a consistent and positive user experience across a broad range of devices, regardless of their age or specifications. To ensure your software is fully accessible across devices, you’ll want to make sure your IoT software development team conducts extensive testing across many devices, hardware configurations, and firmware versions, including functional testing, usability testing, and compatibility testing User Experience and Interface When building connected software, taking the time to facilitate exceptional UX design (user experience design) is critical to success.  UX design is the process of creating meaningful, user-centered, intuitive, and enjoyable software experiences. This is a very specialized process that entails research, user interviews, and workshopping that allows designers to fully understand who their user is, and how to anticipate their wants and needs  (learn more about UX Design in our Ultimate Guide to IoT software development). In addition to UX design, you’ll also want to spend a significant amount of time on your softwares UI (user interface) which encompasses the visual and interactive elements of your software. UI design is concerned with ensuring that users are able to easily and quickly navigate and interact with your app. Another important aspect of design is ADA compliance - a complex system that outlines how to  build digital products that allow for an equal experience for all people, taking into consideration users with both permanent and/or temporary physical or mental disabilities.This involves providing accommodations such as alternative text for images, keyboard navigation, adjustable font sizes, voice recognition technology, screen readers and more. Because accessibly is so important, we’ve put together this free checklist and guide that provides all the information necessary to understanding ADA compliance. The following are some additional considerations for designing impactful, user friendly software Create an Intuitive and User-Friendly Interface Your software should provide users with an intuitive and user-friendly interface that allows them to immediately understand how to navigate your software, interact with elements, and accomplish tasks without confusion or frustration. Make it Efficient Good UX design focuses on streamlining user workflows and processes, enabling users to achieve their goals efficiently. When designing your connected software, ensure that tasks and actions are optimized for speed and ease of use. Make it Consistent Ensure that design elements, layouts, and interactions are consistent throughout your software. This consistency helps users build mental models and confidently predict how different parts of the product will work - allowing for more efficiency and far less frustration. Provide Clear Information Hierarchy A clear information hierarchy in UX design refers to the organization and presentation of information in a way that helps users quickly understand the importance and relationship of different elements. This plays a crucial role in guiding users through the product and ensuring they can easily find what they need. Users should be able to identify the most crucial information or actions easily, information should be grouped logically into categories or sections, and a clear visual hierarchy should be utilized through design elements such as size, color, contrast, and typography. Utilize Responsive Design: Different devices have different screen sizes, so it’s important that designers ensure that the software's user interface is responsive and adaptable to various device form factors. Responsive design ensures that your interface will remain usable and visually appealing across devices by dynamically adjusting based on the device type. Branding and Visual Identity Consistency with your brand's visual identity is essential for establishing a strong and recognizable brand presence. To achieve this, designers should incorporate your brand's colors, typography, and visual elements consistently throughout your software's UI. Connectivity and Network Reliability Considering our increasing reliance on connected devices, it’s understandable that ensuring your software is accessible and functional whenever and wherever a user decides to utilize it is incredibly important. To maximize your softwares reach and accessibility, and to help ensure that users are able to connect their devices regardless of the network technology, it’s important that your connected software is designed to support various network protocols, such as Wi-Fi, Bluetooth, and cellular connections. By doing so, you help ensure that your software has the ability to leverage the available network infrastructure - providing users with consistent and seamless service. However, as we’re all aware, intermittent connectivity issues can be a common occurrence. For this reason, your connected software should be designed to handle connectivity issues gracefully, without causing disruption to the user experience. This can be done by implementing techniques such as intelligent buffering, offline caching, and asynchronous data synchronization, which allow the software to provide smooth operation even during periods of limited or no connectivity. For instances when users temporarily have no connectivity, offline functionalities and data synchronization mechanisms can be a game changer. By incorporating offline functionality into your software, you allow users to continue using certain features even when not connected to a network - for example, a note-taking app may allow users to create or edit notes offline, and then provide automatic synchronization once a connection is again available. As per the previous example, providing data synchronization ensures that any changes a user makes offline are seamlessly updated across devices and platforms once it reconnects with a network. This keeps the user's data consistent and up to date, regardless of the device they use.For instance, a cloud storage app can automatically synchronize files across devices, ensuring that the latest version of a file is always accessible. Finally, it’s important to ensure that your connected software monitors and optimizes network usage, as doing so allows your app to provide efficient and responsible utilization of network resources. Developers can help reduce strain on network infrastructure and enhance overall performance by creating systems that manage network bandwidth effectively, for example by minimizing unnecessary data transfers and implementing efficient data compression techniques. Over-the-Air (OTA) Updates Over-the-Air (OTA) updates are software updates that enable improvements, bug fixes, and the delivery of new features to connected devices, without requiring physical intervention. Providing secure and reliable OTA update mechanisms are of paramount importance for connected devices as they ensure that update packages are securely delivered and installed on devices, while additionally, protecting against potential vulnerabilities or unauthorized access during the update process, thus safeguarding the integrity of the software and the connected device as a whole. During OTA updates, it’s important to maintain backward compatibility to ensure a seamless transition for users. This means that new software versions should be designed to be compatible with older versions of the software and the connected device itself. By considering backward compatibility, developers prevent disruptions in functionality or user experiences when updating the software. Another vital component of OTA updates are version control and rollback strategies. These strategies allow developers to maintain control over the software's stability and quickly address any issues that might arise during software updates. Version control is a strategy that allows developers to manage software versions, including efficiently troubleshooting and debugging various versions of the software. Typically, version control tracks all software changes as they’re made, and is able to identify specific versions that have been deployed to devices. This can be a lifesaver, should issues arise from a specific software update. Similarly, rollback strategies allow developers to revert to a previous software version should a software update cause unforeseen problems. Data Management and Analytics Connected devices generate massive amounts of valuable data, making effective data management and analytics crucial. Implementing a robust data analytics system unlocks the true potential of this data and offers numerous benefits for both users and development teams. Data analytics enable development teams to gain actionable insights into user behavior, preferences, and usage patterns, which can be leveraged to enhance the user experience. For example, by analyzing user data, a smart home system can learn the occupants' daily routines and automatically adjust lighting, temperature, and other settings to align with their preferences, creating a more personalized and comfortable living environment. Furthermore, data analytics can empower users by providing personalized recommendations and insights. For instance, a connected health and wellness app can analyze user data, such as exercise habits and sleep patterns, and then offer tailored suggestions for improving overall well-being. This could include customized exercise plans, sleep optimization techniques, and nutritional recommendations based on individual needs and goals. Data analytics also enables predictive capabilities that can enhance the user experience. By leveraging machine learning algorithms, a smart assistant can analyze user interactions and preferences to anticipate their needs and proactively provide relevant information or assistance. For example, a voice-activated assistant can learn a user's preferences for music, news, and weather updates and provide personalized recommendations without the need for explicit requests. Another benefit of data analytics is anomaly detection. By monitoring and analyzing data from connected devices, potential issues or abnormalities can be identified in real-time. For instance, an energy monitoring system can analyze electricity usage patterns and detect unusual spikes or irregularities, which can indicate malfunctioning appliances or potential safety hazards. This enables timely intervention and preventive maintenance, ensuring a safer and more efficient user experience. Moreover, data analytics can contribute to product improvement and innovation. By aggregating and analyzing data from a large user base, development teams can identify usage patterns, emerging trends, and areas for improvement. This information can guide the development of new features, enhancements, and even entirely new products that better meet user needs. For example, a smart home security system provider can analyze user data to identify common vulnerabilities or user concerns and develop enhanced security features to address them. Data analytics can go beyond improving the user experience and enable proactive device management. By leveraging predictive analytics techniques, connected device software can anticipate device failures, identify maintenance requirements, and optimize device performance. For example, by analyzing sensor data, a smart thermostat can proactively detect anomalies, such as temperature fluctuations, and trigger maintenance notifications or automatically adjust settings to prevent system failures. Battery Efficiency and Power Optimization When building connected software, optimizing battery efficiency and power consumption is essential to providing a positive user experience. By implementing strategies to minimize power consumption and efficiently handle background processes and notifications, developers can ensure that the software operates efficiently and conserves battery power. One key consideration is optimizing the software itself to minimize power consumption. This involves identifying and optimizing resource-intensive tasks, such as excessive CPU usage, unnecessary network requests, or continuous location tracking. By reducing these activities, the software can minimize the strain on the device's battery. For example, a navigation app can employ smart algorithms to minimize GPS usage and optimize route calculations, resulting in reduced battery drain. Efficient handling of background processes and notifications is another crucial aspect of power optimization. Background processes, such as data synchronization or updates, should be carefully managed to prevent excessive battery usage. Implementing intelligent scheduling mechanisms can ensure that background tasks are executed when the device is connected to a power source or during periods of low user activity, thus minimizing their impact on battery life. Similarly, managing notifications and their frequency helps prevent unnecessary wake-ups and reduces battery drain caused by constant display or network activity. Implementing power-saving modes or features within the software is another effective strategy.Power-saving modes allow users to customize settings that optimize power consumption, such as reducing screen brightness, disabling background data usage, or limiting the functionality of non-essential features. By providing these options, users can choose the level of power optimization that suits their needs and extend their device's battery life. Efficient use of sensors and connectivity modules is crucial for battery optimization. Connected devices often rely on various sensors, such as accelerometers, gyroscopes, or ambient light sensors, which consume significant power. By intelligently utilizing these sensors only when necessary, the software can minimize power drain. Additionally, optimizing the use of connectivity modules like Wi-Fi, Bluetooth, or cellular data by employing efficient algorithms and techniques reduces unnecessary power consumption. Continuous monitoring and optimization of power usage is vital for maintaining battery efficiency. Developers should regularly analyze power consumption patterns and identify areas for improvement. By using profiling tools and analyzing energy usage reports, they can pinpoint areas of the software that are consuming excessive power and make the necessary optimizations. This iterative approach ensures that power optimization efforts remain effective over time and with software updates. We know that embarking on the journey of creating a new connected app can feel overwhelming, and that the IoT software development process can seem daunting! We hope this article has provided you with the insight and confidence necessary to move forward with success! Yeti is an IoT application development company. If you'd like to learn more about what we do, be sure to take a look at our work page featuring insightful case studies showcasing our collaborations with renowned clients such as Google, Netflix, Westfield, and many others. For more insightful content, don't miss the Yeti blog and our extensive library of IoT software development content. If you're working on a connected app and need the assistance of an experienced IoT software development team, we’re here to help. Feel free to reach out - we’d love to chat! In the meantime be sure to download our free Guide to IoT software development here! Summer is Yeti's Marketing Manager. When not working, you can find her searching for thrift store treasure, hiking in the Sierra Nevadas, camping, cooking vegan treats and reading anything she can get her hands on. Summer lives surrounded by wilderness in the remote mountains of California and has been known to complete the New York Times crossword puzzle in record time. You Might also like... a person working on the bluetooth app development and design processThe Role of UX in Bluetooth App Development: Creating Intuitive, User-Centric Interfaces UX design plays a crucial role in the Bluetooth app development process. In this article we're sharing how UX design principles, intuitive interfaces, and thoughtful design strategies elevate the user experience, driving engagement and satisfaction in the world of Smart products and Bluetooth enabled apps. an illustration of bluetooth app development productsHere’s Everything You Need to Know About the Bluetooth App Development Process (Part Two) Need a stellar companion app for your Bluetooth enabled product? Truly understanding the Bluetooth app development process is the secret to your success. In part 2 of our blog series covering everything you need to know about the challenges inherent in the Bluetooth app development process, including how you can find the right team to bring your vision to life! illustration of bluetooth app development productsHere’s Everything You Need to Know About the Bluetooth App Development Process (Part One) You’ve built a Bluetooth device and now need a companion app—but where do you start? This two-part blog series covers everything you need to know about Bluetooth app development, including how to find the right team to turn your vision into reality! Browse all Blog Articles Ready for your new product adventure? Let's Get Started
__label__pos
0.901064
Query With Structured Data KSQL enables querying structured, or nested, data, by using the STRUCT data type. You use familiar syntax to declare and access structured data, like mystruct STRUCT<fieldName1 type1, fieldName2 type2> and mystruct->fieldName1. The following example shows how to create a KSQL stream from an Apache Kafka® topic that has structured data. Also, it shows how to run queries to access the structured data. 1. Set up the KSQL environment. 2. Use the kafkacat utility to create and populate a new topic, named raw-topic. 3. Create a stream on the topic that models the topic's data. 4. Inspect the stream to ensure that the data model matches the topic. 5. Query the stream to access the structured data. Set up the KSQL Environment To set up KSQL, follow the first three steps in Writing Streaming Queries Against Apache Kafka® Using KSQL (Docker), or if you have git and Docker installed already, run the following commands: # Step 1 git clone https://github.com/confluentinc/ksql.git cd ksql # Step 2 git checkout 5.3.0-post # Step 3 cd docs/tutorials/ docker-compose up -d After all of the Docker images are pulled, confirm that the KSQL and Kafka containers are running: docker-compose ps Your output should resemble: Name Command State Ports ---------------------------------------------------------------------------------------------------- tutorials_kafka_1 /etc/confluent/docker/run Up 0.0.0.0:39092->39092/tcp, 9092/tcp tutorials_ksql-server_1 /etc/confluent/docker/run Up 8088/tcp tutorials_schema-registry_1 /etc/confluent/docker/run Up 8081/tcp tutorials_zookeeper_1 /etc/confluent/docker/run Up 2181/tcp, 2888/tcp, 3888/tcp The KSQL environment is ready for you to develop real-time streaming applications. Create and Populate a New Topic With Structured Data Use the kafkacat utility to create and populate a new topic, named raw-topic, with some records that have nested data. The records are formatted as JSON arrays. For more information, see kafkacat Utility. docker run --interactive --rm --network tutorials_default \ confluentinc/cp-kafkacat \ kafkacat -b kafka:39092 \ -t raw-topic \ -K: \ -P <<EOF 1:{"type":"key1","data":{"timestamp":"2018-12-21 23:58:42.1","field-a":1,"field-b":"first-value-for-key1"}} 2:{"type":"key2","data":{"timestamp":"2018-12-21 23:58:42.2","field-a":1,"field-c":11,"field-d":"first-value-for-key2"}} 3:{"type":"key1","data":{"timestamp":"2018-12-21 23:58:42.3","field-a":2,"field-b":"updated-value-for-key1"}} 4:{"type":"key2","data":{"timestamp":"2018-12-21 23:58:42.4","field-a":3,"field-c":22,"field-d":"updated-value-for-key2"}} EOF The nested structure is named data and has five fields: • timestamp, a string • field-a, an integer • field-b, a string • field-c, an integer • field-d, a string In the following KSQL queries, the data structure is modeled by using the STRUCT type: DATA STRUCT<timestamp VARCHAR, "field-a" INT, "field-b" VARCHAR, "field-c" INT, "field-d" VARCHAR> Double-quotes are necessary for the fieldnames that contain the - character. Note Properties is not a valid field name. Create a Stream With Structured Data Start the KSQL CLI: docker run --network tutorials_default --rm --interactive --tty \ confluentinc/cp-ksql-cli:5.3.0 \ http://ksql-server:8088 In the KSQL CLI, ensure that raw-topic is available: SHOW TOPICS; Your output should resemble: Kafka Topic | Registered | Partitions | Partition Replicas | Consumers | ConsumerGroups ------------------------------------------------------------------------------------------------ _confluent-metrics | false | 12 | 1 | 0 | 0 _schemas | false | 1 | 1 | 0 | 0 raw-topic | false | 1 | 1 | 0 | 0 ------------------------------------------------------------------------------------------------ Inspect raw-topic to ensure that kafkacat populated it: PRINT 'raw-topic' FROM BEGINNING; Your output should resemble: Format:JSON {"ROWTIME":1544042630406,"ROWKEY":"1","type":"key1","data":{"timestamp":"2018-12-21 23:58:42.1","field-a":1,"field-b":"first-value-for-key1"}} {"ROWTIME":1544042630406,"ROWKEY":"2","type":"key2","data":{"timestamp":"2018-12-21 23:58:42.2","field-a":1,"field-c":11,"field-d":"first-value-for-key2"}} {"ROWTIME":1544042630406,"ROWKEY":"3","type":"key1","data":{"timestamp":"2018-12-21 23:58:42.3","field-a":2,"field-b":"updated-value-for-key1"}} {"ROWTIME":1544042630406,"ROWKEY":"4","type":"key2","data":{"timestamp":"2018-12-21 23:58:42.4","field-a":3,"field-c":22,"field-d":"updated-value-for-key2"}} ^CTopic printing ceased Press Ctrl+C to stop printing the topic. Run the following CREATE STREAM statement to register the topic with KSQL: CREATE STREAM T (TYPE VARCHAR, DATA STRUCT< timestamp VARCHAR, "field-a" INT, "field-b" VARCHAR, "field-c" INT, "field-d" VARCHAR>) WITH (KAFKA_TOPIC='raw-topic', VALUE_FORMAT='JSON'); Your output should resemble: Message ---------------- Stream created ---------------- Run KSQL Queries to Access the Structured Data Run the following command to tell KSQL to read from the beginning of the topic: SET 'auto.offset.reset' = 'earliest'; Run a SELECT query to inspect the T stream: SELECT * FROM T; Your output should resemble: 1544042630406 | 1 | key1 | {TIMESTAMP=2018-12-21 23:58:42.1, field-a=1, field-b=first-value-for-key1, field-c=null, field-d=null} 1544042630406 | 2 | key2 | {TIMESTAMP=2018-12-21 23:58:42.2, field-a=1, field-b=null, field-c=11, field-d=first-value-for-key2} 1544042630406 | 3 | key1 | {TIMESTAMP=2018-12-21 23:58:42.3, field-a=2, field-b=updated-value-for-key1, field-c=null, field-d=null} 1544042630406 | 4 | key2 | {TIMESTAMP=2018-12-21 23:58:42.4, field-a=3, field-b=null, field-c=22, field-d=updated-value-for-key2} ^CQuery terminated Press Ctrl+C to cancel the SELECT query. Note KSQL assigns null to the fields that were omitted when kafkacat populated raw-topic, like field-c and field-d in record key1. Query field-a and field-b by using the -> operator to access the nested elements: SELECT DATA->"field-a", DATA->"field-b" FROM T WHERE TYPE='key1' LIMIT 2; Your output should resemble: 1 | first-value-for-key1 2 | updated-value-for-key1 Limit Reached Query terminated Query the other nested elements: SELECT DATA->"field-a", DATA->"field-c", DATA->"field-d" FROM T WHERE TYPE='key2' LIMIT 2; Your output should resemble: 1 | 11 | first-value-for-key2 3 | 22 | updated-value-for-key2 Limit Reached Query terminated Create persistent queries based on the previous SELECT statements. In this example, two different queries are used to separate the input data into two new streams. CREATE STREAM TYPE_1 AS SELECT DATA->"field-a", DATA->"field-b" FROM T WHERE TYPE='key1'; CREATE STREAM TYPE_2 AS SELECT DATA->"field-a", DATA->"field-c",DATA->"field-d" FROM T2 WHERE TYPE='key2'; For both statements, your output should resemble: Message ---------------------------- Stream created and running ---------------------------- Inspect the schema of the TYPE_1 stream: DESCRIBE TYPE_1; Your output should resemble: Name : TYPE_1 Field | Type ------------------------------------------- ROWTIME | BIGINT (system) ROWKEY | VARCHAR(STRING) (system) DATA__field-a | INTEGER DATA__field-b | VARCHAR(STRING) ------------------------------------------- For runtime statistics and query details run: DESCRIBE EXTENDED <Stream,Table>; Inspect the schema of the TYPE_2 stream: DESCRIBE TYPE_2; Your output should resemble: Name : TYPE_2 Field | Type ------------------------------------------- ROWTIME | BIGINT (system) ROWKEY | VARCHAR(STRING) (system) DATA__field-a | INTEGER DATA__field-c | INTEGER DATA__field-d | VARCHAR(STRING) ------------------------------------------- For runtime statistics and query details run: DESCRIBE EXTENDED <Stream,Table>;
__label__pos
0.834913
Zen Mournster Zen Mournster - 10 months ago 47 Python Question Why can't I pass this int type variable as an argument in Python? Below are three functions that calculates a users holiday cost. The user is encouraged to enter details of his holiday which are then passed off into the functions as arguments. def hotel_cost(days): days = 140*days return days """This function returns the cost of the hotel. It takes a user inputed argument, multiples it by 140 and returns it as the total cost of the hotel""" def plane_ride_cost(city): if city=="Charlotte": return 183 elif city =="Tampa": return 220 elif city== "Pittsburgh": return 222 elif city=="Los Angeles": return 475 """this function returns the cost of a plane ticket to the users selected city""" def rental_car_cost(days): rental_car_cost=40*days if days >=7: rental_car_cost -= 50 elif days >=3: rental_car_cost -= 20 return rental_car_cost """this function calculates car rental cost""" user_days=raw_input("how many days would you be staying in the hotel?") """user to enter a city from one of the above choices""" user_city=raw_input("what city would you be visiting?") """user to enter number of days intended for holiday""" print hotel_cost(user_days) print plane_ride_cost(user_city) print rental_car_cost(user_days) I notice that when I print the functions above, only plane_ride_cost(user_city) runs correctly. The other two functions spit out gibberish. Why is this? Answer Source You need to convert the output of raw_input to int. This should work: user_days=int(raw_input("how many days would you be staying in the hotel?")) """user to enter a city from one of the above choices""" Note that if user enters anything but a number, this will raise an error.
__label__pos
0.996467
微信开源mars源码分析1—上层samples分析 机械面条 微信已经开源了mars,但是市面上相关的文章较少,即使有也是多在于使用xlog等这些,那么这次我希望能够从stn这个直接用于im底层通讯的部分进行个分析。 为了能分析的全面些,我们从samples开始。 首先明确下,微信用了google的开源协议protobuf库,来代替json和xml。至于为何使用这个,原因还在于效率和传输量上,效率上他能够比json提升将近10倍,而且基于二进制而非文本,传输的大小更加有优势,具体的不再累述,有兴趣的可以自己查查。 我们从samples开始看看通过http是怎么获得列表数据的,直接看/mars-master/samples/android/marsSampleChat/app/src/main/java/com/tencent/mars/sample/ConversationActivity.java,这个是个初始的列表界面,需要看的就是这个: /** * pull conversation list from server */ private void updateConversationTopics() { if (taskGetConvList != null) { MarsServiceProxy.cancel(taskGetConvList); } mTextView.setVisibility(View.INVISIBLE); progressBar.setVisibility(View.VISIBLE); swipeRefreshLayout.setRefreshing(true); taskGetConvList = new NanoMarsTaskWrapper<Main.ConversationListRequest, Main.ConversationListResponse>( new Main.ConversationListRequest(), new Main.ConversationListResponse() ) { private List<Conversation> dataList = new LinkedList<>(); @Override public void onPreEncode(Main.ConversationListRequest req) { req.type = conversationFilterType; req.accessToken = ""; // TODO: Log.d("xxx", "onPreEncode: " + req.toString()); } @Override public void onPostDecode(Main.ConversationListResponse response) { Log.d("xxx", "onPostDecode: " + response.toString()); } @Override public void onTaskEnd(int errType, int errCode) { Log.d("xxx", "onTaskEnd: " + errType + " " + errCode); runOnUiThread(new Runnable() { @Override public void run() { if (response != null) { for (Main.Conversation conv : response.list) { dataList.add(new Conversation(conv.name, conv.topic, conv.notice)); Log.d("xxx", conv.toString()); } } if (!dataList.isEmpty()) { progressBar.setVisibility(View.INVISIBLE); conversationListAdapter.list.clear(); conversationListAdapter.list.addAll(dataList); conversationListAdapter.notifyDataSetChanged(); swipeRefreshLayout.setRefreshing(false); } else { Log.i(TAG, "getconvlist: empty response list"); progressBar.setVisibility(View.INVISIBLE); mTextView.setVisibility(View.VISIBLE); } } }); } }; MarsServiceProxy.send(taskGetConvList.setHttpRequest(CONVERSATION_HOST, "/mars/getconvlist")); } 1. new了一个NanoMarsTaskWrapper对象,并Override了几个方法:onPreEncode、onPostDecode、onTaskEnd。分别是编码传输前回调,收到结果解码后回调,任务结束后回调; 2. 设置NanoMarsTaskWrapper对象的http url地址; 3. 通过MarsServiceProxy的send方法,执行发送; 通过这些,我们可以大体了解到,通过一个内置的任务体系,来进行传输的派发调用的;通过服务来驱使整个体系运转,并保证独立性; 其实在目录中已经可以看到了,samples分为2个部分,一个是app,另一个是wrapper,wrapper是jar。 好吧,我们从wrapper入手看下基本结构。 首先是manifest: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tencent.mars.sample.wrapper"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <application> <service android:name=".service.MarsServiceNative" android:process=":marsservice" /> <receiver android:name="com.tencent.mars.BaseEvent$ConnectionReceiver" android:process=":marsservice"/> </application> </manifest> 可以看到,独立进程的服务在这里约定了。广播接受者在这里约定了,与服务在同一进程中。 上面app中使用的MarsServiceProxy是个什么东西呢? public class MarsServiceProxy implements ServiceConnection { ...... private MarsServiceProxy() { worker = new Worker(); worker.start(); } public static void init(Context context, Looper looper, String packageName) { if (inst != null) { // TODO: Already initialized return; } gContext = context.getApplicationContext(); gPackageName = (packageName == null ? context.getPackageName() : packageName); gClassName = SERVICE_DEFUALT_CLASSNAME; inst = new MarsServiceProxy(); } ...... } 其实是从ServiceConnection继承下来的服务连接对象,但是他不仅仅是个连接对象。我们看到,他是个单例,在app的SampleApplicaton的onCreate中进行的初始化: // NOTE: MarsServiceProxy is for client/caller // Initialize MarsServiceProxy for local client, can be moved to other place MarsServiceProxy.init(this, getMainLooper(), null); app中调用的是send这个静态方法: public static void send(MarsTaskWrapper marsTaskWrapper) { inst.queue.offer(marsTaskWrapper); } 其实这个方法在操作的是队列LinkedBlockingQueue<MarsTaskWrapper>。看到了吧,这个MarsServiceProxy其实是个api代理,内部有缓存的任务队列,实际上send就是向这个线程安全的队列中加入一项任务MarsTaskWrapper。 暂时放一下,我们关注下他的服务功能。在构造的时候,new了一个Worker,并start了。这个worker就是一个线程: private static class Worker extends Thread { @Override public void run() { while (true) { inst.continueProcessTaskWrappers(); try { Thread.sleep(50); } catch (InterruptedException e) { // } } } } 也就是说,在这个类创建的时候,同时创建了一个工作线程,不断的以间隔50ms循环调用continueProcessTaskWrappers。再看continueProcessTaskWrappers: private void continueProcessTaskWrappers() { try { if (service == null) { Log.d(TAG, "try to bind remote mars service, packageName: %s, className: %s", gPackageName, gClassName); Intent i = new Intent().setClassName(gPackageName, gClassName); gContext.startService(i); if (!gContext.bindService(i, inst, Service.BIND_AUTO_CREATE)) { Log.e(TAG, "remote mars service bind failed"); } // Waiting for service connected return; } MarsTaskWrapper taskWrapper = queue.take(); if (taskWrapper == null) { // Stop, no more task return; } try { Log.d(TAG, "sending task = %s", taskWrapper); final String cgiPath = taskWrapper.getProperties().getString(MarsTaskProperty.OPTIONS_CGI_PATH); final Integer globalCmdID = GLOBAL_CMD_ID_MAP.get(cgiPath); if (globalCmdID != null) { taskWrapper.getProperties().putInt(MarsTaskProperty.OPTIONS_CMD_ID, globalCmdID); Log.i(TAG, "overwrite cmdID with global cmdID Map: %s -> %d", cgiPath, globalCmdID); } service.send(taskWrapper, taskWrapper.getProperties()); } catch (Exception e) { // RemoteExceptionHandler e.printStackTrace(); } } catch (Exception e) { } } 1.检查服务是否启动,没有则启动并返回等待下一个50ms再继续; 2.从队列中获取一个任务,并给他分配一个cmdID,然后调用MarsService的send方法执行真正的发送事件。 其实从上面看,这个服务代理就是做了这些事情,更深入的事情其实是交给了具体的服务进程来做的。这里就是个代理api。 好的,我们往下看具体的服务。 首先MarsService是个aidl的定义,不过我们从上面的这个线程循环里就可以看到,启动的服务是根据Intent i = new Intent().setClassName(gPackageName, gClassName);启动的,这个gClassName = SERVICE_DEFUALT_CLASSNAME;就是public static final String SERVICE_DEFUALT_CLASSNAME = "com.tencent.mars.sample.wrapper.service.MarsServiceNative";看到了吧,就是MarsServiceNative。 现在起进入到服务里面。 public class MarsServiceNative extends Service implements MarsService { private static final String TAG = "Mars.Sample.MarsServiceNative"; private MarsServiceStub stub; ...... } 这里保存了一个MarsServiceStub,后面的send都是调用他来实现的,现在暂时先放下send,看下onCreate: @Override public void onCreate() { super.onCreate(); final MarsServiceProfile profile = gFactory.createMarsServiceProfile(); stub = new MarsServiceStub(this, profile); // set callback AppLogic.setCallBack(stub); StnLogic.setCallBack(stub); SdtLogic.setCallBack(stub); // Initialize the Mars PlatformComm Mars.init(getApplicationContext(), new Handler(Looper.getMainLooper())); // Initialize the Mars StnLogic.setLonglinkSvrAddr(profile.longLinkHost(), profile.longLinkPorts()); StnLogic.setShortlinkSvrAddr(profile.shortLinkPort()); StnLogic.setClientVersion(profile.productID()); Mars.onCreate(true); StnLogic.makesureLongLinkConnected(); // Log.d(TAG, "mars service native created"); } 1.创建配置信息类MarsServiceProfile; 2.new出MarsServiceStub来; 3.设置各种回调; 4.初始化Mars; 5.Mars.onCreate(true); 6.StnLogic.makesureLongLinkConnected();确认长连接。 这里开始用到了Mars了,这个才是核心,并且不在这个工程中。核心的部分我们先放下,下一篇再深入分析。 回到MarsServiceStub,看他的send方法: @Override public void send(final MarsTaskWrapper taskWrapper, Bundle taskProperties) throws RemoteException { final StnLogic.Task _task = new StnLogic.Task(StnLogic.Task.EShort, 0, "", null); // Set host & cgi path final String host = taskProperties.getString(MarsTaskProperty.OPTIONS_HOST); final String cgiPath = taskProperties.getString(MarsTaskProperty.OPTIONS_CGI_PATH); _task.shortLinkHostList = new ArrayList<>(); _task.shortLinkHostList.add(host); _task.cgi = cgiPath; final boolean shortSupport = taskProperties.getBoolean(MarsTaskProperty.OPTIONS_CHANNEL_SHORT_SUPPORT, true); final boolean longSupport = taskProperties.getBoolean(MarsTaskProperty.OPTIONS_CHANNEL_LONG_SUPPORT, false); if (shortSupport && longSupport) { _task.channelSelect = StnLogic.Task.EBoth; } else if (shortSupport) { _task.channelSelect = StnLogic.Task.EShort; } else if (longSupport) { _task.channelSelect = StnLogic.Task.ELong; } else { Log.e(TAG, "invalid channel strategy"); throw new RemoteException("Invalid Channel Strategy"); } // Set cmdID if necessary int cmdID = taskProperties.getInt(MarsTaskProperty.OPTIONS_CMD_ID, -1); if (cmdID != -1) { _task.cmdID = cmdID; } TASK_ID_TO_WRAPPER.put(_task.taskID, taskWrapper); WRAPPER_TO_TASK_ID.put(taskWrapper, _task.taskID); // Send Log.i(TAG, "now start task with id %d", _task.taskID); StnLogic.startTask(_task); if (StnLogic.hasTask(_task.taskID)) { Log.i(TAG, "stn task started with id %d", _task.taskID); } else { Log.e(TAG, "stn task start failed with id %d", _task.taskID); } } 1.new一个StnLogic.Task; 2.设置task的参数,根据入口的Bundle; 3.2个map保存taskID与task的关系; 4.StnLogic.startTask(_task);启动任务执行; 这里的内容又深入到了Mars核心里,可以看到,关键的处理都是在Mars核心部分完成的,这里的内容甭管是服务还是什么都是在做参数的传递及关系的维护等工作。 好吧,我们倒带回来,回到MarsServiceStub,他实现了StnLogic.ICallBack这个interface。定义在mars里: public interface ICallBack { /** * SDK要求上层做认证操作(可能新发起一个AUTH CGI) * @return */ boolean makesureAuthed(); /** * SDK要求上层做域名解析.上层可以实现传统DNS解析,或者自己实现的域名/IP映射 * @param host * @return */ String[] onNewDns(final String host); /** * 收到SVR PUSH下来的消息 * @param cmdid * @param data */ void onPush(final int cmdid, final byte[] data); /** * SDK要求上层对TASK组包 * @param taskID 任务标识 * @param userContext * @param reqBuffer 组包的BUFFER * @param errCode 组包的错误码 * @return */ boolean req2Buf(final int taskID, Object userContext, ByteArrayOutputStream reqBuffer, int[] errCode, int channelSelect); /** * SDK要求上层对TASK解包 * @param taskID 任务标识 * @param userContext * @param respBuffer 要解包的BUFFER * @param errCode 解包的错误码 * @return int */ int buf2Resp(final int taskID, Object userContext, final byte[] respBuffer, int[] errCode, int channelSelect); /** * 任务结束回调 * @param taskID 任务标识 * @param userContext * @param errType 错误类型 * @param errCode 错误码 * @return */ int onTaskEnd(final int taskID, Object userContext, final int errType, final int errCode); /** * 流量统计 * @param send * @param recv */ void trafficData(final int send, final int recv); /** * 连接状态通知 * @param status 综合状态,即长连+短连的状态 * @param longlinkstatus 仅长连的状态 */ void reportConnectInfo(int status, int longlinkstatus); /** * SDK要求上层生成长链接数据校验包,在长链接连接上之后使用,用于验证SVR身份 * @param identifyReqBuf 校验包数据内容 * @param hashCodeBuffer 校验包的HASH * @param reqRespCmdID 数据校验的CMD ID * @return ECHECK_NOW(需要校验), ECHECK_NEVER(不校验), ECHECK_NEXT(下一次再询问) */ int getLongLinkIdentifyCheckBuffer(ByteArrayOutputStream identifyReqBuf, ByteArrayOutputStream hashCodeBuffer, int[] reqRespCmdID); /** * SDK要求上层解连接校验回包. * @param buffer SVR回复的连接校验包 * @param hashCodeBuffer CLIENT请求的连接校验包的HASH值 * @return */ boolean onLongLinkIdentifyResp(final byte[] buffer, final byte[] hashCodeBuffer); /** * 请求做sync */ void requestDoSync(); String[] requestNetCheckShortLinkHosts(); /** * 是否登录 * @return true 登录 false 未登录 */ boolean isLogoned(); void reportTaskProfile(String taskString); } 可以看到都是回调,通过mars的回调,MarsServiceStub接收到了taskend,并执行了: @Override public int onTaskEnd(int taskID, Object userContext, int errType, int errCode) { final MarsTaskWrapper wrapper = TASK_ID_TO_WRAPPER.remove(taskID); if (wrapper == null) { Log.w(TAG, "stn task onTaskEnd callback may fail, null wrapper, taskID=%d", taskID); return 0; // TODO: ??? } try { wrapper.onTaskEnd(errType, errCode); } catch (RemoteException e) { e.printStackTrace(); } finally { WRAPPER_TO_TASK_ID.remove(wrapper); // onTaskEnd will be called only once for each task } return 0; } 从map中移除task,然后执行了task自己的onTaskEnd。这样我们正最初的updateConversationTopics里就可以看到后续的更新ui的代码。 下面我们要回到updateConversationTopics附近,看看NanoMarsTaskWrapper: public abstract class NanoMarsTaskWrapper<T extends MessageNano, R extends MessageNano> extends AbstractTaskWrapper { private static final String TAG = "Mars.Sample.NanoMarsTaskWrapper"; protected T request; protected R response; public NanoMarsTaskWrapper(T req, R resp) { super(); this.request = req; this.response = resp; } @Override public byte[] req2buf() { try { onPreEncode(request); final byte[] flatArray = new byte[request.getSerializedSize()]; final CodedOutputByteBufferNano output = CodedOutputByteBufferNano.newInstance(flatArray); request.writeTo(output); Log.d(TAG, "encoded request to buffer, [%s]", MemoryDump.dumpHex(flatArray)); return flatArray; } catch (Exception e) { e.printStackTrace(); } return new byte[0]; } @Override public int buf2resp(byte[] buf) { try { Log.d(TAG, "decode response buffer, [%s]", MemoryDump.dumpHex(buf)); response = MessageNano.mergeFrom(response, buf); onPostDecode(response); return StnLogic.RESP_FAIL_HANDLE_NORMAL; } catch (Exception e) { Log.e(TAG, "%s", e); } return StnLogic.RESP_FAIL_HANDLE_TASK_END; } public abstract void onPreEncode(T request); public abstract void onPostDecode(R response); } 1.从AbstractTaskWrapper继承下来; 2.保存了request和response,都是MessageNano类型的(google的protobuf内的message数据类); 3.实现了2个接口,分别用来作为request转换为buf何buf转换成为response。其实就是对象转成byte[],byte转成对象; 3.在req2buf转换的过程中,调用了request的writeTo方法; 4.在buf2resp中,调用了MessageNano.mergeFrom,实际上最终也是调用了response的mergeFrom,见下: /** * Parse {@code data} as a message of this type and merge it with the * message being built. */ public static final <T extends MessageNano> T mergeFrom(T msg, final byte[] data) throws InvalidProtocolBufferNanoException { return mergeFrom(msg, data, 0, data.length); } 根据上面的4点可以看到这是个实现序列化及反序列化的过程。google的开源protobuf我们不去关注,但是需要了解的是他是通过以proto为后缀名的配置文件来达到编译时即可生成类的相关代码的程度。 那么这个AbstractTaskWrapper的基类的作用又是什么呢? public abstract class AbstractTaskWrapper extends MarsTaskWrapper.Stub { private Bundle properties = new Bundle(); public AbstractTaskWrapper() { // Reflects task properties final TaskProperty taskProperty = this.getClass().getAnnotation(TaskProperty.class); if (taskProperty != null) { setHttpRequest(taskProperty.host(), taskProperty.path()); setShortChannelSupport(taskProperty.shortChannelSupport()); setLongChannelSupport(taskProperty.longChannelSupport()); setCmdID(taskProperty.cmdID()); } } @Override public Bundle getProperties() { return properties; } @Override public abstract void onTaskEnd(int errType, int errCode); public AbstractTaskWrapper setHttpRequest(String host, String path) { properties.putString(MarsTaskProperty.OPTIONS_HOST, ("".equals(host) ? null : host)); properties.putString(MarsTaskProperty.OPTIONS_CGI_PATH, path); return this; } public AbstractTaskWrapper setShortChannelSupport(boolean support) { properties.putBoolean(MarsTaskProperty.OPTIONS_CHANNEL_SHORT_SUPPORT, support); return this; } public AbstractTaskWrapper setLongChannelSupport(boolean support) { properties.putBoolean(MarsTaskProperty.OPTIONS_CHANNEL_LONG_SUPPORT, support); return this; } public AbstractTaskWrapper setCmdID(int cmdID) { properties.putInt(MarsTaskProperty.OPTIONS_CMD_ID, cmdID); return this; } @Override public String toString() { return "AbsMarsTask: " + BundleFormat.toString(properties); } } 很简单,就是提供了一些接口来设置传输协议类型,长短连接、http等。 综合来说,这个demo使用了独立的服务框架来进行传输的保证;使用了任务体系来承载每次传输及响应;大量的回调来监控运转过程中的各项关键点;封装了独立的jar wrapper,便于上层的更改及使用;独立的配置类引入支持http和tcp长短连接的使用;protobuf的引入极大提升序列化及反序列化的效率,并降低传输的数据大小; 这篇暂时就到这里吧,后面我们会深入分析下mars的核心部分。 阅读 7.4k 63 声望 26 粉丝 0 条评论 你知道吗? 63 声望 26 粉丝 宣传栏
__label__pos
0.978248
  Show Menu TOPICS× Calendar events Steps to add calendar events, and to manage shared events. To ensure optimal reporting performance, the 20 most recent calendar events will be displayed on trended and overtime graphs. For reports trended over time, you can graphically display events and see whether campaigns or other events have affected your site traffic, revenue, or any other metric. The process of setting up a calendar event involves naming the event, setting the dates, adding notes, and setting an icon. For example, if you use Social, you can create a calendar event to show that there was a correlation between an increase in site traffic and the mention of a product by a celebrity using Twitter. 1. Click Analytics > Components > Calendar Events . 2. Click Add New . 1. Under Title , name the calendar event. 2. Specify the Event Date . 3. Choose the Report Suite to which this event applies. 4. (Optional) Add any Note Text for this event. 5. Select a display icon and color. 6. Click Save . 3. (Optional) Calendar events are user specific unless shared. To share this event, select Share . 4. (Optional) Push the calendar event to users. Calendar Events that have been marked as Shared now have an option to be "pushed" to other users. Pushing a Calendar Event will cause it to show up on the recipient users' trended and overtime graphs. 1. Click Push To Users . 2. **Check All**or check the box next to the user name/s. 3. Click Save . This makes Calendar Events much more usable. Analysts now have the ability to force an overlay onto their users' reports to provide more context. 5. Click Analytics > Components > Calendar Events . 6. Under Shared Calendar Events , specify one of these options: | **Copy Me** | Adds a copy to your list of events, using the same name as the original. However, you cannot see any updates/changes made by the event's owner. | |---|---| | **On Report** | Lets you see changes/updates made by the event owner. | | **Unshare** | Removes this event from your list of shared events. |
__label__pos
0.934867
Answers Solutions by everydaycalculation.com Answers.everydaycalculation.com » Multiply fractions Multiply 75/60 with 20/84 1st number: 1 15/60, 2nd number: 20/84 This multiplication involving fractions can also be rephrased as "What is 75/60 of 20/84?" 75/60 × 20/84 is 25/84. Steps for multiplying fractions 1. Simply multiply the numerators and denominators separately: 2. 75/60 × 20/84 = 75 × 20/60 × 84 = 1500/5040 3. After reducing the fraction, the answer is 25/84 MathStep (Works offline) Download our mobile app and learn to work with fractions in your own time: Android and iPhone/ iPad Related: © everydaycalculation.com
__label__pos
0.624566
Jump to: navigation, search Difference between revisions of "Platform Command Framework" (Contexts) (Other Resources) (18 intermediate revisions by 8 users not shown) Line 4: Line 4:      <center>Figure 1: High Level Architecture</center>   <center>Figure 1: High Level Architecture</center>  +  + = Eclipse Commands Tutorial =  +  + http://www.vogella.de/articles/EclipseCommands/article.html Tutorial about using Eclipse Commands by Lars Vogel  +  + = Other Resources =  + [http://blog.eclipse-tips.com/search/label/Commands Commands in Action] by [http://blog.eclipse-tips.com/ Prakash G.R.]:  +  + * [http://blog.eclipse-tips.com/2009/01/commands-part-1-actions-vs-commands.html Commands Part 1: Actions Vs Commands]  + * [http://blog.eclipse-tips.com/2009/01/commands-part-2-selection-and.html Commands Part 2: Selection and Enablement of IHandlers]  + * [http://blog.eclipse-tips.com/2008/12/commands-part-3-parameters-for-commands.html Commands Part 3: Parameters for Commands]  + * [http://blog.eclipse-tips.com/2009/01/commands-part-4-misc-items.html Commands Part 4: Misc items ...]  + * [http://blog.eclipse-tips.com/2009/02/commands-part-5-authentication-in-rcp.html Commands Part 5: Authentication in RCP applications]  + * [http://blog.eclipse-tips.com/2009/03/commands-part-6-toggle-radio-menu.html Commands Part 6: Toggle & Radio menu contributions]  + * [http://blog.eclipse-tips.com/2009/05/commands-part-7-adding-standard.html Commands Part 7: Adding standard commands]  + * [http://blog.eclipse-tips.com/2009/06/keyboard-accessibility-thru-command.html Keyboard accessibility thru Command Framework]  + * [http://blog.eclipse-tips.com/2009/12/toggle-commands-toggle-other.html Toggle Commands the toggle other contributions]  +  + [http://wiki.eclipse.org/Command_Core_Expressions Command Core Expressions]  +  + [http://wiki.eclipse.org/Platform_Expression_Framework Platform Expression Framework]      = Commands =   = Commands = Line 11: Line 32:   An example of using the extension point to create a command:   An example of using the extension point to create a command:    <extension + <source lang="xml">  + <extension          point="org.eclipse.ui.commands">          point="org.eclipse.ui.commands">        <category        <category Line 24: Line 46:              name="Eat That Taco">              name="Eat That Taco">        </command>        </command> </extension> + </extension>  + </source>      You can programmatically create commands as well.  From within a view:   You can programmatically create commands as well.  From within a view:    ICommandService cmdService = (ICommandService) getSite().getService( + <source lang="java">     ICommandService.class); +   Category lunch = cmdService + ICommandService cmdService = (ICommandService) getSite().getService(     .getCategory("z.ex.view.keybindings.category"); +     ICommandService.class); if (!lunch.isDefined()) { + Category lunch = cmdService   lunch.define("Lunch", "Actions take at lunch time."); +     .getCategory("z.ex.view.keybindings.category"); } + if (!lunch.isDefined()) { Command eatTaco = cmdService +   lunch.define("Lunch", "Actions take at lunch time.");     .getCommand("z.ex.view.keybindings.eatTaco"); + } if (!eatTaco.isDefined()) { + Command eatTaco = cmdService   eatTaco.define("Eat That Taco", "Go for the taco.", lunch); +     .getCommand("z.ex.view.keybindings.eatTaco"); } + if (!eatTaco.isDefined()) {  +   eatTaco.define("Eat That Taco", "Go for the taco.", lunch);  + }  + </source>      Note, however, that a plugin that programmatically defines commands is responsible for cleaning them up if the plugin is ever unloaded.   Note, however, that a plugin that programmatically defines commands is responsible for cleaning them up if the plugin is ever unloaded. Line 50: Line 76:   When a Command specifies its parameters, it can also specify a parameter type and/or some valid values.  For example, the showView command.   When a Command specifies its parameters, it can also specify a parameter type and/or some valid values.  For example, the showView command.      <command + <source lang="xml">  + <command          name="%command.showView.name"          name="%command.showView.name"          description="%command.showView.description"          description="%command.showView.description" Line 60: Line 87:            name="%command.showView.viewIdParameter"            name="%command.showView.viewIdParameter"            values="org.eclipse.ui.internal.registry.ViewParameterValues" />            values="org.eclipse.ui.internal.registry.ViewParameterValues" />   </command> + </command>  + </source>      To execute this command, you need to create a ParameterizedCommand with a Parameterization (an instance of a parameter and its value).   To execute this command, you need to create a ParameterizedCommand with a Parameterization (an instance of a parameter and its value).     + <source lang="java">     ICommandService commandService = ...;     ICommandService commandService = ...;     IHandlerService handlerService = ...;     IHandlerService handlerService = ...; Line 91: Line 120:                 handlerService.executeCommand(parmCommand, null);     handlerService.executeCommand(parmCommand, null);   + </source>      This executes the showView command with the problem view id.  This is done for us when declaratively specifying a keybinding.   This executes the showView command with the problem view id.  This is done for us when declaratively specifying a keybinding.      <key + <source lang="xml">  + <key          sequence="M2+M3+Q X"          sequence="M2+M3+Q X"          contextId="org.eclipse.ui.contexts.window"          contextId="org.eclipse.ui.contexts.window" Line 103: Line 133:            id="org.eclipse.ui.views.showView.viewId"            id="org.eclipse.ui.views.showView.viewId"            value="org.eclipse.ui.views.ProblemView" />            value="org.eclipse.ui.views.ProblemView" />   </key> + </key>  + </source>      == Using an IActionDelegate to execute a command ==   == Using an IActionDelegate to execute a command == Line 117: Line 148:   For example, in the above section we saw the showView command takes one parameter, the view id.  Here is how we create an Action  to execute it:   For example, in the above section we saw the showView command takes one parameter, the view id.  Here is how we create an Action  to execute it:            <action + <source lang="xml">               id="org.eclipse.ui.examples.actions.showOutlineView" + <action               label="Show View:Outline" +   id="org.eclipse.ui.examples.actions.showOutlineView"               menubarPath="org.eclipse.ui.examples.actions.showViewMenu/additions" +   label="Show View:Outline"               style="push"> +   menubarPath="org.eclipse.ui.examples.actions.showViewMenu/additions"             <class class="org.eclipse.ui.tests.api.GenericCommandActionDelegate"> +   style="push">               <parameter name="commandId"   +   <class class="org.eclipse.ui.tests.api.GenericCommandActionDelegate">  +     <parameter name="commandId"                                value="org.eclipse.ui.views.showView"/>                              value="org.eclipse.ui.views.showView"/>               <parameter name="org.eclipse.ui.views.showView.viewId"   +     <parameter name="org.eclipse.ui.views.showView.viewId"                                value="org.eclipse.ui.views.ContentOutline"/>                              value="org.eclipse.ui.views.ContentOutline"/>             </class> +   </class>         </action> + </action>         <action + <action               id="org.eclipse.ui.examples.actions.showBookmarkView" +   id="org.eclipse.ui.examples.actions.showBookmarkView"               label="Show View:Bookmark" +   label="Show View:Bookmark"               menubarPath="org.eclipse.ui.examples.actions.showViewMenu/additions" +   menubarPath="org.eclipse.ui.examples.actions.showViewMenu/additions"               style="push"> +   style="push">             <class class="org.eclipse.ui.tests.api.GenericCommandActionDelegate"> +   <class class="org.eclipse.ui.tests.api.GenericCommandActionDelegate">               <parameter name="commandId"   +       <parameter name="commandId"                                value="org.eclipse.ui.views.showView"/>                              value="org.eclipse.ui.views.showView"/>               <parameter name="org.eclipse.ui.views.showView.viewId"   +       <parameter name="org.eclipse.ui.views.showView.viewId"                                value="org.eclipse.ui.views.BookmarkView"/>                              value="org.eclipse.ui.views.BookmarkView"/>             </class> +   </class>         </action> + </action>  + </source>      '''Notes:'''   '''Notes:''' Line 164: Line 197:        + <source lang="java">     /*******************************************************************************     /*******************************************************************************      * Copyright (c) 2006 IBM Corporation and others.      * Copyright (c) 2006 IBM Corporation and others. Line 319: Line 353:                }                }                ArrayList parameters = new ArrayList();                ArrayList parameters = new ArrayList();              Iterator i = parameterMap.keySet().iterator(); +              Iterator i = parameterMap.entrySet().iterator();                while (i.hasNext()) {                while (i.hasNext()) {                  String parmName = (String) i.next(); +                 Map.Entry entry = (Map.Entry) i.next();  +                  String parmName = (String) entry.getKey();                    if (PARM_COMMAND_ID.equals(parmName)) {                    if (PARM_COMMAND_ID.equals(parmName)) {                        continue;                        continue; Line 330: Line 365:                        return;                        return;                    }                    }                  parameters.add(new Parameterization(parm, (String) parameterMap +                  parameters.add(new Parameterization(parm, (String) entry.getValue()));                         .get(parmName))); +                }                }                parameterizedCommand = new ParameterizedCommand(cmd,                parameterizedCommand = new ParameterizedCommand(cmd, Line 400: Line 434:        }        }     }     }  + </source>      = Handlers =   = Handlers =    Handlers are managed by the <b>org.eclipse.ui.handlers</b> extension point and the IHandlerService.  Many Handlers can register for a command.  At any give time, either 0 or 1 handlers will be active for the command.  A handler's active state and enabled state can be controlled declaratively. + Handlers are managed by the <b>org.eclipse.ui.handlers</b> extension point and the IHandlerService.  Many Handlers can register for a command.  At any give time, either 0 or 1 handlers will be active for the command.  A handler's active state and enabled state can be controlled declaratively.  See [[Command Core Expressions]] for a more complex description of the declarative expressions. Handlers are responsible for interpreting any optional command parameters using the ExecutionEvent parameter.    <extension + <source lang="xml">  + <extension          point="org.eclipse.ui.handlers">          point="org.eclipse.ui.handlers">        <handler        <handler Line 418: Line 454:          </activeWhen>          </activeWhen>        </handler>        </handler> </extension> + </extension>  + </source>      Here the handler is checking the activeContexts variable (See [http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/ISources.html org.eclipse.ui.ISources]) and if the "taco" context is active, the handler is active.   Here the handler is checking the activeContexts variable (See [http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/ui/ISources.html org.eclipse.ui.ISources]) and if the "taco" context is active, the handler is active. Line 426: Line 463:   You can create and activate a handler programmatically:   You can create and activate a handler programmatically:    IHandlerService handlerService = (IHandlerService) getSite() + <source lang="java">     .getService(IHandlerService.class); + IHandlerService handlerService = (IHandlerService) getSite() IHandler handler = new AbstractHandler() { +     .getService(IHandlerService.class);   public Object execute(ExecutionEvent event) + IHandler handler = new AbstractHandler() {           throws ExecutionException { +   public Object execute(ExecutionEvent event)     System.out.println("Eat that Taco"); +           throws ExecutionException {     return null; +     System.out.println("Eat that Taco");   } +     return null; }; +   } handlerService + };     .activateHandler("z.ex.view.keybindings.eatTaco", handler); + handlerService  +     .activateHandler("z.ex.view.keybindings.eatTaco", handler);  + </source>     + As of 3.2 (and later releases) we should be calling the IHandlerService to run commands. We should not call the Command object execute method itself.    In 3.2 to run commands we should be calling the IHandlerService, not the Command object execute method itself. + <source lang="java">   +     handlerService.executeCommand("z.ex.view.keybindings.eatTaco", null);     handlerService.executeCommand("z.ex.view.keybindings.eatTaco", null);  + </source>  +  + In 3.1 it is still necessary to call the Command object directly since the IHandlerService didn't support executeCommand(*). But you can provide almost the same execution environment.  +  + <source lang="java">  + Command eatTaco = cmdService  +   .getCommand("z.ex.view.keybindings.eatTaco");  + eatTaco.execute(new ExecutionEvent(Collections.EMPTY_MAP, null, handlerService.getCurrentState()));  + </source>    In 3.1 the IHandlerService didn't support executeCommand(*), but you can provide almost the same execution environment. + If you want the handler to evaluate an enablement expression you can do that using the expression parameter of the  + activateHandler() method. Here is how you need to setup your expression in order to properly work tracking  + selection changes:    Command eatTaco = cmdService + <source lang="java">     .getCommand("z.ex.view.keybindings.eatTaco"); + Expression expr = new Expression() { eatTaco.execute(new ExecutionEvent(Collections.EMPTY_MAP, null, handlerService.getCurrentState())); +     public final EvaluationResult evaluate(final IEvaluationContext context) {  +         Object sel = context.getVariable(ISources.ACTIVE_CURRENT_SELECTION_NAME);  +         (return EvaluationResult.TRUE/FALSE depending on how much you like the selection)  +     }  +     public void collectExpressionInfo(final ExpressionInfo info) {  +         // You need this to cause the expr to be evaluated on selection events  +         info.markDefaultVariableAccessed();  +     }  + };  + </source>      = KeyBindings =   = KeyBindings = Line 453: Line 512:   KeyBindings are managed by the <b>org.eclipse.ui.bindings</b> extension point and the IBindingService.  Keybindings cannot be updated programmatically.   KeyBindings are managed by the <b>org.eclipse.ui.bindings</b> extension point and the IBindingService.  Keybindings cannot be updated programmatically.    <extension + <source lang="xml">  + <extension          point="org.eclipse.ui.bindings">          point="org.eclipse.ui.bindings">        <key        <key Line 461: Line 521:              sequence="CTRL+3">              sequence="CTRL+3">        </key>        </key> </extension> + </extension>  + </source>    A key binding is active when the context is active. + A key binding is active when the context is active. A keybinding is associated with a command (with optional parameters specified by parameter id and value). If a command has a handler while the keybinding is invoked, the handler extracts the command parameters specified by the keybinding from the ExecutionEvent and invokes the appropriate action.      = Contexts =   = Contexts = Line 471: Line 532:   Most contexts are created by the extension point, and activated programmatically when appropriate.  But you can create contexts programmatically as well.  The active contexts usually form a tree, although in the case of keybindings this tree is narrowed down to a branch.   Most contexts are created by the extension point, and activated programmatically when appropriate.  But you can create contexts programmatically as well.  The active contexts usually form a tree, although in the case of keybindings this tree is narrowed down to a branch.    <extension + <source lang="xml">  + <extension          point="org.eclipse.ui.contexts">          point="org.eclipse.ui.contexts">        <context        <context Line 479: Line 541:              parentId="org.eclipse.ui.contexts.window">              parentId="org.eclipse.ui.contexts.window">        </context>        </context> </extension> + </extension>  + </source>      For a context that was attached to a view, it would normally be activated in the view's createPartControl(*) method.   For a context that was attached to a view, it would normally be activated in the view's createPartControl(*) method.    IContextService contextService = (IContextService) getSite() + <source lang="java">   .getService(IContextService.class); + IContextService contextService = (IContextService) getSite() IContextActivation contextActivation = contextService.activateContext("z.ex.view.keybindings.contexts.taco"); +   .getService(IContextService.class);  + IContextActivation contextActivation = contextService.activateContext("z.ex.view.keybindings.contexts.taco");  + </source>      You can only de-activate a context that you are responsible for activating.   You can only de-activate a context that you are responsible for activating. Line 491: Line 556:   Programmatically, you can create contexts:   Programmatically, you can create contexts:    Context tacos = contextService + <source lang="java">     .getContext("z.ex.view.keybindings.contexts.taco"); + Context tacos = contextService if (!tacos.isDefined()) { +     .getContext("z.ex.view.keybindings.contexts.taco");   tacos.define("Mexican Food", "To allow the consumption of Tacos", + if (!tacos.isDefined()) {       "org.eclipse.ui.contexts.window"); +   tacos.define("Mexican Food", "To allow the consumption of Tacos", } +       "org.eclipse.ui.contexts.window");  + }  + </source>      Note, however, that a plugin that programmatically defines contexts is responsible for cleaning them up if the plugin is ever unloaded.   Note, however, that a plugin that programmatically defines contexts is responsible for cleaning them up if the plugin is ever unloaded. Line 528: Line 595:      I put these options in a <b>debug.options</b> file and run eclipse using:   I put these options in a <b>debug.options</b> file and run eclipse using:   + <source lang="bash"> bash$ eclipse -debug debug.options -data /opt/local/pw_workspace >debug.log 2>&1 + bash$ eclipse -debug debug.options -data /opt/local/pw_workspace >debug.log 2>&1   + </source>   This logs the debug output to the debug.log file.  This works on windows as well:   This logs the debug output to the debug.log file.  This works on windows as well:  + <source lang="dos">  + C:\development> eclipse33\eclipsec.exe -debug debug.options -data workspaces\pw_workspace >debug.log 2>&1  + </source>  + <b>handlers.verbose.commandId</b> allows you to track the information about a specific command that isn't working.  org.eclipse.jdt.ui.navigate.open.type is the open type dialog (normally CTRL+SHIFT+T) and org.eclipse.ui.edit.copy (commented out) is COPY (normally CTRL+C)    C:\development> eclipse32\eclipse.exe -debug debug.options -data workspaces\pw_workspace >debug.log 2>&1      <b>handlers.verbose.commandId</b> allows you to track the information about a specific command that isn't working.  org.eclipse.jdt.ui.navigate.open.type is the open type dialog (normally CTRL+SHIFT+T) and org.eclipse.ui.edit.copy (commented out) is COPY (normally CTRL+C) + [[Category:Eclipse Project]] Revision as of 11:31, 31 January 2012 Architecture Overview http://dev.eclipse.org/viewcvs/index.cgi/~checkout~/platform-ui-home/R3_1/contributions-proposal/requestForComments_html_m41374bdb.png Figure 1: High Level Architecture Eclipse Commands Tutorial http://www.vogella.de/articles/EclipseCommands/article.html Tutorial about using Eclipse Commands by Lars Vogel Other Resources Commands in Action by Prakash G.R.: Command Core Expressions Platform Expression Framework Commands Commands are managed by the org.eclipse.ui.commands extension point and the ICommandService. An example of using the extension point to create a command: <extension point="org.eclipse.ui.commands"> <category description="Actions take at lunch time." id="z.ex.view.keybindings.category" name="Lunch"> </category> <command categoryId="z.ex.view.keybindings.category" description="Go for the taco." id="z.ex.view.keybindings.eatTaco" name="Eat That Taco"> </command> </extension> You can programmatically create commands as well. From within a view: ICommandService cmdService = (ICommandService) getSite().getService( ICommandService.class); Category lunch = cmdService .getCategory("z.ex.view.keybindings.category"); if (!lunch.isDefined()) { lunch.define("Lunch", "Actions take at lunch time."); } Command eatTaco = cmdService .getCommand("z.ex.view.keybindings.eatTaco"); if (!eatTaco.isDefined()) { eatTaco.define("Eat That Taco", "Go for the taco.", lunch); } Note, however, that a plugin that programmatically defines commands is responsible for cleaning them up if the plugin is ever unloaded. Also, like IAction you can execute a command directly ... but to get the proper environment it's better to execute it through the IHandlerService. See #Handlers. Executing a command with parameters When a Command specifies its parameters, it can also specify a parameter type and/or some valid values. For example, the showView command. <command name="%command.showView.name" description="%command.showView.description" categoryId="org.eclipse.ui.category.views" id="org.eclipse.ui.views.showView" defaultHandler="org.eclipse.ui.handlers.ShowViewHandler"> <commandParameter id="org.eclipse.ui.views.showView.viewId" name="%command.showView.viewIdParameter" values="org.eclipse.ui.internal.registry.ViewParameterValues" /> </command> To execute this command, you need to create a ParameterizedCommand with a Parameterization (an instance of a parameter and its value). ICommandService commandService = ...; IHandlerService handlerService = ...; Command showView = commandService .getCommand("org.eclipse.ui.views.showView"); IParameter viewIdParm = showView .getParameter("org.eclipse.ui.views.showView.viewId");   // the viewId parameter provides a list of valid values ... if you // knew the id of the problem view, you could skip this step. // This method is supposed to be used in places like the keys // preference page, to allow the user to select values IParameterValues parmValues = viewIdParm.getValues(); String viewId = null; Iterator i = parmValues.getParameterValues().values().iterator(); while (i.hasNext()) { String id = (String) i.next(); if (id.indexOf("ProblemView") != -1) { viewId = id; break; } }   Parameterization parm = new Parameterization(viewIdParm, viewId); ParameterizedCommand parmCommand = new ParameterizedCommand( showView, new Parameterization[] { parm });   handlerService.executeCommand(parmCommand, null); This executes the showView command with the problem view id. This is done for us when declaratively specifying a keybinding. <key sequence="M2+M3+Q X" contextId="org.eclipse.ui.contexts.window" commandId="org.eclipse.ui.views.showView" schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"> <parameter id="org.eclipse.ui.views.showView.viewId" value="org.eclipse.ui.views.ProblemView" /> </key> Using an IActionDelegate to execute a command In 3.1 and 3.2 there is no declarative support for a menu item to execute a command. But you can write an IActionDelegate (like GenericCommandActionDelegate) that can be used in the standard extension points (org.eclipse.ui.actionSets, org.eclipse.ui.popupMenus, org.eclipse.ui.editorActions, and org.eclipse.ui.viewActions) and use it to execute the command. We need to do these things to wire our command to a menu item: 1. Define an action in an extension point using plugin.xml markup 2. Connect this action to our IActionDelegate instance (also in plugin.xml) 3. Tell our IActionDelegate which command to execute (also in plugin.xml) 4. Code the IActionDelegate class to perform the command execution. (see code example below). For example, in the above section we saw the showView command takes one parameter, the view id. Here is how we create an Action to execute it: <action id="org.eclipse.ui.examples.actions.showOutlineView" label="Show View:Outline" menubarPath="org.eclipse.ui.examples.actions.showViewMenu/additions" style="push"> <class class="org.eclipse.ui.tests.api.GenericCommandActionDelegate"> <parameter name="commandId" value="org.eclipse.ui.views.showView"/> <parameter name="org.eclipse.ui.views.showView.viewId" value="org.eclipse.ui.views.ContentOutline"/> </class> </action> <action id="org.eclipse.ui.examples.actions.showBookmarkView" label="Show View:Bookmark" menubarPath="org.eclipse.ui.examples.actions.showViewMenu/additions" style="push"> <class class="org.eclipse.ui.tests.api.GenericCommandActionDelegate"> <parameter name="commandId" value="org.eclipse.ui.views.showView"/> <parameter name="org.eclipse.ui.views.showView.viewId" value="org.eclipse.ui.views.BookmarkView"/> </class> </action> Notes: • For commands without parameters, you can use the class attribute short from: class="org.eclipse.ui.tests.api.GenericCommandActionDelegate:my.commandId" • your action definition looks more like a keybinding definition. You are specifying the command id and any parameters needed for that action. • We specifed the action using the <class/> element instead of the class attribute ... you'll get a couple of warnings, ignore them. • The definitionId that is currently in the <action/> element is for linking up legacy actions to a keybinding through a command. For example, you've had a ShowMyViewActionDelegate since 3.0, and you want to attach a keybinding to it. We don't want to use that. • We have just shown the plugin.xml markup to trigger a command from within an action. Since the action can be inserted into a menu, this approach allows commands to be triggered by menu items. The glue between actions and commands is a single generic IActionDelegate implementation (shown below). All of the specific behavior code is now unified in the command and its handler. We no longer need an action delegate with a specific run() method for every menu item; consequently we don't need to link ActionSets to commands with the definitionId. Known Issues: When you start up eclipse you'll get warnings about your actions not having a class attribute. It's not an error, and won't effect the action performance. You'll also see the actions in the Uncategorized section of the keybindings page. You can bind keys to them but they won't work from the keybinding. That's OK, you should be binding keys to the command not the action. Generic Command Action Delegate We'll need a more robust implementation, but in 3.2 your action delegate needs to look something like the class below. I've only tested this with org.eclipse.ui.actionSets, but it should work with the viewActions, editorActions, and popupMenus extension points as well. The latest version of the code lives in HEAD in the org.eclipse.ui.tests plugin: GenericCommandActionDelegate.java /******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.ui.tests.api;   import java.util.ArrayList; import java.util.Iterator; import java.util.Map;   import org.eclipse.core.commands.Command; import org.eclipse.core.commands.IParameter; import org.eclipse.core.commands.Parameterization; import org.eclipse.core.commands.ParameterizedCommand; import org.eclipse.core.commands.common.NotDefinedException; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExecutableExtension; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.handlers.IHandlerService;   /** * This action delegate can be used to specify a command with or without * parameters be called from an &lt;action/&gt; specified in actionSets, * editorActions, viewActions, or popupMenus. */ public class GenericCommandActionDelegate implements IWorkbenchWindowActionDelegate, IViewActionDelegate, IEditorActionDelegate, IObjectActionDelegate, IExecutableExtension {   private static final String PARM_COMMAND_ID = "commandId";   private String commandId = null;   private Map parameterMap = null;   private ParameterizedCommand parameterizedCommand = null;   private IHandlerService handlerService = null;   /* * (non-Javadoc) * * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose() */ public void dispose() { handlerService = null; parameterizedCommand = null; parameterMap = null; }   /* * (non-Javadoc) * * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */ public void run(IAction action) { if (handlerService == null) { // what, no handler service ... no problem return; } try { if (commandId != null) { handlerService.executeCommand(commandId, null); } else if (parameterizedCommand != null) { handlerService.executeCommand(parameterizedCommand, null); } // else there is no command for this delegate } catch (Exception e) { // exceptions reduced for brevity // and we won't just do a print out :-) } }   /* * (non-Javadoc) * * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, * org.eclipse.jface.viewers.ISelection) */ public void selectionChanged(IAction action, ISelection selection) { // we don't care, handlers get their selection from the // ExecutionEvent application context }   /* * (non-Javadoc) * * @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement, * java.lang.String, java.lang.Object) */ public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException { String id = config.getAttribute(IWorkbenchRegistryConstants.ATT_ID); // save the data until our init(*) call, where we can get // the services. if (data instanceof String) { commandId = (String) data; } else if (data instanceof Map) { parameterMap = (Map) data; if (parameterMap.get(PARM_COMMAND_ID) == null) { Status status = new Status(IStatus.ERROR, "org.eclipse.ui.tests", "The '" + id + "' action won't work without a commandId"); throw new CoreException(status); } } else { Status status = new Status( IStatus.ERROR, "org.eclipse.ui.tests", "The '" + id + "' action won't work without some initialization parameters"); throw new CoreException(status); } }   /** * Build a command from the executable extension information. * * @param commandService * to get the Command object */ private void createCommand(ICommandService commandService) { String id = (String) parameterMap.get(PARM_COMMAND_ID); if (id == null) { return; } if (parameterMap.size() == 1) { commandId = id; return; } try { Command cmd = commandService.getCommand(id); if (!cmd.isDefined()) { // command not defined? no problem ... return; } ArrayList parameters = new ArrayList(); Iterator i = parameterMap.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String parmName = (String) entry.getKey(); if (PARM_COMMAND_ID.equals(parmName)) { continue; } IParameter parm = cmd.getParameter(parmName); if (parm == null) { // asking for a bogus parameter? No problem return; } parameters.add(new Parameterization(parm, (String) entry.getValue())); } parameterizedCommand = new ParameterizedCommand(cmd, (Parameterization[]) parameters .toArray(new Parameterization[parameters.size()])); } catch (NotDefinedException e) { // command is bogus? No problem, we'll do nothing. } }   /* * (non-Javadoc) * * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow) */ public void init(IWorkbenchWindow window) { if (handlerService != null) { // already initialized return; }   handlerService = (IHandlerService) window .getService(IHandlerService.class); if (parameterMap != null) { ICommandService commandService = (ICommandService) window .getService(ICommandService.class); createCommand(commandService); } }   /* * (non-Javadoc) * * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart) */ public void init(IViewPart view) { init(view.getSite().getWorkbenchWindow()); }   /* * (non-Javadoc) * * @see org.eclipse.ui.IEditorActionDelegate#setActiveEditor(org.eclipse.jface.action.IAction, * org.eclipse.ui.IEditorPart) */ public void setActiveEditor(IAction action, IEditorPart targetEditor) { // we don't actually care about the active editor, since that // information is in the ExecutionEvent application context // but we need to make sure we're initialized. if (targetEditor != null) { init(targetEditor.getSite().getWorkbenchWindow()); } }   /* * (non-Javadoc) * * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction, * org.eclipse.ui.IWorkbenchPart) */ public void setActivePart(IAction action, IWorkbenchPart targetPart) { // we don't actually care about the active part, since that // information is in the ExecutionEvent application context // but we need to make sure we're initialized. if (targetPart != null) { init(targetPart.getSite().getWorkbenchWindow()); } } } Handlers Handlers are managed by the org.eclipse.ui.handlers extension point and the IHandlerService. Many Handlers can register for a command. At any give time, either 0 or 1 handlers will be active for the command. A handler's active state and enabled state can be controlled declaratively. See Command Core Expressions for a more complex description of the declarative expressions. Handlers are responsible for interpreting any optional command parameters using the ExecutionEvent parameter. <extension point="org.eclipse.ui.handlers"> <handler class="z.ex.view.keybindings.handlers.TacoHandler" commandId="z.ex.view.keybindings.eatTaco"> <activeWhen> <with variable="activeContexts"> <iterate operator="or"> <equals value="z.ex.view.keybindings.contexts.taco"/> </iterate> </with> </activeWhen> </handler> </extension> Here the handler is checking the activeContexts variable (See org.eclipse.ui.ISources) and if the "taco" context is active, the handler is active. The handler itself, TacoHandler, must implement IHandler but would usually be derived from the abstract base class org.eclipse.core.commands.AbstractHandler. You can create and activate a handler programmatically: IHandlerService handlerService = (IHandlerService) getSite() .getService(IHandlerService.class); IHandler handler = new AbstractHandler() { public Object execute(ExecutionEvent event) throws ExecutionException { System.out.println("Eat that Taco"); return null; } }; handlerService .activateHandler("z.ex.view.keybindings.eatTaco", handler); As of 3.2 (and later releases) we should be calling the IHandlerService to run commands. We should not call the Command object execute method itself. handlerService.executeCommand("z.ex.view.keybindings.eatTaco", null); In 3.1 it is still necessary to call the Command object directly since the IHandlerService didn't support executeCommand(*). But you can provide almost the same execution environment. Command eatTaco = cmdService .getCommand("z.ex.view.keybindings.eatTaco"); eatTaco.execute(new ExecutionEvent(Collections.EMPTY_MAP, null, handlerService.getCurrentState())); If you want the handler to evaluate an enablement expression you can do that using the expression parameter of the activateHandler() method. Here is how you need to setup your expression in order to properly work tracking selection changes: Expression expr = new Expression() { public final EvaluationResult evaluate(final IEvaluationContext context) { Object sel = context.getVariable(ISources.ACTIVE_CURRENT_SELECTION_NAME); (return EvaluationResult.TRUE/FALSE depending on how much you like the selection) } public void collectExpressionInfo(final ExpressionInfo info) { // You need this to cause the expr to be evaluated on selection events info.markDefaultVariableAccessed(); } }; KeyBindings KeyBindings are managed by the org.eclipse.ui.bindings extension point and the IBindingService. Keybindings cannot be updated programmatically. <extension point="org.eclipse.ui.bindings"> <key commandId="z.ex.view.keybindings.eatTaco" contextId="z.ex.view.keybindings.contexts.taco" schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" sequence="CTRL+3"> </key> </extension> A key binding is active when the context is active. A keybinding is associated with a command (with optional parameters specified by parameter id and value). If a command has a handler while the keybinding is invoked, the handler extracts the command parameters specified by the keybinding from the ExecutionEvent and invokes the appropriate action. Contexts Contexts are managed by the org.eclipse.ui.contexts extension point and the IContextService. Most contexts are created by the extension point, and activated programmatically when appropriate. But you can create contexts programmatically as well. The active contexts usually form a tree, although in the case of keybindings this tree is narrowed down to a branch. <extension point="org.eclipse.ui.contexts"> <context description="To allow the consumption of Tacos" id="z.ex.view.keybindings.contexts.taco" name="Mexican Food" parentId="org.eclipse.ui.contexts.window"> </context> </extension> For a context that was attached to a view, it would normally be activated in the view's createPartControl(*) method. IContextService contextService = (IContextService) getSite() .getService(IContextService.class); IContextActivation contextActivation = contextService.activateContext("z.ex.view.keybindings.contexts.taco"); You can only de-activate a context that you are responsible for activating. Programmatically, you can create contexts: Context tacos = contextService .getContext("z.ex.view.keybindings.contexts.taco"); if (!tacos.isDefined()) { tacos.define("Mexican Food", "To allow the consumption of Tacos", "org.eclipse.ui.contexts.window"); } Note, however, that a plugin that programmatically defines contexts is responsible for cleaning them up if the plugin is ever unloaded. Menu Contributions See Menu Contributions Tracing Option There are a couple of reasons why keybindings and commands might not work. 1. Keybindings are in a context that is not active 2. There is a keybinding conflict 3. No handler is currently active for the command 4. There is a handler conflict To help track down the problem, you can run with debug tracing options. For example: org.eclipse.ui/debug=true org.eclipse.ui/trace/keyBindings=true org.eclipse.ui/trace/keyBindings.verbose=true org.eclipse.ui/trace/sources=true org.eclipse.ui/trace/handlers=true org.eclipse.ui/trace/handlers.verbose=true #org.eclipse.ui/trace/handlers.verbose.commandId=org.eclipse.ui.edit.copy org.eclipse.ui/trace/handlers.verbose.commandId=org.eclipse.jdt.ui.navigate.open.type org.eclipse.ui/trace/contexts=true org.eclipse.ui/trace/contexts.verbose=true I put these options in a debug.options file and run eclipse using: bash$ eclipse -debug debug.options -data /opt/local/pw_workspace >debug.log 2>&1 This logs the debug output to the debug.log file. This works on windows as well: C:\development> eclipse33\eclipsec.exe -debug debug.options -data workspaces\pw_workspace >debug.log 2>&1 handlers.verbose.commandId allows you to track the information about a specific command that isn't working. org.eclipse.jdt.ui.navigate.open.type is the open type dialog (normally CTRL+SHIFT+T) and org.eclipse.ui.edit.copy (commented out) is COPY (normally CTRL+C)
__label__pos
0.654305
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. As a follow up to Generate a sequence of all permutation of some range of numbers, I have written the following code inside a Perm class: /** * Permute A to its next permutation, if possible. Returns true if there is * such a permutation, and false otherwise. */ static boolean nextPerm(int[] A) { int N = A.length; int k = N - 1; int v; Set<Integer> S = new HashSet<Integer>(); while (k >= 0) { int max = Collections.max(S); if (max > A[k]) { v = Collections.min(S); S.remove(v); S.add(A[k]); A[k] = v; int [] sArr = convertToArray(S); for (int i = k + 1; i < N - 1; i += 1) { A[i] = sArr[i - k - 1]; } return true; } else { S.add(A[k]); k -= 1; } } return false; } static int [] convertToArray (Set<Integer> s) { int [] sArr = new int[s.size()]; int index = 0; for(Integer i : s) { sArr[index++] = i; } Arrays.sort(sArr); return sArr; } Basically, what it does is to generate a sequence of all permutation of some range of numbers, as follow: Let A be a sequence of integers 0 to N-1 in ascending order (let's assume its an array of int[N]). next_permutation(A): k = N-1 S = { } while k >= 0: if S contains a value larger than A[k]: v = the smallest member of S that is larger than A[k] remove v from S insert A[k] in S A[k] = v A[k+1:N-1] = the values in S in ascending order. return true else: insert A[k] in S k -= 1 return false My code doesn't seem to work tho. Can anyone shed some lights please? Thanks! UPDATE: After taking the inputs from everyone and work on the problem for a bit, I was able to make it work! There are a couple things I've learned: 1. As mentioned by Worakam, TreeSet(compared to HashSet) comes in very handy in this question as it is sorted and has the higher() function. 2. Originally I thought turning a TreeSet into an Integer array would be hectic since the Integer objects aren't quite int. However, it turns out that(probably due to autoboxing/unboxing post java5), I was able to treat the elements within the Integer array as normal int and add int items to it(as shown in the for loop). Here is the working code: static boolean nextPerm(int[] A) { int N = A.length; int k = N - 1; int v; int max = 0; TreeSet<Integer> S = new TreeSet<Integer>(); while (k >= 0) { if (!S.isEmpty() && S.last() > A[k]) { v = S.higher(A[k]); S.remove(v); S.add(A[k]); A[k] = v; Integer [] sArr = new Integer[S.size()]; S.toArray(sArr); for (int i = k + 1; i < N; i += 1) { A[i] = sArr[i - k - 1]; } return true; } else { S.add(A[k]); k -= 1; } } return false; } Thanks alot everyone!! share|improve this question 4   "My code doesn't seem to work tho." -- this tells us little that will help us figure out what is wrong. Please tell the details. Also tell us the results of your attempts to debug this with a debugger or with println statements. –  Hovercraft Full Of Eels Oct 20 '13 at 1:45      Are you aware that you can just call toArray() on a Set<Integer> ? You probably don't need your convertToArray method. –  David Wallace Oct 20 '13 at 1:52      "As a followup" looks more like an edit to me, why is there two question? –  RC. Oct 20 '13 at 4:32      @DavidWallace Hello David, doesn't toArray() on a Set<Integer> return an array of type Integer instead of int? –  Iann Wu Oct 20 '13 at 7:11      Ooh, good point. Sorry. –  David Wallace Oct 20 '13 at 7:29 1 Answer 1 up vote 1 down vote accepted First, Collections.max(S) throws NoSuchElementException when the set is empty. Second, picking the least member of S is not the correct way to implement "the smallest member of S that is larger than A[k]". I suggest that instead of using a HashSet, you should use a sorted data structure, such as a java.util.TreeSet. It would eliminate the need to sort the set yourself. And the method higher() could be pretty useful for your need. share|improve this answer      Thanks alot Worakam! Your input is very helpful and finally I was able to make it work!! 1000 thanks!! –  Iann Wu Oct 20 '13 at 10:19 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.987875
TOC This article has been localized into German by the community. XML: XPath mit der XmlDocument-Klasse benutzen In einem früheren Kapitel haben wir die Klasse XmlDocument verwendet, um Informationen aus einer XML-Datei zu erhalten. Wir haben es getan, indem wir eine Reihe von Aufrufen der ChildNodes-Eigenschaft verwendet haben. Das was einfach, weil das Beispiel sehr einfach war. Es hat aber der Lesbarkeit unseres Codes nicht gut getan, so dass wir in diesem Kapitel einen anderen Ansatz betrachten werden, der definitiv leistungsfähiger und dennoch einfacher zu lesen und zu pflegen ist. Die Technologie, die wir dafür verwenden werden, heißt XPath und wird von der gleichen Organisation verwaltet, die auch den XML-Standard erstellt hat. XPath ist eigentlich eine ganze Abfragesprache mit vielen Möglichkeiten, aber weil das hier kein XPath-Tutorial ist, werden wir uns nur mit einigen grundlegenden Abfragen befassen. Doch selbst in seinen einfachsten Formen ist XPath immer noch mächtig, wie Sie in den folgenden Beispielen sehen werden. Die Klasse XmlDocument verfügt über mehrere Methoden, die eine XPath-Abfrage als Parameter erhalten und dann die resultierenden XmlNode(s) zurückgeben. In diesem Kapitel werden wir uns mit zwei Methoden beschäftigen: Die SelectSingleNode()-Methode, die eine einzelnen XmlNode basierend auf der angegebenen XPath-Abfrage zurückgibt, und die SelectNodes()-Methode, die eine XmlNodeList-Sammlung von XmlNodeObjekten basierend auf der angegebenen XPath-Abfrage zurückgibt. Wir werden beide der oben genannten Methoden ausprobieren, aber anstatt das XML mit Währungsinformationen zu verwenden, das wir in den vorherigen Kapiteln getestet haben, werden wir nun eine neue XML-Quelle ausprobieren. RSS-Feeds sind im Wesentlichen XML-Dokumente, die auf eine bestimmte Weise erstellt wurden, um einer Vielzahl von verschiedenen Newsreadern zu ermöglichen, dieselben Informationen auf ihre eigene Weise zu analysieren und anzuzeigen. Wir werden einen RSS-Feed von CNN verwenden, der sich unter http://rss.cnn.com/rss/edition_world.rss befindet und Nachrichten aus der ganzen Welt enthält. Wenn Sie es in Ihrem Browser öffnen, kann Ihr Browser dies schön formatiert darstellen, so dass Sie sich einen Überblick über den Feed verschaffen und ihn abonnieren können, aber lassen Sie sich davon nicht täuschen: Unter der Haube ist es nur XML, das Sie sehen werden, wenn Sie "Seitenquelltext anzeigen" in Ihrem Browser aufrufen. Sie werden sehen, dass das Wurzelelement "rss" heißt. Das RSS-Element hat in der Regel ein oder mehrere "Channel"-Elemente, und innerhalb dieser Elemente finden wir Informationen über den Feed sowie die Knoten "Item", der die Nachrichten enthält, die wir normalerweise wollen. Im folgenden Beispiel verwenden wir die SelectSingleNode()-Methode, um den Titel des Feeds zu erhalten. Wenn Sie sich das XML ansehen, werden Sie sehen, dass es ein <title> Element als untergeordnetes Element des <channel> Elements gibt, das dann ein untergeordnetes Element des <rss> Elements, der Wurzel ist. Diese Abfrage kann in XPath so beschrieben werden: //rss/channel/title Wir schreiben einfach die Namen des gesuchten Elements, getrennt durch einen Schrägstrich (/), der besagt, dass das Element ein Kind des Elements vor dem Schrägstrich sein sollte. Die Verwendung dieses XPath im Code ist sehr einfach: using System; using System.Text; using System.Xml; namespace ParsingXml { class Program { static void Main(string[] args) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("http://rss.cnn.com/rss/edition_world.rss"); XmlNode titleNode = xmlDoc.SelectSingleNode("//rss/channel/title"); if(titleNode != null) Console.WriteLine(titleNode.InnerText); Console.ReadKey(); } } } Wir verwenden die SelectSingleNode()-Methode, um das Element <title> zu finden, das unseren XPath einfach als Zeichenkettenparameter erhält. Wir überprüfen dann, ob es ein Ergebnis zurückgegeben hat, und wenn ja, zeigen wir den InnerText des gefundenen Knotens an, der der Titel des RSS-Feeds sein sollte. Im nächsten Beispiel werden wir die SelectNodes()-Methode verwenden, um alle "item"-Knoten im RSS-Feed zu finden und dann Informationen über sie auszugeben: using System; using System.Text; using System.Xml; namespace ParsingXml { class Program { static void Main(string[] args) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("http://rss.cnn.com/rss/edition_world.rss"); XmlNodeList itemNodes = xmlDoc.SelectNodes("//rss/channel/item"); foreach(XmlNode itemNode in itemNodes) { XmlNode titleNode = itemNode.SelectSingleNode("title"); XmlNode dateNode = itemNode.SelectSingleNode("pubDate"); if((titleNode != null) && (dateNode != null)) Console.WriteLine(dateNode.InnerText + ": " + titleNode.InnerText); } Console.ReadKey(); } } } Die SelectNodes()-Methode nimmt eine XPath-Abfrage als Zeichenkette, wie wir es im vorherigen Beispiel gesehen haben, und gibt dann eine Liste von XmlNode-Objekten in einer XmlNodeList-Sammlung zurück. Wir iterieren durch sie mit einer foreach-Schleife, und von jedem der "item"-Knoten fragen wir nach einem Kind-Knoten namens "title" und "pubDate" (Veröffentlichungsdatum) mit dem SelectSingleNode() direkt auf dem "item"-Knoten. Wenn wir beide bekommen, zeigen wir das Datum und den Titel in der gleichen Zeile an und gehen dann weiter. In unserem Beispiel wollten wir von jedem "item"-Knoten zwei verschiedene Werte, weshalb wir nach den "item"-Knoten gefragt und dann jeden von ihnen verarbeitet haben. Wenn wir jedoch nur die z.B. die Titel der einzelnen Elemente benötigen, können wir die XPath-Abfrage so ändern: //rss/channel/item/title Es wird jedem Titelknoten in jedem der Elementknoten zugeordnet. Hier ist die Abfrage mit etwas C#-Code: XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("http://rss.cnn.com/rss/edition_world.rss"); XmlNodeList titleNodes = xmlDoc.SelectNodes("//rss/channel/item/title"); foreach(XmlNode titleNode in titleNodes) Console.WriteLine(titleNode.InnerText); Console.ReadKey(); This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!
__label__pos
0.515579
VoxImplant. Blog Step-by-step call center tutorial part 7 Operator status and temporary ban While Voximplant ACD framework provides only essential call center backbone, it also has some out-of-the-box features for most popular use cases. One of such features is “Operator Status” that can be set to “Ready” if operator is available to handle a call, or any one of non-“Ready” if calls should not be forwarded to that operator. All statuses except “Ready” and “Offline” works the same, different names can be used to track statistics. Web SDK is used to manage operator status. For example, status can be changed via setOperatorACDStatus method. In our demo web phone, operator status can be changed via a buttons row: operator-status-buttons Operator that is not logged in has an “Offline” status. After login, the status is automatically changed to “Online”. If all operators has “Offline” status, queuing new request will fail with the ACDEvents.Offline event. Important: Since “Online” is not “Ready”, all new logged-in operators will not receive any calls until they status is set to “Ready”. This mechanic is implemented to protect new developers from accident calls toward operators who don’t expect them. Status need to be explicitly set to “Ready” either by developer or operator. Another out-of-the-box feature is “automatic operator ban”. If operator does not answer the call, such operator is marked as “banned” and will not receive calls for 12 hours. For non-answered call the ACDEvents.OperatorFailed event will be fired and call will be dispatched to the next available operator. This is the second “safety net” so calls are not constantly directed to operators who don’t answer them. In order to “unban” operator, status should be changed to “Ready” from “non-Ready” via Web SDK API. With our phone.voximplant.com example app this is done by clicking on any non-“Ready” status button and then on the “Ready” status button. Queue info and operator status can be received via HTTP API: curl "https://api.voximplant.com/platform_api/GetACDState?account_id=123456&api_key=12345678-1234-1234-1234-123456789012" For example, with one “banned” operator and one call waiting, following response will be received: 1. { 2. "result":{ 3. "acd_queues":[ 4. { 5. "outgoing":{ 6. "waiting_call_count":0, 7. "max_waiting_time":0, 8. "servicing_calls":[], 9. "servicing_call_count":0, 10. "waiting_calls":[] 11. }, 12. "waiting_call_count":1, 13. "max_waiting_time":112, 14. "acd_queue_name":"main", 15. "ready_operators":[], 16. "ready_operator_count":0, 17. "locked_operators":[ 18. { 19. "unreached":"2016-11-21 11:47:34", 20. "user_id":170857, 21. "acd_calls":[], 22. "user_name":"user", 23. "locks":[], 24. "user_display_name":"user" 25. } 26. ], 27. "servicing_calls":[], 28. "servicing_call_count":0, 29. "acd_queue_id":207, 30. "waiting_calls":[ 31. { 32. "acd_session_history_id":87746, 33. "is_incoming":true, 34. "minutes_to_submit":719, 35. "waiting_time":112, 36. "acd_request_id":"1V4TTW8dREyxTc0DFvcQBwJdNWXvyEAqnmh4AvHEfQw", 37. "begin_time":"2016-11-21 11:46:32", 38. "callerid":"79262251608", 39. "priority":100 40. } 41. ] 42. } 43. ] 44. } 45. } Note the locked_operators list that contains info about unavailable operators. Operators in that list with unreached field are banned. Other HTTP API methods can be used to manage queue, collect statistics, etc. Tagged in Comments
__label__pos
0.858141
IMO Level 1- Mathematics Olympiad (SOF) Class 5: Questions 15 - 20 of 889 Access detailed explanations (illustrated with images and videos) to 889 questions. Access all new questions- tracking exam pattern and syllabus. View the complete topic-wise distribution of questions. Unlimited Access, Unlimited Time, on Unlimited Devices! View Sample Explanation or View Features. Rs. 400.00 -OR- How to register? Already Subscribed? Question 15 Question MCQ▾ Which of these could be solved by using the sentence Choices Choice (4)Response a. Shan is 3 times as old as as Sanjit. If A is Sanjit՚s age in years, how old is Shan? b. Tara is 3 years older than Fanny. If A is Fanny՚s age in years, how old is Tara? c. Nayan is one-third as old as Anand. If A is Nayan՚s age, how old is Anand? d. Geeta is 3 years younger than Suhana. If A is Suhana՚s age in years, how old is Geeta? Question 16 Question MCQ▾ There are 147 toffees in a packet. How many toffees are there in 9 such packets? Choices Choice (4)Response a. b. c. d. Question 17 Question MCQ▾ Star Represent the Twice Differences is twice the difference between the 9th and 7th multiple of 5. Find Star Represent the Twice Differences ? Choices Choice (4)Response a. 1 b. 20 c. 2 d. 10 Question 18 Question MCQ▾ = ________ Choices Choice (4)Response a. 1 b. 10 c. 100 d. None of the above Question 19 Question MCQ▾ Cost of 14 calculators is rupees 1456. How much is the cost of 7 such calculators? Choices Choice (4)Response a. 726 rupees b. 728 rupees c. 826 rupees d. Question does not provide sufficient data or is vague Question 20 Question MCQ▾ A balloon seller sold 236 red balloons, 23 white balloons and 749 blue balloons. How many balloons were sold in all? Choices Choice (4)Response a. 186 b. 1008 c. 1005 d. 654
__label__pos
0.999594
cover image for article Configure Neovim in Lua Edit Author: Meet Rajesh Gor #vim #lua Introduction It has been a while since I have written a Vim article. Finally, I got some ideas after configuring my Neovim setup for Lua. I recently migrated to Ubuntu a couple of months back and it has been a cool change from Windows 7! In this article, we'll see how you can set up neovim for Lua. Since Neovim 0.5, it supports lua out of the box, so in the recent release 0.7, it added more native support to lua making it a lot easier to configure and play with neovim. So, we will see how we can use lua to convert all the 200 liner vimscript into lua (We can even have packages and modules:) We will cover how to configure your keymaps, pull up all the plugins, vim options, and other customizations. Why move to Lua? I have used Vimscript for quite a while now, configured it as per my needs, and also made a few plugins like frontmatter, dj.vim, and commenter which are quite clunky and not robust in terms of usage and customizability. Vimscript is good but it's a bit messy when you want extreme customization. I recently wanted to go full Neovim, I was kind of stuck in Vimscript and some of my plugins work for me but it might not work for others, it might be a piece of gibberish vimscript dumped. So, Why not have full native experience in Neovim if you can. It has now baked-in support for LSP, Debugging, Autocommands, and so much more. If you have Neovim 0.5+ you should be good to go full lua. Backup Neovim Config Firstly, keep your original neovim/vim init files safe, back them up, make a copy and save it with a different name like nvim_config.vim. If you already have all your config files backed up as an ansible script or dotfiles GitHub repository, you can proceed ahead. But don't keep the init.vim file as it is in the ~/.config/nvim folder, it might override after we configure the lua scripts. Basic Configuration So, I assume you have set up Neovim, If not you need to follow some simple steps like downloading the package and making sure your neovim environment is working with vimscript first. The Neovim Wiki provides great documentation on how to install neovim on various platforms using different methods. After your neovim is set up and you have a basic configuration, you can now start to migrate into lua. Create a init.lua file in the same path as your init.lua file is i.e. at ~/.config/nvim or ~/AppData/Local/nvim/ for Windows. That's why it is recommended to keep the initial configuration vimscript file in a safe place. While migrating from vimscript to lua, once the lua file is created and the next time you restart neovim, the default settings will be from init.lua and not init.vim, so be prepared. Firstly, you need to configure some options like number, syntax highlighting, tabs, and some keymaps of course. We can use the vim.opt method to set options in vim using lua syntax. So, certain corresponding vim options would be converted as follows: If you have the following kind of settings in your vimrc or init.vim: -- vimscript set number set tabstop=4 set shiftwidth=4 set softtabstop=0 set expandtab set noswapfile The above settings are migrated into lua syntax as follows: --lua vim.opt.number = true vim.opt.tabstop = 4 vim.opt.shiftwidth = 4 vim.opt.softtabstop = 0 vim.opt.expandtab = true vim.opt.swapfile = false You can set other options in your config file accordingly. If you get sick of writing vim.opt. again and again, you can use a variable set to vim.opt and then access that variable to set the options. Something of the lines as below: local set = vim.opt set.number = true set.tabstop = 4 set.shiftwidth = 4 set.softtabstop = 0 set.expandtab = true set.swapfile = false We can create a variable in lua like local variable_name = something so, we have created a variable set which is assigned to the value of vim.opt which is a method(function) in lua to set the options from the vimscript environment. Finally, access the set keyword to set the options. Using the set word is not necessary, you can use whatever you want. After setting up the basic options, you can source the file with :so % from the command mode. Just normally as you source the config files. Using Lua in Command Mode We can use the lua functions or any other commands from the command mode in neovim using the lua command. Just prefix the command with :lua and after that, you can use lua syntax like function calling or setting variables, logging things, etc. Lua in Command Mode Adding Keymaps Now, that we have some basic config setup, we can quickly get the keymaps. It's not that hard to make keymaps to set up in lua. To create keymaps, we have two options. One is compatible with Neovim and the other is compatible with Vim as well. 1. vim.keymap.set OR 2. vim.api.nvim_set_keymap Personally, I don't see a difference in terms of usage but vim.keymap.set is a wrapper around nvim_set_keymap. So, it is really a matter of personal preference which you want to use. So, both the functions have quite similar parameters: vim.keymap.set({mode}, {lhs}, {rhs}, {options}) vim.api.nvim_set_keymap({mode}, {lhs}, {rhs}, {options}) The advantage of vim.keymap.set over vim.api.nvim_set_keymap is that it allows directly calling lua functions rather than calling vimscripty way like :lua function(), so we directly can use lua code in the RHS part of the function parameter. Let's take a basic example mapping: vim.keymap.set('n', 'Y', 'yy', {noremap = false}) Here, we have mapped Shift+y with the keys yy in normal mode. The first argument is the mode, it can be a single-mode like 'n', 'v', 'i', etc., or a multi-mode table like {'n', 'v'}, {'v', 'i'}, etc. The next parameter is also a string but it should be the key for triggering the mapping. In this case, we have used Y which is Shift + y, it can be any key shortcut you want to map. The third parameter is the string which will be the command to be executed after the key has been used. Here we have used the keys yy, if the map is from a command mode, you will be using something like ':commands_to_be executed' as the third parameter. The fourth parameter which is optional can contain special arguments. We have set a default option which is noremap as true, the options are not string but lua tables instead, so it can be similar to python dictionary or a map kind of a structure with a key value pair. One more important aspect in keymapping might about the leader key, you can set your leader key by using the global vim options with vim.g and access mapleader to set it to the key you wish. This will make the leader key available to us and thereafter we can map the leader key in custom mappings. vim.g.mapleader = " " Here, I have set my leader key to the <Space> key. Now, we can map keys to the existing keymaps in the vimscript. Let's map some basic keymaps first and then after setting up the plugins,we can move into plugin-specific mappings. You can also use vim.api.nvim_set_keymap function with the same parameters as well. vim.keymap.set('n', '<leader>w', ':w<CR>',{noremap = true}) vim.keymap.set('n', '<leader>q', ':q!<CR>',{noremap = true}) vim.keymap.set('n', '<leader>s', ':so %<CR>',{noremap = true}) vim.keymap.set('n', '<leader>ev', ':vsplit $MYVIMRC<CR>',{noremap = true}) vim.keymap.set('n', '<leader>sv', ':w<CR>:so %<CR>:q<CR>',{noremap = true}) OR vim.api.nvim_set_keymap('n', '<leader>w', ':w<CR>',{noremap = true}) vim.api.nvim_set_keymap('n', '<leader>q', ':q!<CR>',{noremap = true}) vim.api.nvim_set_keymap('n', '<leader>s', ':so %<CR>',{noremap = true}) vim.api.nvim_set_keymap('n', '<leader>ev', ':vsplit $MYVIMRC<CR>',{noremap = true}) vim.api.nvim_set_keymap('n', '<leader>sv', ':w<CR>:so %<CR>:q<CR>',{noremap = true}) If, you don't like writing vim.keymap.set or vim.api.nvim_set_keymap again and again, you can create a simpler function for it. In lua a function is created just like a variable by specifying the scope of the function i.e. local followed by the function keyword and finally the name of the function and parenthesis. The function body is terminated by the end keyword. function map(mode, lhs, rhs, opts) local options = { noremap = true } if opts then options = vim.tbl_extend("force", options, opts) end vim.api.nvim_set_keymap(mode, lhs, rhs, options) end Now, in this function map, we have passed in the same parameters like the vim.keymap.set function takes but we have just parsed the function in a shorter and safer way by adding noremap = true by default. So this is just a helper function or a verbose function for calling the vim.keymap.set function. To use this function, we can simply call map with the same arguments as given to the prior functions. map('n', '<leader>w', ':w<CR>') map('n', '<leader>q', ':q!<CR>') map('n', '<leader>s', ':so %<CR>') Notice here, though, we have not passed the {noremap = true} as it will be passed by default to the vim.api.nvim_set_keymap or vim.keymap.set function via the custom map function. If you want some more examples, here are some additional mapping specific to languages, meant for compiling or running scripts with neovim instance. -- vimscript nnoremap cpp :!c++ % -o %:r && %:r<CR> nnoremap c, :!gcc % -o %:r && %:r<CR> nnoremap py :!python %<cr> nnoremap go :!go run %<cr> nnoremap sh :!bash %<CR> -- lua map('n', 'cpp' ':!c++ % -o %:r && %:r<CR>') map('n', 'c,' ':!gcc % -o %:r && %:r<CR>') map('n', 'py' ':!python %<cr>') map('n', 'go' ':!go run %<cr>') map('n', 'sh' ':!bash %<cr>') So, this is how we can set up our keymaps in lua. You can customize this function as per your needs. These are just made for the understanding purpose of how to reduce the repetitive stuff in the setup. If you are really stuck up and not feeling to convert those mappings into lua then I have a function that can do it for you, check out my dotfile repo -> keymapper Adding Plugin Manager Now, we really missing some plugins, aren't we? So, the neovim community has some good choices for using a new plugin manager written in core lua. It is usually a good idea to move into lua completely rather than switching to and fro between vimscript and lua. So, Packer is the new plugin manager for Neovim in Lua, there is other plugin managers out there as well like paq. If you don't want to switch with the plugin manager, you can still use vim-based plugin managers like Vim-Plug. So, let's install the Packer plugin manager into Neovim. We simply have to run the following command in the console and make sure the plugin manager is configured correctly. # Linux git clone --depth 1 https://github.com/wbthomason/packer.nvim\ ~/.local/share/nvim/site/pack/packer/start/packer.nvim # Windows git clone https://github.com/wbthomason/packer.nvim "$env:LOCALAPPDATA\nvim-data\site\pack\packer\start\packer.nvim" Now, if you open a new neovim instance and try to run the command :PackerClean, and no error pops out that means you have configured it correctly. You can move ahead to installing plugins now. Yeah! PLUG-IN time! return require('packer').startup(function() end) First try to source the file, if it throws out errors it shouldn't try to fix the installation path of Packer. If the command succeded we can finally pull up some plugins. Below are some of the plugins that you can use irrespective of what language preferences you would have. This includes basic dev-icons for the status line as well as the explorer window file icons. As usual, add your plugins and make them yours. return require('packer').startup(function() use 'wbthomason/packer.nvim' use 'tpope/vim-fugitive' use { 'nvim-lualine/lualine.nvim', requires = { 'kyazdani42/nvim-web-devicons', opt = true } } use 'tiagofumo/vim-nerdtree-syntax-highlight' use 'kyazdani42/nvim-web-devicons' use 'vim-airline/vim-airline' use 'vim-airline/vim-airline-themes' end) After adding the list of your plugins, you need to source the file and then install the plugins with the command :PackerInstall. This function will install all the plugins after the file has been sourced so make sure you don't forget it. Colors and Color Themes You might fancy some good-looking and aesthetic setup for neovim of course! In Neovim, we already have a wide variety of configurations to set up like color schemes, GUI colors, terminal colors, etc. You can pick up a color scheme from a large list of awesome color schemes from GitHub. After choosing the theme, plug it in the packer plugin list which we just created and source the file and finally run :PackerInstall. This should install the plugin. You can then set the colorscheme as per your preference, first view the color scheme temporarily on the current instance with the command :colorscheme colorscheme_name. return require('packer').startup(function() use 'wbthomason/packer.nvim' -- use 'Mofiqul/dracula.nvim' -- end) You can then add the command to set it as the default color scheme for Neovim. vim.cmd [[silent! colorscheme dracula]] You can change the background color, text color, icons style and terminal and gui style separately with the augroup and setting the colorscheme commands. vim.api.nvim_command([[ augroup ChangeBackgroudColour autocmd colorscheme * :hi normal termbg=#000030 termfg=#ffffff autocmd colorscheme * :hi Directory ctermfg=#ffffff augroup END ]]) vim.o.termguicolors = true Here, I have used the background and foreground colors of the terminal variant of Neovim. Also for the Directory Explorer i.e. netrw, I have changed the terminal foreground. This you can configure as per your needs, Though this is still vimscripty, there are Autocommands and autogroups available sooner in Neovim. Separating Configurations If you wish to keep all your config in one file i.e. init.lua file, you can, though you can separate out things like keymaps, plugins, custom_options or if you have lsp configurations into separate lua packages or creating a separate module. This helps in loading up things as per requirement and also looks readable, making it a lot easier to test out things without breaking the whole config. Definitely, there will be personal preferences and pros and cons of both approaches, you can pick up whatever suits your style. Creating separate packages To create a separate package, we can simply add a file in the same folder as init.vim i.e. in the folder ~/.config/nvim or equivalent for windows. The package name can be any valid filename with the lua extension. For instance, you can create a package for all your keymaps and load it in the init.lua as per the order you want to load them. It can be at the top, or else if you have certain base settings lower in the init file, these might not reflect or load up in the keymap package so better to load them after some of the core settings have been set. Let's create the package and dump all our maps into the keymap file package. -- ~/.config/nvim/keymap.lua function map(mode, lhs, rhs, opts) local options = { noremap = true } if opts then options = vim.tbl_extend("force", options, opts) end vim.api.nvim_set_keymap(mode, lhs, rhs, options) end map('n', '<leader>w', ':w<CR>') map('n', '<leader>q', ':q!<CR>') map('n', '<leader>s', ':so %<CR>') map('n', 'cpp' ':!c++ % -o %:r && %:r<CR>') map('n', 'c,' ':!gcc % -o %:r && %:r<CR>') map('n', 'py' ':!python %<cr>') map('n', 'go' ':!go run %<cr>') map('n', 'sh' ':!bash %<cr>') -- more keymaps So, this might work if you don't have any plugin-related keymaps as it would require those functions or objects available to execute. So, we might also want to separate plugins and load them first in our keymaps or in the init file. Now, there needs to be a way for grabbing a package. Yes, there is basically like import in python or any other programming language, lua has require keyword for importing packages. Since the init file and the keymaps are in the same folder path, we can simply say, require("keymap") in our init.lua file. Now, it depends on your config where you want to load this package. At the top i.e. at the beginning of neovim instance or after loading the plugins down. -- init.lua require("keymaps") -- At the top -- OR -- After loading Packer plugins So, now you can separate all your configs as per your requirement. It is like splitting up a puzzle and again combining them. Similar package can be created for plugins, options or lsp configurations. Creating a separate module Now, we have seen how to create a lua package and loading in neovim. We also can create modules in neovim configuration. For instance, first, the init file is loaded, Other files might not be required hence it is not loaded by default, it is only loaded when requireed. So, we can create a module in lua with a folder, and inside of it, we can have packages as we had in the previous method. Also, every module can have a init file loaded first when we require that module. The rest of the packages in the module are thus made available thereafter. So, in neovim, we need to create a lua folder for placing all our modules so that the lua runtime is picked up correctly. Inside this lua folder, we can create a module basically a folder. This folder name can be anything you like, I like to keep it my nickname, you can use whatever you prefer. # ~/.config/nvim -- init.lua -- lua/ -- module_name/ -- init.lua -- package_name.lua -- keymaps.lua Now, we can create packages in this module. You can move your keymaps package inside this folder. The keymaps package is nothing here but an example provided in the previous section for creating a package. You can basically dump all your keymaps in a single lua file and then import it from the init file. Similarly you can create a package inside a module and import it from the init file of the module(local init file ~/.config/nvim/lua/module_name/init.lua) or the global init file(~/.config/nvim/init.lua). To load the packages, you have to use the same require statement irrespective of where you are importing from i.e. either from the module or from the global init file. The require statement would look like the following require("module_name/package_name"). Now, we can use the keymaps package to import from the module init file and then import the module from the global init file. To import a module, we can simply use the module name in the require string as require("module_name"). -- ~/.config/nvim -- lua/module_name/options.lua vim.opt.number = true vim.opt.tabstop = 4 vim.opt.swapfile = false -- lua/module_name/plugins.lua require("module_name.options") return require('packer').startup(function() use 'wbthomason/packer.nvim' --plugins end) -- lua/module_name/keymap.lua require("module_name.plugins") -- maps() -- lua/module_name/init.lua require("module_name.keymaps) -- init.lua require("module_name") So, this is how we can create modules and packages for configurations in neovim using lua. This is also a kind of a structure for creating your own neovim plugin with lua! For further references, you can check out my dotfiles. References Conclusion So, that is just a basic overview of how you can get your neovim configured for lua. It is a great experience to just create such a personalized environment and play with it and have fun. You might have hopefully configured Neovim for Lua from this little guide. Maybe in the next article, I'll set up LSP in Neovim. If you have any queries or feedback, please let me know. Thank you for reading. Happy Viming :)
__label__pos
0.701358
本站電子書 您可以在這些電子書店找到本站電子書: Google Play 圖書iBooks StoreHyReadReadmooPubu 紙本書與電子書偏好調查(於 Facebook 粉絲專頁);《如何自學程式設計》入選 Google Play 台灣地區2016年度最佳書籍 Java API 分類導覽 - java.awt.SystemColor activeCaption, ACTIVE_CAPTION SystemColor 類別 (class) 的 activeCaption 屬性 (field) 為作用中標題列的背景顏色物件, ACTIVE_CAPTION 則是 activeCaption 的整數索引值。 修飾子 public static final SystemColor activeCaption public static final int ACTIVE_CAPTION 舉例如下 import java.awt.*; import java.awt.event.*; public class SystemColorDemo01 { public static void main(String[] args) { Frame frame = new Frame("AWTDemo"); frame.addWindowListener(new AdapterDemo()); frame.setSize(320, 240); Label word = new Label("activeCaption"); word.setForeground(SystemColor.activeCaption); frame.add(word); frame.setVisible(true); System.out.println("activeCaption: " + SystemColor.ACTIVE_CAPTION); } } class AdapterDemo extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } /* 《程式語言教學誌》的範例程式 http://pydoing.blogspot.com/ 檔名:SystemColorDemo01.java 功能:示範 Java 程式 作者:張凱慶 時間:西元 2012 年 3 月 */ 此例建立一個 Label 物件,並將前景顏色設定為 SystemColor.activeCaption Label word = new Label("There is no spoon."); word.setForeground(SystemColor.activeCaption); frame.add(word); 然後在命令列印出 SystemColor.ACTIVE_CAPTION System.out.println("activeCaption: " + SystemColor.ACTIVE_CAPTION); 編譯後執行,結果如下 中英文術語對照 類別class 屬性field 參數parameter 您可以繼續參考 字型與顏色 相關目錄 Java API 分類導覽 Java 教材 首頁 參考資料 http://docs.oracle.com/javase/6/docs/api/java/awt/SystemColor.html 沒有留言:
__label__pos
0.719739
What can you do with Calendar? With Google Calendar, you can quickly schedule meetings and events, and get reminders about upcoming activities, so you always know what’s next. Calendar is designed for teams, so it’s easy to share your schedule with others and create multiple calendars that you and your team can use together. What you’ll need: Google Apps account 10 minutes Switching from a different calendar program? You may also want to see Switching to Google Calendar from Outlook or Switching to Google Calendar from IBM Notes. Note: If your administrator hasn’t already migrated your old calendar for you, you may want to import your old calendar before starting this tutorial. What can you do with Google Calendar 1 Schedule events In Calendar, it’s easy to schedule one-time activities like conferences and recurring events like staff meetings. When you receive an invitation to someone else’s event, you can let everyone know if you’re attending with a single click! In this section, you'll learn how to: 1.1 Create an event To create an event in Calendar: 1. Go to calendar.google.com. 2. Click CREATE. Create an event 1.2 Invite people and reserve rooms and resources To invite people to your event: 1. In the Event details page, find the Add section and click Guests. 2. Type the first few letters of a person’s name or email address in the box. Matching addresses in your organization’s directory appear as you type. 3. Click one of the suggestions to add that person to the event. If no suggestions appear, type your guest’s full email address and click Add. You can even add a Google Groups mailing list address to invite a large group of people at once, such as your whole team (For example: [email protected]), or the entire organization (For example: [email protected]). To reserve rooms and resources* for your event: 1. In the Event details page, find the Add section and click Rooms, etc. 2. (Optional) To see only available resources, check Show only available. 3. Start typing the room or resource’s name and click one of the suggestions. Or, browse the list of resources and click Add next to an available resource you want. *Your Google Apps administrator must first set up Calendar resources for your organization. Invite people and reserve rooms and resources 1.3 Choose your event time To choose a date and time for your event, click the date and time boxes, and select when your event starts and ends. To set up a recurring event, such as weekly meetings: 1. Check Repeat and enter the details for how you want to schedule your recurring events. 2. Click SAVE. If you have a lot of guests, you can quickly see when everyone is available. Click Suggested times under your guest list to see a list of times when everyone can attend. Or, click the Find a time tab to stack your guests’ calendars, then pick a time when nobody has a scheduling conflict. Choose your event time 1.4 Save and update events When you’re finished filling in the details, save your event: 1. Click SAVE. 2. In the pop-up, click Send to notify guests by email, or Don’t send if you don’t want to notify guests at this time. To update existing events: 1. Click the event in your Calendar. 2. Click Edit event to make changes, such as updating the time or inviting more guests. You’ll also be able to see which of your guests have accepted your invitation. 3. Click SAVE. Save and update events 1.5 Respond to invitations When you get an invitation to an event, it appears on your calendar. To reply to an invitation in Calendar: 1. In the calendar grid, click the event. 2. In the dialog box, select your response. Or, if you’d like to include a short note with your response, click More details, select your response, type your note, and click Save. 3. You can change your response at any time by clicking More details > Add a note or change your response. You’ll also get an invitation in your email. If you're using Gmail, you can respond to the invitation by clicking RSVP in your list of emails, or by clicking a response option in the email. Respond to invitations 1.6 View and restore deleted events Restore an event you deleted by mistake, or permanently remove deleted events. To view and restore deleted events*: 1. In Calendar, open the My calendars list. 2. Hover over your calendar and next to the name, click the Down arrow Calendar dropdown arrow Trash. 3. Check the box next to the event you want to change and do one of the following options: • To restore the deleted event, click Restore selected events. • To permanently delete the event, click Delete forever. 4. (Optional) To delete all events in your trash, at the top, click Empty trash now. *To view and manage deleted events for other calendars, you must have "Make changes to events" or "Make changes AND manage sharing" permission for them. Note: Deleted events remain in a calendar's trash for 30 days. None 2 Add reminders You can create 2 types of reminders in Calendar: • Event notifications — To remember an upcoming event, add an event notification. • Personal reminders — To remember something on your to-do list, add a personal reminder. In this section, you'll learn how to: 2.1 Set up default event notification settings 1. Click Settings and select Settings. 2. At the top, click Calendars. 3. Next to your calendar's name, click Edit notifications. 4. Choose how and when you want to be notified about different events and updates. 5. Click SAVE. Set up default notification settings 2.2 Add, change, or remove event notifications Need a little extra time to prepare for an important meeting? Or, maybe you don’t need a reminder about an activity after all. You don’t have to change your default notification settings — just add or update reminders for that particular event: 1. On your calendar, click the event and then click Edit event (for events without guests) or More details (for events with multiple guests). 2. In the Notifications section, choose how you want to be reminded about the event. 3. (Optional) To add multiple notifications, click Add a notification. 4. (Optional) To remove a notification, click Remove Calendar x notification next to the notification you want to remove. 5. Click SAVE. Add or change notifications for a specific event 2.3 Add personal reminders Note: Reminders you create in Inbox or Google Keep also show up in Google Calendar. To add a personal reminder: 1. If you don’t see Reminders under My calendars, click the Down arrow Calendar dropdown arrow next to Tasks and select Switch to Reminders. 2. Click an empty time slot in your calendar. 3. At the top, click Reminder. 4. Add your reminder. 5. Choose a date, time, and frequency for your reminder. 6. Click Create. None 2.4 Change personal reminders To change a personal reminder: 1. Do one of the following options: • If you have a single reminder in a time slot, click the reminder and then click Edit. • If you have multiple reminders in the same time slot, hover over the reminder block, click the reminder, and click Edit Docs editing mode. 2. Update the event details. 3. Click Save changes. None 2.5 Complete or remove personal reminders To remove a reminder from your calendar, you can: • Mark it done. The reminder stays on your calendar, but it's crossed out. • Delete it, which removes the reminder completely. • Hide all reminders temporarily. 1 To mark a reminder done: Do one of the following options: • If you have a single reminder in a time slot, click the reminder, and then click Mark as done. • If you have multiple reminders in the same time slot, hover over the reminder block, click the reminder, and click Mark as done Docs checkmark. 2 To delete a reminder: 1. Click the reminder you want to update. 2. Do one of the following: • If you have a single reminder in a time slot, click Delete. • If you have multiple reminders in the same time slot, click Edit Docs editing mode and then click Delete. 3 To hide all reminders: Under My calendars, click Reminders. None 3 Share and view Share your calendar with coworkers, family, and friends so they can easily see when you’re available. You can look at other people’s calendars to do the same. In this section, you'll learn how to: 3.1 Share your calendar To choose who to share your calendar with and how much they can see: 1. Click the Down arrow Calendar dropdown arrow next to your calendar name. 2. Click Share this Calendar. 3. Enter email addresses and set permissions for people you want to share with. 4. Click Save. Share your calendar To share your calendar with people who don’t use Google Calendar: 1. Click the Down arrow Calendar dropdown arrow next to your calendar name. 2. Click Calendar settings. 3. Scroll to Calendar Address, click one of the options to get a link you can share. For example, to let someone see your calendar in any web browser, click and share the URL in the pop-up. 4. Click OK > Save. Share your calendar 3.2 View other people's calendars Wondering if someone’s available to meet? To view other people’s calendars: 1. Under Other calendars, start typing the person’s name or address in the Add a coworker’s calendar box. 2. Select the person from the list: • If the person has shared their calendar, it appears in your Other calendars list. That person's events also appear on your calendar. • If the person hasn’t shared their calendar or doesn’t use Google Calendar, a dialog box appears. Fill out your request and click Send invite. 3. Click the box to the left of a person’s name in your Other calendars list to hide or show their events on your calendar. Schedule events quickly by checking your coworkers’ availability or layering their calendars over yours in a single view. When you’re done looking at other people’s calendars, go back to viewing only your calendar by clicking the Down arrow next to your calendar and selecting Display only this calendar. View other people's calendars 4 Create a team calendar In addition to your own calendar, you can create other calendars to track schedules and manage projects. For example, you can create a team calendar to track information, such as team members’ vacations schedules and business trip dates. With everyone’s availability in one calendar, it’s easy to: • Know who’s in the office if you have questions or need to talk to someone. • Plan team-wide events and meetings. • Assign tasks and projects based on people’s availability. In this section, you'll learn how to: 4.1 Create a team calendar To create a team calendar: 1. Click the Down arrow next to My calendars and select Create new calendar. 2. Name the calendar, enter your timezone, and add a description so your team knows the purpose of this calendar. 3. Check the Share this calendar with others box, and share it with everyone in your organization. 4. Enter individual email addresses of people who can modify or manage the calendar, and set their permission levels. 5. Click Create calendar. You can create as many calendars as you want using the same process. Create a team calendar 5 Customize Now that you know how to use all the key features in your Calendar, you can customize it further to match the way you work. In this section, you'll learn how to: 5.1 Choose your calendar view You can choose how many days you see at a time in your calendar view, or change your calendar to an agenda view to see a list of your events. Select the option that’s best for you in the top corner of your calendar. Choose your calendar view 5.2 Change your event colors Changing event colors can help you distinguish between calendars when you have several layered on the same screen. To change the color of events on your or others’ calendars: 1. Click the Down arrow next to the calendar name. 2. Select the color you want from the palette. Change your event colors Next steps Try it now Get more training Add attachments to your events, set up bookable office hours, create collaborative team calendars, and more. See Calendar tips
__label__pos
0.933246
Go Down Topic: help with String manipulation (Read 2467 times) previous topic - next topic JT007 Need some help understanding this line of code Code: [Select] s[0] = cstring[0]; s[1] = '\0'; SlaveID = (unsigned long)atoi(s); Its purpose is to parse a string input and store the value in SlaveID (in this case the first character from a serial input string) I want to be able to use 3 characters ie. 255. the code above only shows the first character how can i manipulate it so i cand display the first 3 characters of a string in essence how does the line above work GoForSmoke s[1] = '\0' ? same as s[1] = 0; which makes a null terminator right after s[0] Some time try debugging by printing different variables out, then you'll know what you got -right then-. Nick Gammon on multitasking Arduinos: 1) http://gammon.com.au/blink 2) http://gammon.com.au/serial 3) http://gammon.com.au/interrupts JT007 I have worked out that this code simply tests the first character and stores it, so back to my question how can i filter a string to give me the first 3 characters so that i can store it, i want to capture a 3 digit value i. 255. in VB6 i can use the mid or instring command and get the characters i want how is this acheived with c and the arduino code. I have looked at the tutorials and string examples but i have not found one that will filter characters out of a string please help J. UKHeliBob The first question is do you mean a String or a string ? If you are using Strings then have a look at this page http://arduino.cc/en/Tutorial/StringSubstring If not then you can certainly do the following which is an extension of the example in your first post. Code: [Select] char myText1[] = {   "Hello"}; char myText2[4];        //space for 3 characters plus null in target void setup() {   Serial.begin(9600);   for (int ch = 0; ch <= 2;ch++)   {     myText2[ch]=myText1[ch];   }   myText2[3] = '\0';   Serial.println(myText1);   Serial.println(myText2); } void loop() { } This being C++ I expect that there is a neater way of doing it but this example makes it very obvious what is going on and, of course, you could pick out any characters from the first string and put them in the second.  Note that the null termination of the sub-string is very important. Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers. johncc You mean something like this? Code: [Select] char *s="123Hello"; int num=atoi(s);   // c-string to integer char s2[8]; itoa( num, s2, 10);  // integer to c-string base 10 mrburnette #5 Jan 27, 2013, 04:35 pm Last Edit: Jan 27, 2013, 09:48 pm by mrburnette Reason: 1 With Arduino 1.0 forward (I'm using 1.0.3), you can use the Streams class to manage input from terminals or PC hosted applications.  A new set of commands have been included to make life easier: Serial.parseFloat() and Serial.parseInt() The easiest way to understand the new commands is to run a simple program, the example below will run on probably all Arduinos, but I've only tested with UNO and Nano328.  When running the example, use the Arduino Serial Monitor first.  You can put in integers or floating point for the triangle sides "a" and "b".  Then try the stream by inputting a set of variables, comma separated.  Now try a set of variables separated by a space!  IN ALL CASES, you must use a leading zero for any number less than 0: for example, ".5" will be taken as 5.0 but 0.5 will be taken correctly.  IF you only want integers, then replace the .parseFloat() with .parseInt() and change the variables from float to int. Now use an external terminal program such as ttermpro (Tera Term) and connect to the Arduino.  Because the terminal is a character-by-character transfer, each keystroke is transmitted up until the newline.  So, the behavior is a bit different than that of the Arduino Serial Monitor. Code: [Select] /* Right Triangle - User Interactive via Serial Terminal   M. Ray Burnette 20130125   Arduino Nano 328P target processor   Binary sketch size: 5,384 bytes (of a 30,720 byte maximum) */ #include "math.h" #define BAUD 9600 #define timeoutPeriod 2147483647    // Long var... about 25 days float a; float b; float h; // long timeoutPeriod = 2147483647; void setup() {  Serial.begin(BAUD);  Serial.setTimeout(timeoutPeriod); // default is 1 second  Serial.println("Let's calculate a hypotenuse, h");  Serial.println("               /|");  Serial.println("             /  |");  Serial.println("           /    |");  Serial.println("      h  /      |");  Serial.println("       /       b|");  Serial.println("     /          |");  Serial.println("   /            |");  Serial.println(" /________a_____|");  Serial.println("");  Serial.println("");   } void loop() {  Serial.println("Enter value for leg 'a', Press ENTER");  if (Serial.read() == '\n') ;  // Wait here until input buffer has a newline  {      //Side 1    a = Serial.parseFloat();        // new command in 1.0 forward    Serial.print("a = "); Serial.println(a, 6);  }  Serial.println("Enter value for leg 'b', Press ENTER");  if (Serial.read() == '\n') ;  // Wait here until input buffer has a newline  {       //Side 2    b = Serial.parseFloat();    Serial.print("b = "); Serial.println(b, 6);  }  h = sqrt ( a*a + b*b );  Serial.print("hypotenuse = ");  Serial.println(h, 6); Serial.println(); } Parse 2 integers from stream... any non-numeric delimiter can be used, i.e., "O" or "|" Code: [Select] #define BAUD 9600 #define timeoutPeriod 2147483647 int a; int b; void setup() {   Serial.begin(BAUD);   Serial.setTimeout(timeoutPeriod); // default is 1 second } void loop() {   Serial.println("Enter first integer: ");   {     a = Serial.parseInt();     Serial.print("a = "); Serial.println(a);   }   Serial.println("Enter second integer: ");   {     b = Serial.parseInt();     Serial.print("b = "); Serial.println(b);   } } Output example: GoForSmoke 255 would be '2' '5' '5' '0' The zero marks the end of the string. If you are parsing a longer string then after 255 there would be a ' ' (space) that you would look for to maybe replace with 0 but if you want to parse the rest then  save that location to a pointer so you can go back and do that. If you don't know what pointers are then you need to search on C pointers and do some learning. Nothing I could post quickly here will just give it to you right away, learning this properly means doing some homework with sketches. You can turn '2' into 2 through val = '2' - '0' but check that you have '0' to '9' -- always expect that an error will happen, serial data has no guarantees. Normally I would pull each character in, check (if error then report it and either stop the program or ask for input again), multiply any old value by 10 (initialized to 0, 0 * 10 = 0) and add the new value until I hit the terminating zero. But there's at least 3 other ways including using atoi() which can return error as well. Even parsing, you can use strtok() which is very nice but actually more complicated than processing a string as an array which is funny because so many people use it "because it's easier". Yeah sure, -after- you learn the ins and outs there's less typing so that makes it easier. Or don't learn the ins and outs and spend even more time puzzling out bugs. You have a few things to learn no matter what. Like how C strings work, what ASCII code is, and pointers. Then have a look through C string commands which once you the first stuff should make easy sense. After that, plan your code. Here's another clue; if you don't understand everything about example code then find out before you go modifying it or using pieces of it in something else. Nick Gammon on multitasking Arduinos: 1) http://gammon.com.au/blink 2) http://gammon.com.au/serial 3) http://gammon.com.au/interrupts AWOL Quote 255 would be '2' '5' '5' '0' No, "255" would be '2' '5' '5' '\0' "Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill. Do not send technical questions via personal messaging - they will be ignored. UKHeliBob That's neater (less code) but hardly easily understood.  How would you use the method to get sub-strings ? Also, it only works if the string starts with an integer as far as I can see Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers. zoomkat Quote so back to my question how can i filter a string to give me the first 3 characters so that i can store it, i want to capture a 3 digit value i. 255. The below is for servo control. It captures a string number sent using a comma as a delimiter to signal the end of transmission. You should be able to do something similar to get your number. Code: [Select] //zoomkat 3-5-12 simple delimited ',' string parce //from serial port input (via serial monitor) //and print result out serial port // CR/LF could also be a delimiter String readString; #include <Servo.h> Servo myservo;  // create servo object to control a servo void setup() {  Serial.begin(9600);  myservo.writeMicroseconds(1500); //set initial servo position if desired  myservo.attach(7);  //the pin for the servo control  Serial.println("servo-delomit-test-22-dual-input"); // so I can keep track of what is loaded } void loop() {  //expect a string like 700, or 1500, or 2000,  //or like 30, or 90, or 180,  if (Serial.available())  {    char c = Serial.read();  //gets one byte from serial buffer    if (c == ',') {      if (readString.length() >1) {        Serial.println(readString); //prints string to serial port out        int n = readString.toInt();  //convert readString into a number        // auto select appropriate value, copied from someone elses code.        if(n >= 500)        {          Serial.print("writing Microseconds: ");          Serial.println(n);          myservo.writeMicroseconds(n);        }        else        {            Serial.print("writing Angle: ");          Serial.println(n);          myservo.write(n);        }        //do stuff with the captured readString        readString=""; //clears variable for new input      }    }      else {          readString += c; //makes the string readString    }  } } Google forum search: Use Google Advanced Search and use Http://forum.arduino.cc/index in the "site or domain:" box. GoForSmoke Quote 255 would be '2' '5' '5' '0' No, "255" would be '2' '5' '5' '\0' Oh right, I should have wrote '2' '5' '5' 0 Nick Gammon on multitasking Arduinos: 1) http://gammon.com.au/blink 2) http://gammon.com.au/serial 3) http://gammon.com.au/interrupts JT007 Ok I have attached my code, so hopefully you can see what im trying to acheive. I have been working on getting an RS485 modbus link set up and this code will be used by the Host PC to communicate with the master module Input string should arrive in the format of 255O255| the first 3 characters are the Slave device address Capital Letter "O" designates an output function the remainder is the digital value to be transmitted over an RS485 Link followed by a termination character "|" used to generate a message of ID, Function, value The code im using was plagerised from a stepper motor program, I liked the way in which it analyses the serial input. I just want to increase the number of Slave IDs The code is working Code: [Select] #define USB_SERIAL #define ON 1 #define OFF 0 #include <stdio.h> // for function sprintf // Conditional start int Startup = 0; int Run = 0; int SlaveID = 0; byte DigitalVal =0; #if defined(USB_SERIAL) #include <ctype.h>     //needed for function 'toupper' #include <string.h>    //needed for 'strcmp' and 'strcat' #endif int test = ON; // E for Echo                 //test facility which can be enabled/diabled via serial port command                                   //presently this only echoes commands back to serial port  --  possibly useful during development of PC based driver programs int hundreds,tens,ones; #if defined(USB_SERIAL) int analyse_command_string(char cstring[]); char *stripallspaces( char *s ); //set up program information char progname[60] = "Winder Control v";  //this info will be echoed to the serial port on startup or reboot of the Arduino char progversion[] ="1"; char commandstring[130] = "";     //serial input string buffer #endif void setup()   #if defined(USB_SERIAL)   //set up serial port   Serial.begin(9600);  #endif  } void loop() {   int c, i;    int static n = 0; // NOTE: THIS VARIABLE MUST BE DECLARED AS STATIC     // ----------------------------- READ SERIAL INPUT STRING ------------------------------------------------- #if defined(USB_SERIAL)      //SET FOR CONTROL VIA USB_SERIAL PORT      //      if (Serial.available() > 0)  //ie charater(s) in input buffer        {        commandstring[n] = Serial.read(); n++;           if (commandstring[n-1] == '|') //ie character is '|' (end of command marker)           {           commandstring[n]='\0';  //terminate string and reset counter ready for next string           n = 0;                   //if test mode enabled, echo string back to serial port -- could be useful for development of driver programs           if (test == ON) {Serial.println(commandstring); Serial.print("\n");}                         //analyse command string and place info into motor1 or motor2 'struct's           if(analyse_command_string(commandstring) == -1) n = 0;        }        } //END OF USB_SERIAL PORT SECTION #endif } // -------------------------- SERIAL COMMANDS ------------------------------------------ #if defined(USB_SERIAL) //CODE BELOW HERE NEEDED ONLY FOR CONTROL VIA USB_SERIAL PORT int analyse_command_string(char cstring[]) {         int x = 0;//    char s[20];        //Strip all spaces that might be in the command string    stripallspaces(cstring);         //Look for Start winder enable/disable    if (toupper(cstring[0]) == 'P')       {       s[0] = cstring[1]; s[1] = '\0';       if(strcmp(s,"1") == 0) Startup = 1;       if(strcmp(s,"0") == 0) Startup = 0;      // Serial.println("CF1!");       return 0;       }         //Look for winder run/stop command    if (toupper(cstring[0]) == 'R')       {       s[0] = cstring[1]; s[1] = '\0';       if(strcmp(s,"1") == 0) Run = 1;       if(strcmp(s,"0") == 0) Run = 0;       Serial.println("OK!");       return 0;       }          //Look for test enable/disable        if (toupper(cstring[0]) == 'E') //E for Echo was T for Test - all test statements have been scripted out       {      s[0] = cstring[1]; s[1] = '\0';      if(strcmp(s,"+") == 0) test = ON;       if(strcmp(s,"0") == 0) test = OFF;     return 0;      }       //====================================================================================================================== //Input string should arrive in the format of 255O255| // the first 3 characters are the Slave device address // Capital Letter "O" designates an output function // the remainder is the digital value to be transmitted over an RS485 Link // followed by a termination character "|" // used to generate a message of ID, Function, value //All other commands must begin with a SlaveID number/character    //Get SlaveID    s[0] = cstring[0]; s[1] = '\0'; SlaveID = atoi(s);       //The second character defines the parameter that is to be set   //** i want this to be the fourth as i want 255 addresses and not just 9.      //Ensure that this is in upper case    cstring[1] = toupper(cstring[1]);  //this is the function character            //Now search string for the function parameters   if (cstring[1] == 'O') //Send DigitalOutput value       {       x = 0; while(cstring[2+x] !='|'){s[x] = cstring[2+x]; x++;}       s[x] = '\0';       DigitalVal = (unsigned long)atol(s);  //note use of 'long int' here       //if (motorID == 1) motor1.interval = interval; else motor2.interval = interval;      Serial.print(SlaveID);      Serial.print(" ");      Serial.print(DigitalVal);       return 0;       }       //=====================================================================================================================          //Should not get to here so print error    Serial.print("ERROR: Unrecognised command\n"); return -1; } char *stripallspaces( char *s ) {    //Strips ALL spaces from string 's'    char s1[256];    int c0 = 0;    int c1 = 0;    while ( s[c0] != '\0' )        {        while( s[c0] == ' ' ) c0++;            s1[c1] = s[c0];            c0++;            c1++;        }    s1[c1] = '\0';    strcpy( s, s1 );    return &s[0]; } //------------------------------------------------------------------------------------------------------------------------------------------------- #endif    // END OF CODE NEEDED FOR CONTROL VIA USB_SERIAL PORT PaulS Quote Input string should arrive in the format of 255O255| Why? 255,O,255| would be a lot simpler to parse. JT007 Hi Paul, You are absolutely right. i was going down the road of manipulating the code i had already. comma delimited does make a lot of sense. It looks like im going back to rewriting a hole heap of code. I was hoping that there would be a straight forward solution like SlaveID=mid(cstring,0,3) - good old VB ahh well back to the drawing board cheers J. PaulS Quote I was hoping that there would be a straight forward solution like SlaveID=mid(cstring,0,3) - good old VB If the slave ID will always be three characters, then strncpy() will copy three characters to another array. You can then append a NULL and use atoi() to get a numeric value. Go Up   Please enter a valid email to subscribe Confirm your email address We need to confirm your email address. To complete the subscription, please click the link in the email we just sent you. Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
__label__pos
0.773392
ogg_afh.c: Rename oggbuf_len to inbuf_size [paraslash.git] / ogg_afh.c 1 /* 2 * Copyright (C) 2004-2007 Andre Noll <[email protected]> 3 * 4 * This program is free software; you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation; either version 2 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program; if not, write to the Free Software 16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA. 17 */ 18 /** \file ogg_afh.c para_server's ogg vorbis audio format handler */ 19 20 #include <inttypes.h> 21 #include <ogg/ogg.h> 22 #include <vorbis/codec.h> 23 #include <vorbis/vorbisfile.h> 24 25 #include "server.cmdline.h" 26 #include "server.h" 27 #include "vss.h" 28 #include "afh.h" 29 #include "error.h" 30 #include "string.h" 31 32 /** must be big enough to hold header */ 33 #define CHUNK_SIZE 32768 34 static double chunk_time = 0.25; 35 36 static OggVorbis_File *oggvorbis_file; 37 static FILE *infile; 38 static int header_len, inbuf_size, vi_channels; 39 static char *header, *inbuf; 40 static ssize_t *chunk_table, max_chunk_len; 41 static struct audio_format_handler *af; 42 static long vi_sampling_rate, vi_bitrate, vi_bitrate_nominal, 43 num_chunks; 44 45 static int ogg_compute_header_len(void) 46 { 47 int ret, len, in = fileno(infile); 48 unsigned int serial; 49 char *buf; 50 ogg_page page; 51 ogg_packet packet; 52 vorbis_comment vc; 53 vorbis_info vi; 54 ogg_stream_state *stream_in = para_malloc(sizeof(ogg_stream_state)); 55 ogg_stream_state *stream_out = para_malloc(sizeof(ogg_stream_state)); 56 ogg_sync_state *sync_in = para_malloc(sizeof(ogg_sync_state)); 57 58 ogg_sync_init(sync_in); 59 vorbis_info_init(&vi); 60 vorbis_comment_init(&vc); 61 buf = ogg_sync_buffer(sync_in, CHUNK_SIZE); 62 len = read(in, buf, CHUNK_SIZE); 63 ret = -E_OGG_READ; 64 if (len <= 0) 65 goto err1; 66 ogg_sync_wrote(sync_in, len); 67 ret = -E_SYNC_PAGEOUT; 68 if (ogg_sync_pageout(sync_in, &page) <= 0) 69 goto err1; 70 serial = ogg_page_serialno(&page); 71 ogg_stream_init(stream_in, serial); 72 ogg_stream_init(stream_out, serial); 73 ret = ogg_stream_pagein(stream_in, &page); 74 if (ret < 0) { 75 ret = E_STREAM_PAGEIN; 76 goto err2; 77 } 78 ret = ogg_stream_packetout(stream_in, &packet); 79 if (ret != 1) { 80 ret = -E_STREAM_PACKETOUT; 81 goto err2; 82 } 83 ret = -E_VORBIS; 84 if (vorbis_synthesis_headerin(&vi, &vc, &packet) < 0) 85 goto err2; 86 PARA_INFO_LOG("channels: %i, rate: %li\n", vi.channels, vi.rate); 87 ogg_stream_packetin(stream_out, &packet); 88 89 ret = ogg_sync_pageout(sync_in, &page); 90 if (ret <= 0) { 91 ret = -E_SYNC_PAGEOUT; 92 goto err2; 93 } 94 ogg_stream_pagein(stream_in, &page); 95 ogg_stream_packetout(stream_in, &packet); 96 ogg_stream_packetin(stream_out, &packet); 97 98 ret = ogg_sync_pageout(sync_in, &page); 99 if (ret <= 0) { 100 ret = -E_SYNC_PAGEOUT; 101 goto err2; 102 } 103 ogg_stream_pagein(stream_in, &page); 104 ogg_stream_packetout(stream_in, &packet); 105 ogg_stream_packetin(stream_out, &packet); 106 107 header_len = 0; 108 while (ogg_stream_flush(stream_out, &page)) 109 header_len += page.body_len + page.header_len; 110 ret = len; 111 PARA_INFO_LOG("header_len = %d\n", header_len); 112 err2: 113 ogg_stream_destroy(stream_in); 114 ogg_stream_destroy(stream_out); 115 err1: 116 ogg_sync_destroy(sync_in); 117 vorbis_info_clear(&vi); 118 vorbis_comment_clear(&vc); 119 return ret; 120 } 121 122 static void tunetable(void) 123 { 124 int i = 1, j = -1, lp = 1; 125 while (i < num_chunks) { 126 if (chunk_table[i] == chunk_table[lp]) { 127 i++; 128 continue; 129 } 130 if (j < 0) 131 tv_scale(i, &af->chunk_tv, &af->eof_tv); 132 for (j = lp; j < i; j++) 133 chunk_table[j] = chunk_table[i]; 134 lp = i; 135 } 136 #if 1 137 for (i = 2; i < num_chunks; i++) 138 if (chunk_table[i] != chunk_table[1]) 139 break; 140 lp = i; 141 for (i = 2; i < num_chunks - lp; i++) 142 chunk_table[i] = chunk_table[i + lp]; 143 #endif 144 } 145 146 147 /* 148 * Alloc and fill array table of byte offsets. chunk_table[i] is the 149 * offset in the current infile at which the sample containing time i * 150 * CHUNK_TIME begins. 151 */ 152 static void ogg_compute_chunk_table(double time_total) 153 { 154 int i, ret, num; 155 ssize_t pos = 0, min = 0, old_pos; 156 157 old_pos = 0; 158 ret = 0; 159 num = time_total / chunk_time + 3; 160 PARA_DEBUG_LOG("chunk time: %g allocating %d chunk pointers\n", 161 chunk_time, num); 162 chunk_table = para_malloc(num * sizeof(size_t)); 163 chunk_table[0] = 0; 164 max_chunk_len = 0; 165 rewind(infile); 166 for (i = 1; ret == 0; i++) { 167 ogg_int64_t diff; 168 ret = ov_time_seek(oggvorbis_file, i * chunk_time); 169 if (ret) 170 break; 171 pos = ov_raw_tell(oggvorbis_file); 172 diff = pos - old_pos; 173 max_chunk_len = PARA_MAX(max_chunk_len, diff); 174 min = (i == 1)? diff : PARA_MIN(min, diff); 175 chunk_table[i] = pos; 176 if (i < 11 || !((i - 1) % 1000)|| i > num - 11) 177 PARA_DEBUG_LOG("chunk #%d: %g secs, pos: %zd, " 178 "size: %zd\n", i - 1, 179 i * chunk_time, pos, pos - old_pos); 180 old_pos = pos; 181 } 182 num_chunks = i - 1; 183 chunk_table[i] = pos; 184 tunetable(); 185 PARA_INFO_LOG("%li chunks (%fs), max chunk: %zd, min chunk: %zd\n", 186 num_chunks, chunk_time, max_chunk_len, min); 187 rewind(infile); 188 } 189 190 static void ogg_close_audio_file(void) 191 { 192 if (oggvorbis_file) { 193 PARA_DEBUG_LOG("%s", "ov_clear\n"); 194 ov_clear(oggvorbis_file); 195 free(oggvorbis_file); 196 oggvorbis_file = NULL; 197 } 198 free(header); 199 header = NULL; 200 header_len = 0; 201 free(chunk_table); 202 chunk_table = NULL; 203 num_chunks = 0; 204 free(inbuf); 205 inbuf = NULL; 206 inbuf_size = 0; 207 } 208 209 static int ogg_save_header(FILE *file, int len) 210 { 211 int ret; 212 213 header = para_malloc(len); 214 rewind(file); 215 ret = read(fileno(file), header, len); 216 if (ret != len) 217 return -E_OGG_READ; 218 return 1; 219 } 220 221 /* 222 * Init oggvorbis file and write some tech data to given pointers. 223 */ 224 static int ogg_get_file_info(FILE *file, char *info_str, long unsigned *frames, 225 int *seconds) 226 { 227 int ret; 228 double time_total; 229 vorbis_info *vi; 230 ogg_int64_t raw_total; 231 232 infile = file; 233 if (!file) 234 return -E_OGG_NO_FILE; 235 ret = ogg_compute_header_len(); 236 if (ret < 0) 237 return ret; 238 ret = ogg_save_header(file, header_len); 239 if (ret < 0) 240 return ret; 241 rewind(file); 242 oggvorbis_file = para_malloc(sizeof(OggVorbis_File)); 243 ret = ov_open(file, oggvorbis_file, NULL, 0); 244 if (ret < 0) { 245 free(oggvorbis_file); 246 free(header); 247 return -E_OGG_OPEN; 248 } 249 ret = -E_OGG_INFO; 250 vi = ov_info(oggvorbis_file, 0); 251 if (!vi) 252 goto err; 253 time_total = ov_time_total(oggvorbis_file, -1); 254 raw_total = ov_raw_total(oggvorbis_file, -1); 255 *seconds = time_total; 256 vi_sampling_rate = vi->rate; 257 vi_bitrate = ov_bitrate(oggvorbis_file, 0); 258 vi_bitrate_nominal = vi->bitrate_nominal; 259 vi_channels = vi->channels; 260 ogg_compute_chunk_table(time_total); 261 *frames = num_chunks; 262 sprintf(info_str, "audio_file_info1:%lu x %lu, %ldkHz, %d channels, %ldkbps\n" 263 "audio_file_info2: \n" 264 "audio_file_info3: \n", 265 num_chunks, (long unsigned) (chunk_time * 1000 * 1000), 266 vi_sampling_rate / 1000, vi_channels, vi_bitrate / 1000 267 ); 268 rewind(file); 269 return 1; 270 err: 271 ogg_close_audio_file(); 272 return ret; 273 } 274 275 /* 276 * Simple stream reposition routine 277 */ 278 static int ogg_reposition_stream(long unsigned request) 279 { 280 int ret; 281 long seek; 282 283 seek = chunk_table[request]; 284 ret = fseek(infile, seek, SEEK_SET); 285 PARA_DEBUG_LOG("seek to %li returned %d. offset:%li\n", seek, 286 ret, ftell(infile)); 287 return ret < 0? -E_OGG_REPOS : 1; 288 } 289 290 static ogg_int64_t get_chunk_size(long unsigned chunk_num) 291 { 292 ogg_int64_t ret; 293 if (chunk_num >= num_chunks) 294 return -1; 295 ret = chunk_table[chunk_num + 1] - chunk_table[chunk_num]; 296 if (!ret) 297 return ret; 298 #if 0 299 PARA_DEBUG_LOG("chunk %d: %lli-%lli (%lli bytes)\n", 300 chunk_num, 301 chunk_table[chunk_num], 302 chunk_table[chunk_num + 1] - 1, 303 ret); 304 #endif 305 return ret; 306 } 307 308 static char *ogg_read_chunk(long unsigned current_chunk, ssize_t *len) 309 { 310 int ret; 311 ogg_int64_t cs = get_chunk_size(current_chunk); 312 if (!cs) { /* nothing to send for this run */ 313 *len = 0; 314 return inbuf; 315 } 316 if (cs < 0) { /* eof */ 317 *len = 0; 318 return NULL; 319 } 320 *len = cs; 321 if (!inbuf || inbuf_size < *len) { 322 PARA_INFO_LOG("increasing ogg buffer size (%d -> %zu)\n", 323 inbuf_size, *len); 324 inbuf = para_realloc(inbuf, *len); 325 inbuf_size = *len; 326 } 327 ret = read(fileno(infile), inbuf, *len); 328 if (!ret) { 329 *len = 0; 330 return NULL; 331 } 332 if (ret < 0) { 333 *len = -E_OGG_READ; 334 return NULL; 335 } 336 if (ret != *len) 337 PARA_WARNING_LOG("short read (%d/%zd)\n", ret, *len); 338 *len = ret; 339 return inbuf; 340 } 341 342 static char *ogg_get_header_info(int *len) 343 { 344 *len = header_len; 345 return header; 346 } 347 348 static const char* ogg_suffixes[] = {"ogg", NULL}; 349 350 /** 351 * the init function of the ogg vorbis audio format handler 352 * 353 * \param p pointer to the struct to initialize 354 */ 355 void ogg_init(struct audio_format_handler *p) 356 { 357 af = p; 358 af->reposition_stream = ogg_reposition_stream; 359 af->get_file_info = ogg_get_file_info, 360 af->read_chunk = ogg_read_chunk; 361 af->close_audio_file = ogg_close_audio_file; 362 af->get_header_info = ogg_get_header_info; 363 af->chunk_tv.tv_sec = 0; 364 af->chunk_tv.tv_usec = 250 * 1000; 365 tv_scale(3, &af->chunk_tv, &af->eof_tv); 366 af->suffixes = ogg_suffixes; 367 }
__label__pos
0.995553
Source: https://www.confluent.io/ Introduction Let’s start by answering the question “What is Kafka?”. Kafka is a Distributed Streaming Platform or a Distributed Commit Log Let’s try to understand those jargons. Distributed Kafka works as a cluster of one or more nodes that can live in different Datacenters, we can distribute data/ load across different nodes in the Kafka Cluster, and it is inherently scalable, available, and fault-tolerant. Streaming Platform Kafka stores data as a stream of continuous records which can be processed in different methods. Commit Log This one is my favorite. When you push data to Kafka it takes and appends them to a stream of records, like appending logs in a log file or if you’re from a Database background like the WAL. This stream of data can be “Replayed” or read from any point in time. Is Kafka a message queue? It certainly can act as a message queue, but it’s not limited to that. It can act as a FIFO queue, as a Pub/ Sub messaging system, a real-time streaming platform. And because of the durable storage capability of Kafka, it can even be used as a Database (read about it here). Having said all of that, Kafka is commonly used for real-time streaming data pipelines, i.e. to transfer data between systems, building systems that transform continuously flowing data, and building event-driven systems. We will jump into core Kafka concepts now. Message A message is the atomic unit of data for Kafka. Let’s say that you are building a log monitoring system, and you push each log record into Kafka, your log message is a JSON that has this structure. When you push this JSON into Kafka you are actually pushing 1 message. Kafka saves this JSON as a byte array, and that byte array is a message for Kafka. This is that atomic unit, a JSON having two keys “level” and “message”. But it does not mean you can’t push anything else into Kafka, you can push String, Integer, a JSON of different schema, and everything else, but we generally push different types of messages into different topics (we will get to know what is a topic soon). Messages might have an associated “Key” which is nothing but some metadata, which is used to determine the destination partition (will know soon as well) for a message. Topic Topics, as the name suggests, are the logical categories of messages in Kafka, a stream of the same type of data. Going back to our previous example of the logging system, let’s say our system generates application logs, ingress logs, and database logs and pushes them to Kafka for other services to consume. Now, these three types of logs can be logically be divided into three topics, appLogs, ingressLogs, and dbLogs. We can create these three topics in Kafka, whenever there’s an app log message, we push it to appLogs topic and for database logs, we push it to the dbLogs topic. This way we have logical segregation between messages, sort of like having different tables for holding different types of data. Partitions Partition is analogous to shard in the database and is the core concept behind Kafka’s scaling capabilities. Let’s say that our system becomes really popular and hence there are millions of log messages per second. So now the node on which appLogs topic is present, is unable to hold all the data that is coming in. We initially solve this by adding more storage to our node i.e. vertical scaling. But as we all know vertical scaling has its limit, once that threshold is reached we need to horizontally scale, which means we need to add more nodes and split the data between the nodes. When we split data of a topic into multiple streams, we call all of those smaller streams the “Partition” of that topic. Source: Kafka The Definitive Guide This image depicts the idea of partitions, where a single topic has 4 partitions, and all of them hold a different set of data. The blocks you see here are the different messages in that partition. Let’s imagine the topic to be an array, now due to memory constraint we have split the single array into 4 different smaller arrays. And when we write a new message to a topic, the relevant partition is selected and then that message is added at the end of the array. An offset for a message is the index of the array for that message. The numbers on the blocks in this picture denote the Offset, the first block is at the 0th offset and the last block would on the (n-1)th offset. The performance of the system also depends on the ways you set up partitions, we will look into that later in the article. (Please note that on Kafka it is not going to be an actual array but a symbolic one) Producer A producer is the Kafka client that publishes messages to a Kafka topic. Also one of the core responsibilities of the Producer is to decide which partition to send the messages to. Depending on various configuration and parameters, the producer decides the destination partition, let’s look a bit more into this. 1. No Key specified => When no key is specified in the message the producer will randomly decide partition and would try to balance the total number of messages on all partitions. 2. Key Specified => When a key is specified with the message, then the producer uses Consistent Hashing to map the key to a partition. Don’t worry if you don’t know what consistent hashing is, in short, it’s a hashing mechanism where for the same key same hash is generated always, and it minimizes the redistribution of keys on a re-hashing scenario like a node add or a node removal to the cluster. So let’s say in our logging system we use source node ID as the key, then the logs for the same node will always go to the same partition. This is very relevant for the order guarantees of messages in Kafka, we will shortly see how. 3. Partition Specified => You can hardcode the destination partition as well. 4. Custom Partitioning logic => We can write some rules depending on which the partition can be decided. Consumer So far we have produced messages, to read those messages we use Kafka consumer. A consumer reads messages from partitions, in an ordered fashion. So if 1, 2, 3, 4 was inserted into a topic, the consumer will read it in the same order. Since every message has an offset, every time a consumer reads a message it stores the offset value onto Kafka or Zookeeper, denoting that it is the last message that the consumer read. So in case, a consumer node goes down, it can come back and resume from the last read position. Also if at any point in time a consumer needs to go back in time and read older messages, it can do so by just resetting the offset position. Consumer Group A consumer group is a collection of consumers that work together to read messages from a topic. There are some very interesting concepts here, let’s go through them. 1. Fan out exchange => A single topic can be subscribed to by multiple consumer groups. Let’s say that you are building an OTP service. Now you need to send both text and email OTP. So your OTP service can put the OTP in Kafka, and then the SMS Service consumer group and Email Service consumer group can both receive the message and can then send the SMS and email out. 2. Order guarantee => Now we have seen that a topic can be partitioned and multiple consumers can consumer from the same topic, then how do you maintain the order of messages on the consumer-end one might ask. Good question. One partition can not be read by multiple consumers in the same consumer group. This is enabled by the consumer group only, only one consumer in the group gets to read from a single partition. Let me explain. So your producer produces 6 messages. Each message is a key-value pair, for key “A” value is “1”, for “C” value is “1”, for “B” value is “1”, for “C” value is “2” ….. “B” value is “2”. (Please note that by key I mean the message key that we discussed earlier and not the JSON or Map key). Our topic has 3 partitions, and due to consistent hashing messages with the same key always go to the same partition, so all the messages with “A” as the key will get grouped and the same for B and C. Now as each partition has only one consumer, they get messages in order only. So the consumer will receive A1 before A2 and B1 before B2, and thus the order is maintained, tada 🎉. Going back to our logging system example the keys are the source node ID, then all the logs for node1 will go to the same partition always. And since the messages are always going to the same partition, we will have the order of the messages maintained. This will not be possible if the same partition had multiple consumers in the same group. If you read the same partition in the different consumers who are in different groups, then also for each consumer group the messages will end up ordered. So for 3 partitions, you can have a max of 3 consumers, if you had 4 consumers, one consumer will be sitting idle. But for 3 partitions you can have 2 consumers, then one consumer will read from one partition and one consumer will read from two partitions. If one consumer goes down in this case, the last surviving consumer will end up reading from all the three partitions, and when new consumers are added back, again partition would be split between consumers, this is called re-balancing. Source: Kafka The Definitive Guide Broker A broker is a single Kafka server. Brokers receive messages from producers, assigns offset to them, and then commit them to the partition log, which is basically writing data to disk, and this gives Kafka its durable nature. Cluster A Kafka cluster is a group of broker nodes working together to provide, scalability, availability, and fault tolerance. One of the brokers in a cluster works as the Controller, which basically assigns partitions to brokers, monitors for broker failure to do certain administrative stuff. In a cluster, partitions are replicated on multiple brokers depending on the replication factor of the topic to have failover capability. What I mean is, for a topic of replication factor 3, each partition of that topic will live onto 3 different brokers. When a partition is replicated onto 3 brokers, one of the brokers will act as the leader for that partition and the rest two will be followers. Data is always written on the leader broker and then replicated to the followers. This way we do not lose data nor availability of the cluster, and if the leader goes down another leader is elected Let’s look at a practical example. I am running a 5 node Kafka cluster locally and I run this command kafka-topics — create — zookeeper zookeeper:2181 — topic applog — partitions 5 — replication-factor 3 If we break down the command, it becomes 1. Create a topic 2. Create 5 partitions of that topic 3. And replicate data of all 5 partitions into a total of 3 nodes This screenshot describes the topic we just created. Let’s take Partition 0, the leader node for this partition is node 2. The data for this partition is replicated on nodes 2,5 and 1.S o one partition is replicated on 3 nodes and this behavior is repeated for all 5 partitions. And also if you see, all the leader nodes for each partition are different. So to utilize the nodes properly, the Kafka controller broker distributed the partitions evenly across all nodes. And you can also observe the replications are also evenly distributed and no node is overloaded. All of these are done by the controller Broke with the help of Zookeeper. Since you have understood clustering now, you can see to scale we could partition a topic even more and for each partition, we could add a dedicated consumer node, and that way we can horizontally scale. Zookeeper Kafka does not function without zookeeper( at least for now, they have plans to deprecate zookeeper in near future). Zookeeper works as the central configuration and consensus management system for Kafka. It tracks the brokers, topics, and partition assignment, leader election, basically all the metadata about the cluster. And these my friend were the basic and core concepts of Kafka. Beyond basics There are a few more things that are slightly advanced that you should know, I would not go into details and just touch upon, cause I don’t want to overload you with so much information in one shot. Producer You can send messages in 3 ways to Kafka. • Fire and forget • Synchronous send • Asynchronous send. All of them have their performance vs consistency pitfalls. You can configure characteristics of acknowledgment on the producer as well. • ACK 0: Don’t wait for an ack |FASTEST • ACK 1: Consider sent when leader broker received the message |FASTER • ACK All: Consider sent when all replicas received the message |FAST You can compress and batch messages on producer before sendig to broker. It gives high throughput and lowers disk usage but raises CPU usage. Avro Serializer/ Deserializer If you use Avro as the serializer/ deserializer instead of normal JSON, you will have to declare your schema upfront but this gives better performance and saves storage. Consumer Poll loop Kafka consumer constantly polls data from the broker and it’s no the other way round. You can configure partition assignment strategy • Range: Consumer gets consecutive partitions • Round Robin: Self-explanatory • Sticky: Tries to create minimum impact while rebalancing keeping most of the assignment as is • Cooperative sticky: Sticky but allows cooperative rebalancing Batch size We can configure how many records and how much data is returned per poll call. Commit offset On message read we can update the offset position for the consumer, this is called committing the offset. Auto commit can be enabled or the application can commit the offset explicitly. This can be done both synchronously and asynchronously. Ending notes Kafka is a great piece of software and has tons of capabilities and can be used in various sets of use cases. Kafka fits great into Modern-day Distributed Systems due to it being distributed by design. It was originally founded at LinkedIn and is currently maintained by Confluent. It is used by top tech companies like Uber, Netflix, Activision, Spotify, Slack, Pinterest, Coursera. We looked into the core concepts of Kafka to get you started. There are tons of other things like Kafka Stream API or kSql that we did not talk about in the interest of time. References 1. Kafka the Definitive Guide 2. https://www.confluent.io/blog/apache-kafka-intro-how-kafka-works/ [This article was originally published on hackernoon] Thanks for reading!!! I am Aritra Das, I work as a Software Developer, and really enjoy building Distributed Systems. Feel free to reach out to me on Linkedin or Twitter for anything related to tech. Happy learning 😃
__label__pos
0.754449
Data Manipulation in R Subset Data Frame Rows in R This tutorial describes how to subset or extract data frame rows based on certain criteria. In this tutorial, you will learn the following R functions from the dplyr package: • slice(): Extract rows by position • filter(): Extract rows that meet a certain logical criteria. For example iris %>% filter(Sepal.Length > 6). • filter_all(), filter_if() and filter_at(): filter rows within a selection of variables. These functions replicate the logical criteria over all variables or a selection of variables. • sample_n(): Randomly select n rows • sample_frac(): Randomly select a fraction of rows • top_n(): Select top n rows ordered by a variable We will also show you how to remove rows with missing values in a given column. Subsetting Data Frame Rows in R Contents: Required packages Load the tidyverse packages, which include dplyr: library(tidyverse) Demo dataset We’ll use the R built-in iris data set, which we start by converting into a tibble data frame (tbl_df) for easier data analysis. my_data <- as_tibble(iris) my_data ## # A tibble: 150 x 5 ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## <dbl> <dbl> <dbl> <dbl> <fct> ## 1 5.1 3.5 1.4 0.2 setosa ## 2 4.9 3 1.4 0.2 setosa ## 3 4.7 3.2 1.3 0.2 setosa ## 4 4.6 3.1 1.5 0.2 setosa ## 5 5 3.6 1.4 0.2 setosa ## 6 5.4 3.9 1.7 0.4 setosa ## # ... with 144 more rows Extract rows by position • Key R function: slice() [dplyr package] my_data %>% slice(1:6) Filter rows by logical criteria • Key R function: filter() [dplyr package]. Used to filter rows that meet some logical criteria. Before continuing, we introduce logical comparisons and operators, which are important to know for filtering data. Logical comparisons The “logical” comparison operators available in R are: 1. Logical comparisons • <: for less than • >: for greater than • <=: for less than or equal to • >=: for greater than or equal to • ==: for equal to each other • !=: not equal to each other • %in%: group membership. For example, “value %in% c(2, 3)” means that value can takes 2 or 3. • is.na(): is NA • !is.na(): is not NA. 2. Logical operators • value == 2|3: means that the value equal 2 or (|) 3. value %in% c(2, 3) is a shortcut equivalent to value == 2|3. • &: means and. For example sex == “female” & age > 25 The most frequent mistake made by beginners in R is to use = instead of == when testing for equality. Remember that, when you are testing for equality, you should always use == (not =). Extract rows based on logical criteria • One-column based criteria: Extract rows where Sepal.Length > 7: my_data %>% filter(Sepal.Length > 7) ## # A tibble: 12 x 5 ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## <dbl> <dbl> <dbl> <dbl> <fct> ## 1 7.1 3 5.9 2.1 virginica ## 2 7.6 3 6.6 2.1 virginica ## 3 7.3 2.9 6.3 1.8 virginica ## 4 7.2 3.6 6.1 2.5 virginica ## 5 7.7 3.8 6.7 2.2 virginica ## 6 7.7 2.6 6.9 2.3 virginica ## # ... with 6 more rows • Multiple-column based criteria: Extract rows where Sepal.Length > 6.7 and Sepal.Width ≤ 3: my_data %>% filter(Sepal.Length > 6.7, Sepal.Width <= 3) ## # A tibble: 10 x 5 ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## <dbl> <dbl> <dbl> <dbl> <fct> ## 1 6.8 2.8 4.8 1.4 versicolor ## 2 7.1 3 5.9 2.1 virginica ## 3 7.6 3 6.6 2.1 virginica ## 4 7.3 2.9 6.3 1.8 virginica ## 5 6.8 3 5.5 2.1 virginica ## 6 7.7 2.6 6.9 2.3 virginica ## # ... with 4 more rows • Test for equality (==): Extract rows where Sepal.Length > 6.5 and Species = “versicolor”: my_data %>% filter(Sepal.Length > 6.7, Species == "versicolor") ## # A tibble: 3 x 5 ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## <dbl> <dbl> <dbl> <dbl> <fct> ## 1 7 3.2 4.7 1.4 versicolor ## 2 6.9 3.1 4.9 1.5 versicolor ## 3 6.8 2.8 4.8 1.4 versicolor • Using OR operator (|): Extract rows where Sepal.Length > 6.5 and (Species = “versicolor” or Species = “virginica”): Use this: my_data %>% filter( Sepal.Length > 6.7, Species == "versicolor" | Species == "virginica" ) ## # A tibble: 20 x 5 ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## <dbl> <dbl> <dbl> <dbl> <fct> ## 1 7 3.2 4.7 1.4 versicolor ## 2 6.9 3.1 4.9 1.5 versicolor ## 3 6.8 2.8 4.8 1.4 versicolor ## 4 7.1 3 5.9 2.1 virginica ## 5 7.6 3 6.6 2.1 virginica ## 6 7.3 2.9 6.3 1.8 virginica ## # ... with 14 more rows Or, equivalently, use this shortcut (%in% operator): my_data %>% filter( Sepal.Length > 6.7, Species %in% c("versicolor", "virginica" ) ) Filter rows within a selection of variables This section presents 3 functions - filter_all(), filter_if() and filter_at() - to filter rows within a selection of variables. These functions replicate the logical criteria over all variables or a selection of variables. Create a new demo data set from my_data by removing the grouping column “Species”: my_data2 <- my_data %>% select(-Species) • Select rows where all variables are greater than 2.4: my_data2 %>% filter_all(all_vars(.> 2.4)) ## # A tibble: 3 x 4 ## Sepal.Length Sepal.Width Petal.Length Petal.Width ## <dbl> <dbl> <dbl> <dbl> ## 1 6.3 3.3 6 2.5 ## 2 7.2 3.6 6.1 2.5 ## 3 6.7 3.3 5.7 2.5 • Select rows when any of the variables are greater than 2.4: my_data2 %>% filter_all(any_vars(.> 2.4)) ## # A tibble: 150 x 4 ## Sepal.Length Sepal.Width Petal.Length Petal.Width ## <dbl> <dbl> <dbl> <dbl> ## 1 5.1 3.5 1.4 0.2 ## 2 4.9 3 1.4 0.2 ## 3 4.7 3.2 1.3 0.2 ## 4 4.6 3.1 1.5 0.2 ## 5 5 3.6 1.4 0.2 ## 6 5.4 3.9 1.7 0.4 ## # ... with 144 more rows • Vary the selection of columns on which to apply the filtering criteria. filter_at() takes a vars() specification. The following R code apply the filtering criteria on the columns Sepal.Length and Sepal.Width: my_data2 %>% filter_at(vars(starts_with("Sepal")), any_vars(. > 2.4)) ## # A tibble: 150 x 4 ## Sepal.Length Sepal.Width Petal.Length Petal.Width ## <dbl> <dbl> <dbl> <dbl> ## 1 5.1 3.5 1.4 0.2 ## 2 4.9 3 1.4 0.2 ## 3 4.7 3.2 1.3 0.2 ## 4 4.6 3.1 1.5 0.2 ## 5 5 3.6 1.4 0.2 ## 6 5.4 3.9 1.7 0.4 ## # ... with 144 more rows Remove missing values We start by creating a data frame with missing values. In R NA (Not Available) is used to represent missing values: # Create a data frame with missing data friends_data <- data_frame( name = c("A", "B", "C", "D"), age = c(27, 25, 29, 26), height = c(180, NA, NA, 169), married = c("yes", "yes", "no", "no") ) # Print friends_data ## # A tibble: 4 x 4 ## name age height married ## <chr> <dbl> <dbl> <chr> ## 1 A 27 180 yes ## 2 B 25 NA yes ## 3 C 29 NA no ## 4 D 26 169 no Extract rows where height is NA: friends_data %>% filter(is.na(height)) ## # A tibble: 2 x 4 ## name age height married ## <chr> <dbl> <dbl> <chr> ## 1 B 25 NA yes ## 2 C 29 NA no Exclude (drop) rows where height is NA: friends_data %>% filter(!is.na(height)) ## # A tibble: 2 x 4 ## name age height married ## <chr> <dbl> <dbl> <chr> ## 1 A 27 180 yes ## 2 D 26 169 no In the R code above, !is.na() means that “we don’t want” NAs. Select random rows from a data frame It’s possible to select either n random rows with the function sample_n() or a random fraction of rows with sample_frac(). We first use the function set.seed() to initiate random number generator engine. This important for users to reproduce the analysis. set.seed(1234) # Extract 5 random rows without replacement my_data %>% sample_n(5, replace = FALSE) # Extract 5% of rows, randomly without replacement my_data %>% sample_frac(0.05, replace = FALSE) Select top n rows ordered by a variable Select the top 5 rows ordered by Sepal.Length my_data %>% top_n(5, Sepal.Length) ## # A tibble: 5 x 5 ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## <dbl> <dbl> <dbl> <dbl> <fct> ## 1 7.7 3.8 6.7 2.2 virginica ## 2 7.7 2.6 6.9 2.3 virginica ## 3 7.7 2.8 6.7 2 virginica ## 4 7.9 3.8 6.4 2 virginica ## 5 7.7 3 6.1 2.3 virginica Group by the column Species and select the top 5 of each group ordered by Sepal.Length: my_data %>% group_by(Species) %>% top_n(5, Sepal.Length) ## # A tibble: 16 x 5 ## # Groups: Species [3] ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## <dbl> <dbl> <dbl> <dbl> <fct> ## 1 5.8 4 1.2 0.2 setosa ## 2 5.7 4.4 1.5 0.4 setosa ## 3 5.7 3.8 1.7 0.3 setosa ## 4 5.5 4.2 1.4 0.2 setosa ## 5 5.5 3.5 1.3 0.2 setosa ## 6 7 3.2 4.7 1.4 versicolor ## # ... with 10 more rows Summary In this tutorial, we introduce how to filter a data frame rows using the dplyr package: • Filter rows by logical criteria: my_data %>% filter(Sepal.Length >7) • Select n random rows: my_data %>% sample_n(10) • Select a random fraction of rows: my_data %>% sample_frac(10) • Select top n rows by values: my_data %>% top_n(10, Sepal.Length) Select Data Frame Columns in R (Prev Lesson) (Next Lesson) Identify and Remove Duplicate Data in R Back to Data Manipulation in R Comments ( 15 ) • Robert Mukiibi very good tutorial • Kassambara Thank you for your positive feedback, highly appreciated • Christoph I suppose the top_n function to sort the rows in descending order. If that’s correct, line 15 should be line 12 (since 7.9 > 7.7). See below. Why isn’t it the case? my_data %>% group_by(Species) %>% top_n(5, Sepal.Length) # A tibble: 16 x 5 # Groups: Species [3] Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.8 4 1.2 0.2 setosa 2 5.7 4.4 1.5 0.4 setosa 3 5.7 3.8 1.7 0.3 setosa 4 5.5 4.2 1.4 0.2 setosa 5 5.5 3.5 1.3 0.2 setosa 6 7 3.2 4.7 1.4 versicolor 7 6.9 3.1 4.9 1.5 versicolor 8 6.7 3.1 4.4 1.4 versicolor 9 6.8 2.8 4.8 1.4 versicolor 10 6.7 3 5 1.7 versicolor 11 6.7 3.1 4.7 1.5 versicolor 12 7.7 3.8 6.7 2.2 virginica 13 7.7 2.6 6.9 2.3 virginica 14 7.7 2.8 6.7 2 virginica 15 7.9 3.8 6.4 2 virginica 16 7.7 3 6.1 2.3 virginica • Kassambara Hi, The top_n() function doesn’t sort the data, it only pick the top n based on a variable. For sorting, use the function arrange() and then the top_n(). my_data %>% group_by(Species) %>% arrange(desc(Sepal.Length)) %>% top_n(5, Sepal.Length) • Ashmeel Hi Kassambara, This is very informative. Could you please let me know how could I pick up distinct rows if the values of the rows are same? Thanks & Regards, Ashmeel. • Ashmeel Got it! validCust %>% group_by(CUSTGRP) %>% top_n(1, AGE) %>% distinct(CUSTGRP, AGE) Thanks! Your blog is informative. • Kassambara It’s great that you find the answer to your question… Thank you for the positive feedback! Highly appreciated • Sasacat Hi, I have an off-topic question – from which place is the photo at the top of this site? • Kassambara The photo at the top of the site is from the “Saint Andéol” lake (Aubrac, Lozére, France) • Billy Hi! great tutorial, my only problem is when I subset my data I loose the row.names in the new dataframe. How to I preserve that information? • Kassambara In modern R programming (with tidyverse) each column should have a name. Yu can transform your row names into a column for preserving them. The function `rownames_to_column()` can be used: library(tidyverse) mtcars %>% rownames_to_column() %>% filter(mpg > 20) • Fabricio Thank you very much, that helped me a lot. • Jiali I can use top_on to extract the highest data from the data frame, what about the lowest one, which function should i use? • Kassambara If n is positive, top_n() selects the top n rows. If negative, selects the bottom n rows. • Ramesh Ramasamy Hi! great tutorial, Very informative. Highly useful. Thanks a lot. Post a Reply Teacher Alboukadel Kassambara Role : Founder of Datanovia Read More
__label__pos
0.762297
[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index] Re: should etch be Debian 4.0 ? Nigel Jones wrote: On 10/07/05, Thomas Hood <[email protected]> wrote: Are release numbers really needed? Why not do away with them altogether? you mean, just stick with code names? That wouldn't exactly work, Debian's apt/dpkg basicly relies on release numbers, how else can it easily and quickly realize that apache2-2.0.40 is older than apache2-2.0.50? I was obviously referring to the numbers assigned to releases of the operating system, not to releases of individual packages. -- Thomas Hood Reply to:
__label__pos
0.999996
CGAL 5.4 - Triangulated Surface Mesh Simplification Definition The concept StopPredicate describes the requirements for the predicate which indicates if the simplification process must finish. Has Models: CGAL::Surface_mesh_simplification::Count_stop_predicate<TriangleMesh> CGAL::Surface_mesh_simplification::Count_ratio_stop_predicate<TriangleMesh> CGAL::Surface_mesh_simplification::Edge_length_stop_predicate<FT> Operations bool operator() (const Edge_profile::FT &current_cost, const Edge_profile &profile, const Edge_profile::edges_size_type initial_edge_count, const Edge_profile::edges_size_type current_edge_count) const  This predicate is called each time an edge is selected for processing, before it is collapsed. More...   Member Function Documentation ◆ operator()() bool StopPredicate::operator() ( const Edge_profile::FT &  current_cost, const Edge_profile &  profile, const Edge_profile::edges_size_type  initial_edge_count, const Edge_profile::edges_size_type  current_edge_count  ) const This predicate is called each time an edge is selected for processing, before it is collapsed. current_edge_cost is the cost of the selected edge. initial_edge_count and current_edge_count are the number of initial and current edges. If the return value is true the simplification terminates before processing the edge, otherwise it continues normally.
__label__pos
0.510463
string.c   [plain text] /********************************************************************** string.c - $Author: jkh $ $Date: 2002/05/27 17:59:44 $ created at: Mon Aug 9 17:12:58 JST 1993 Copyright (C) 1993-2000 Yukihiro Matsumoto Copyright (C) 2000 Network Applied Communication Laboratory, Inc. Copyright (C) 2000 Information-technology Promotion Agency, Japan **********************************************************************/ #include "ruby.h" #include "re.h" #define BEG(no) regs->beg[no] #define END(no) regs->end[no] #include <math.h> #include <ctype.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif VALUE rb_cString; #define STR_NO_ORIG FL_USER2 VALUE rb_fs; VALUE rb_str_new(ptr, len) const char *ptr; long len; { NEWOBJ(str, struct RString); OBJSETUP(str, rb_cString, T_STRING); str->ptr = 0; str->len = len; str->orig = 0; str->ptr = ALLOC_N(char,len+1); if (ptr) { memcpy(str->ptr, ptr, len); } str->ptr[len] = '\0'; return (VALUE)str; } VALUE rb_str_new2(ptr) const char *ptr; { if (!ptr) { rb_raise(rb_eArgError, "NULL pointer given"); } return rb_str_new(ptr, strlen(ptr)); } VALUE rb_tainted_str_new(ptr, len) const char *ptr; long len; { VALUE str = rb_str_new(ptr, len); OBJ_TAINT(str); return str; } VALUE rb_tainted_str_new2(ptr) const char *ptr; { VALUE str = rb_str_new2(ptr); OBJ_TAINT(str); return str; } VALUE rb_str_new3(str) VALUE str; { NEWOBJ(str2, struct RString); OBJSETUP(str2, rb_cString, T_STRING); str2->len = RSTRING(str)->len; str2->ptr = RSTRING(str)->ptr; str2->orig = str; OBJ_INFECT(str2, str); return (VALUE)str2; } VALUE rb_str_new4(orig) VALUE orig; { VALUE klass; klass = CLASS_OF(orig); while (TYPE(klass) == T_ICLASS || FL_TEST(klass, FL_SINGLETON)) { klass = (VALUE)RCLASS(klass)->super; } if (RSTRING(orig)->orig) { VALUE str; if (FL_TEST(orig, STR_NO_ORIG)) { str = rb_str_new(RSTRING(orig)->ptr, RSTRING(orig)->len); } else { str = rb_str_new3(RSTRING(orig)->orig); } OBJ_FREEZE(str); RBASIC(str)->klass = klass; return str; } else { NEWOBJ(str, struct RString); OBJSETUP(str, klass, T_STRING); str->len = RSTRING(orig)->len; str->ptr = RSTRING(orig)->ptr; RSTRING(orig)->orig = (VALUE)str; str->orig = 0; OBJ_INFECT(str, orig); OBJ_FREEZE(str); return (VALUE)str; } } VALUE rb_str_to_str(str) VALUE str; { return rb_convert_type(str, T_STRING, "String", "to_str"); } static void rb_str_become(str, str2) VALUE str, str2; { if (str == str2) return; if (NIL_P(str2)) { RSTRING(str)->ptr = 0; RSTRING(str)->len = 0; RSTRING(str)->orig = 0; return; } if ((!RSTRING(str)->orig||FL_TEST(str,STR_NO_ORIG))&&RSTRING(str)->ptr) free(RSTRING(str)->ptr); RSTRING(str)->ptr = RSTRING(str2)->ptr; RSTRING(str)->len = RSTRING(str2)->len; RSTRING(str)->orig = RSTRING(str2)->orig; RSTRING(str2)->ptr = 0; /* abandon str2 */ RSTRING(str2)->len = 0; if (OBJ_TAINTED(str2)) OBJ_TAINT(str); } void rb_str_associate(str, add) VALUE str, add; { if (!FL_TEST(str, STR_NO_ORIG)) { if (RSTRING(str)->orig) { rb_str_modify(str); } RSTRING(str)->orig = rb_ary_new(); FL_SET(str, STR_NO_ORIG); } rb_ary_push(RSTRING(str)->orig, add); } static ID id_to_s; VALUE rb_obj_as_string(obj) VALUE obj; { VALUE str; if (TYPE(obj) == T_STRING) { return obj; } str = rb_funcall(obj, id_to_s, 0); if (TYPE(str) != T_STRING) return rb_any_to_s(obj); if (OBJ_TAINTED(obj)) OBJ_TAINT(str); return str; } VALUE rb_str_dup(str) VALUE str; { VALUE str2; VALUE klass; if (TYPE(str) != T_STRING) str = rb_str_to_str(str); klass = CLASS_OF(str); while (TYPE(klass) == T_ICLASS || FL_TEST(klass, FL_SINGLETON)) { klass = (VALUE)RCLASS(klass)->super; } if (OBJ_FROZEN(str)) str2 = rb_str_new3(str); else if (FL_TEST(str, STR_NO_ORIG)) { str2 = rb_str_new(RSTRING(str)->ptr, RSTRING(str)->len); } else if (RSTRING(str)->orig) { str2 = rb_str_new3(RSTRING(str)->orig); FL_UNSET(str2, FL_TAINT); OBJ_INFECT(str2, str); } else { str2 = rb_str_new3(rb_str_new4(str)); } OBJ_INFECT(str2, str); if (FL_TEST(str, FL_EXIVAR)) rb_clone_generic_ivar(str2, str); RBASIC(str2)->klass = klass; return str2; } static VALUE rb_str_clone(str) VALUE str; { VALUE clone = rb_str_dup(str); if (FL_TEST(str, STR_NO_ORIG)) RSTRING(clone)->orig = RSTRING(str)->orig; CLONESETUP(clone, str); return clone; } static VALUE rb_str_s_new(argc, argv, klass) int argc; VALUE *argv; VALUE klass; { VALUE str = rb_str_new(0, 0); OBJSETUP(str, klass, T_STRING); rb_obj_call_init(str, argc, argv); return str; } static VALUE rb_str_length(str) VALUE str; { return INT2NUM(RSTRING(str)->len); } static VALUE rb_str_empty(str) VALUE str; { if (RSTRING(str)->len == 0) return Qtrue; return Qfalse; } VALUE rb_str_plus(str1, str2) VALUE str1, str2; { VALUE str3; if (TYPE(str2) != T_STRING) str2 = rb_str_to_str(str2); str3 = rb_str_new(0, RSTRING(str1)->len+RSTRING(str2)->len); memcpy(RSTRING(str3)->ptr, RSTRING(str1)->ptr, RSTRING(str1)->len); memcpy(RSTRING(str3)->ptr + RSTRING(str1)->len, RSTRING(str2)->ptr, RSTRING(str2)->len); RSTRING(str3)->ptr[RSTRING(str3)->len] = '\0'; if (OBJ_TAINTED(str1) || OBJ_TAINTED(str2)) OBJ_TAINT(str3); return str3; } VALUE rb_str_times(str, times) VALUE str; VALUE times; { VALUE str2; long i, len; len = NUM2LONG(times); if (len == 0) return rb_str_new(0,0); if (len < 0) { rb_raise(rb_eArgError, "negative argument"); } if (LONG_MAX/len < RSTRING(str)->len) { rb_raise(rb_eArgError, "argument too big"); } str2 = rb_str_new(0, RSTRING(str)->len*len); for (i=0; i<len; i++) { memcpy(RSTRING(str2)->ptr+(i*RSTRING(str)->len), RSTRING(str)->ptr, RSTRING(str)->len); } RSTRING(str2)->ptr[RSTRING(str2)->len] = '\0'; OBJ_INFECT(str2, str); RBASIC(str2)->klass = rb_obj_class(str); return str2; } static VALUE rb_str_format(str, arg) VALUE str, arg; { VALUE *argv; if (TYPE(arg) == T_ARRAY) { argv = ALLOCA_N(VALUE, RARRAY(arg)->len + 1); argv[0] = str; MEMCPY(argv+1, RARRAY(arg)->ptr, VALUE, RARRAY(arg)->len); return rb_f_sprintf(RARRAY(arg)->len+1, argv); } argv = ALLOCA_N(VALUE, 2); argv[0] = str; argv[1] = arg; return rb_f_sprintf(2, argv); } VALUE rb_str_substr(str, beg, len) VALUE str; long beg, len; { VALUE str2; if (len < 0) return Qnil; if (beg > RSTRING(str)->len) return Qnil; if (beg < 0) { beg += RSTRING(str)->len; if (beg < 0) return Qnil; } if (beg + len > RSTRING(str)->len) { len = RSTRING(str)->len - beg; } if (len < 0) { len = 0; } if (len == 0) return rb_str_new(0,0); str2 = rb_str_new(RSTRING(str)->ptr+beg, len); RBASIC(str2)->klass = rb_obj_class(str); if (OBJ_TAINTED(str)) OBJ_TAINT(str2); return str2; } static int str_independent(str) VALUE str; { if (OBJ_FROZEN(str)) rb_error_frozen("string"); if (!OBJ_TAINTED(str) && rb_safe_level() >= 4) rb_raise(rb_eSecurityError, "Insecure: can't modify string"); if (!RSTRING(str)->orig || FL_TEST(str, STR_NO_ORIG)) return 1; if (TYPE(RSTRING(str)->orig) != T_STRING) rb_bug("non string str->orig"); return 0; } void rb_str_modify(str) VALUE str; { char *ptr; if (str_independent(str)) return; ptr = ALLOC_N(char, RSTRING(str)->len+1); if (RSTRING(str)->ptr) { memcpy(ptr, RSTRING(str)->ptr, RSTRING(str)->len); } ptr[RSTRING(str)->len] = 0; RSTRING(str)->ptr = ptr; RSTRING(str)->orig = 0; } VALUE rb_str_freeze(str) VALUE str; { return rb_obj_freeze(str); } VALUE rb_str_dup_frozen(str) VALUE str; { if (RSTRING(str)->orig && !FL_TEST(str, STR_NO_ORIG)) { OBJ_FREEZE(RSTRING(str)->orig); return RSTRING(str)->orig; } if (OBJ_FROZEN(str)) return str; str = rb_str_dup(str); OBJ_FREEZE(str); return str; } VALUE rb_str_resize(str, len) VALUE str; long len; { rb_str_modify(str); if (len >= 0) { if (RSTRING(str)->len < len || RSTRING(str)->len - len > 1024) { REALLOC_N(RSTRING(str)->ptr, char, len + 1); } RSTRING(str)->len = len; RSTRING(str)->ptr[len] = '\0'; /* sentinel */ } return str; } VALUE rb_str_cat(str, ptr, len) VALUE str; const char *ptr; long len; { if (len > 0) { int poffset = -1; rb_str_modify(str); if (RSTRING(str)->ptr <= ptr && ptr < RSTRING(str)->ptr + RSTRING(str)->len) { poffset = ptr - RSTRING(str)->ptr; } REALLOC_N(RSTRING(str)->ptr, char, RSTRING(str)->len + len + 1); if (ptr) { if (poffset >= 0) ptr = RSTRING(str)->ptr + poffset; memcpy(RSTRING(str)->ptr + RSTRING(str)->len, ptr, len); } RSTRING(str)->len += len; RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; /* sentinel */ } return str; } VALUE rb_str_cat2(str, ptr) VALUE str; const char *ptr; { return rb_str_cat(str, ptr, strlen(ptr)); } VALUE rb_str_append(str1, str2) VALUE str1, str2; { if (TYPE(str2) != T_STRING) str2 = rb_str_to_str(str2); str1 = rb_str_cat(str1, RSTRING(str2)->ptr, RSTRING(str2)->len); OBJ_INFECT(str1, str2); return str1; } VALUE rb_str_concat(str1, str2) VALUE str1, str2; { if (FIXNUM_P(str2)) { int i = FIX2INT(str2); if (0 <= i && i <= 0xff) { /* byte */ char c = i; return rb_str_cat(str1, &c, 1); } } str1 = rb_str_append(str1, str2); return str1; } int rb_str_hash(str) VALUE str; { register long len = RSTRING(str)->len; register char *p = RSTRING(str)->ptr; register int key = 0; #ifdef HASH_ELFHASH register unsigned int g; while (len--) { key = (key << 4) + *p++; if (g = key & 0xF0000000) key ^= g >> 24; key &= ~g; } #elif HASH_PERL if (ruby_ignorecase) { while (len--) { key = key*33 + toupper(*p); p++; } } else { while (len--) { key = key*33 + *p++; } } key = key + (key>>5); #else if (ruby_ignorecase) { while (len--) { key = key*65599 + toupper(*p); p++; } } else { while (len--) { key = key*65599 + *p; p++; } } key = key + (key>>5); #endif return key; } static VALUE rb_str_hash_m(str) VALUE str; { int key = rb_str_hash(str); return INT2FIX(key); } #define lesser(a,b) (((a)>(b))?(b):(a)) int rb_str_cmp(str1, str2) VALUE str1, str2; { long len; int retval; len = lesser(RSTRING(str1)->len, RSTRING(str2)->len); retval = rb_memcmp(RSTRING(str1)->ptr, RSTRING(str2)->ptr, len); if (retval == 0) { if (RSTRING(str1)->len == RSTRING(str2)->len) return 0; if (RSTRING(str1)->len > RSTRING(str2)->len) return 1; return -1; } if (retval > 0) return 1; return -1; } static VALUE rb_str_equal(str1, str2) VALUE str1, str2; { if (str1 == str2) return Qtrue; if (TYPE(str2) != T_STRING) { str2 = rb_check_convert_type(str2, T_STRING, "String", "to_str"); if (NIL_P(str2)) return Qfalse; } if (RSTRING(str1)->len == RSTRING(str2)->len && rb_str_cmp(str1, str2) == 0) { return Qtrue; } return Qfalse; } static VALUE rb_str_cmp_m(str1, str2) VALUE str1, str2; { int result; if (TYPE(str2) != T_STRING) str2 = rb_str_to_str(str2); result = rb_str_cmp(str1, str2); return INT2FIX(result); } static VALUE rb_str_match(x, y) VALUE x, y; { VALUE reg; long start; switch (TYPE(y)) { case T_REGEXP: return rb_reg_match(y, x); case T_STRING: reg = rb_reg_regcomp(y); start = rb_reg_search(reg, x, 0, 0); if (start == -1) { return Qnil; } return INT2NUM(start); default: return rb_funcall(y, rb_intern("=~"), 1, x); } } static VALUE rb_str_match2(str) VALUE str; { return rb_reg_match2(rb_reg_regcomp(str)); } static long rb_str_index(str, sub, offset) VALUE str, sub; long offset; { char *s, *e, *p; long len; if (offset < 0) { offset += RSTRING(str)->len; if (offset < 0) return -1; } if (RSTRING(str)->len - offset < RSTRING(sub)->len) return -1; s = RSTRING(str)->ptr+offset; p = RSTRING(sub)->ptr; len = RSTRING(sub)->len; if (len == 0) return offset; e = RSTRING(str)->ptr + RSTRING(str)->len - len + 1; while (s < e) { if (rb_memcmp(s, p, len) == 0) { return (s-(RSTRING(str)->ptr)); } s++; } return -1; } static VALUE rb_str_index_m(argc, argv, str) int argc; VALUE *argv; VALUE str; { VALUE sub; VALUE initpos; long pos; if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) { pos = NUM2LONG(initpos); } else { pos = 0; } if (pos < 0) { pos += RSTRING(str)->len; if (pos < 0) return Qnil; } switch (TYPE(sub)) { case T_REGEXP: pos = rb_reg_adjust_startpos(sub, str, pos, 0); pos = rb_reg_search(sub, str, pos, 0); break; case T_STRING: pos = rb_str_index(str, sub, pos); break; case T_FIXNUM: { int c = FIX2INT(sub); long len = RSTRING(str)->len; char *p = RSTRING(str)->ptr; for (;pos<len;pos++) { if (p[pos] == c) return INT2NUM(pos); } return Qnil; } default: rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(sub))); } if (pos == -1) return Qnil; return INT2NUM(pos); } static VALUE rb_str_rindex(argc, argv, str) int argc; VALUE *argv; VALUE str; { VALUE sub; VALUE position; int pos, len; char *s, *sbeg, *t; if (rb_scan_args(argc, argv, "11", &sub, &position) == 2) { pos = NUM2INT(position); if (pos < 0) { pos += RSTRING(str)->len; if (pos < 0) return Qnil; } if (pos > RSTRING(str)->len) pos = RSTRING(str)->len; } else { pos = RSTRING(str)->len; } switch (TYPE(sub)) { case T_REGEXP: if (RREGEXP(sub)->len) { pos = rb_reg_adjust_startpos(sub, str, pos, 1); pos = rb_reg_search(sub, str, pos, 1); } if (pos >= 0) return INT2NUM(pos); break; case T_STRING: len = RSTRING(sub)->len; /* substring longer than string */ if (RSTRING(str)->len < len) return Qnil; if (RSTRING(str)->len - pos < len) { pos = RSTRING(str)->len - len; } sbeg = RSTRING(str)->ptr; s = RSTRING(str)->ptr + pos; t = RSTRING(sub)->ptr; if (len) { while (sbeg <= s) { if (rb_memcmp(s, t, len) == 0) { return INT2NUM(s - RSTRING(str)->ptr); } s--; } } else { return INT2NUM(pos); } break; case T_FIXNUM: { int c = FIX2INT(sub); char *p = RSTRING(str)->ptr + pos; char *pbeg = RSTRING(str)->ptr; while (pbeg <= p) { if (*p == c) return INT2NUM(p - RSTRING(str)->ptr); p--; } return Qnil; } default: rb_raise(rb_eTypeError, "type mismatch: %s given", rb_class2name(CLASS_OF(sub))); } return Qnil; } static char succ_char(s) char *s; { char c = *s; /* numerics */ if ('0' <= c && c < '9') (*s)++; else if (c == '9') { *s = '0'; return '1'; } /* small alphabets */ else if ('a' <= c && c < 'z') (*s)++; else if (c == 'z') { return *s = 'a'; } /* capital alphabets */ else if ('A' <= c && c < 'Z') (*s)++; else if (c == 'Z') { return *s = 'A'; } return 0; } static VALUE rb_str_succ(orig) VALUE orig; { VALUE str; char *sbeg, *s; int c = -1; int n = 0; str = rb_str_new(RSTRING(orig)->ptr, RSTRING(orig)->len); RBASIC(str)->klass = rb_obj_class(orig); OBJ_INFECT(str, orig); if (RSTRING(str)->len == 0) return str; sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1; while (sbeg <= s) { if (ISALNUM(*s)) { if ((c = succ_char(s)) == 0) break; n = s - sbeg; } s--; } if (c == -1) { /* str contains no alnum */ sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1; c = '\001'; while (sbeg <= s) { if ((*s += 1) != 0) break; s--; } } if (s < sbeg) { REALLOC_N(RSTRING(str)->ptr, char, RSTRING(str)->len + 2); s = RSTRING(str)->ptr + n; memmove(s+1, s, RSTRING(str)->len - n); *s = c; RSTRING(str)->len += 1; RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; } return str; } static VALUE rb_str_succ_bang(str) VALUE str; { rb_str_modify(str); rb_str_become(str, rb_str_succ(str)); return str; } VALUE rb_str_upto(beg, end, excl) VALUE beg, end; int excl; { VALUE current; ID succ = rb_intern("succ"); if (TYPE(end) != T_STRING) end = rb_str_to_str(end); current = beg; while (rb_str_cmp(current, end) <= 0) { rb_yield(current); if (!excl && rb_str_equal(current, end)) break; current = rb_funcall(current, succ, 0, 0); if (excl && rb_str_equal(current, end)) break; if (RSTRING(current)->len > RSTRING(end)->len) break; } return beg; } static VALUE rb_str_upto_m(beg, end) VALUE beg, end; { return rb_str_upto(beg, end, 0); } static VALUE rb_str_aref(str, indx) VALUE str; VALUE indx; { long idx; switch (TYPE(indx)) { case T_FIXNUM: idx = FIX2LONG(indx); num_index: if (idx < 0) { idx = RSTRING(str)->len + idx; } if (idx < 0 || RSTRING(str)->len <= idx) { return Qnil; } return INT2FIX(RSTRING(str)->ptr[idx] & 0xff); case T_REGEXP: if (rb_reg_search(indx, str, 0, 0) >= 0) return rb_reg_last_match(rb_backref_get()); return Qnil; case T_STRING: if (rb_str_index(str, indx, 0) != -1) return indx; return Qnil; default: /* check if indx is Range */ { long beg, len; switch (rb_range_beg_len(indx, &beg, &len, RSTRING(str)->len, 0)) { case Qfalse: break; case Qnil: return Qnil; default: return rb_str_substr(str, beg, len); } } idx = NUM2LONG(indx); goto num_index; } return Qnil; /* not reached */ } static VALUE rb_str_aref_m(argc, argv, str) int argc; VALUE *argv; VALUE str; { if (argc == 2) { return rb_str_substr(str, NUM2INT(argv[0]), NUM2INT(argv[1])); } if (argc != 1) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)", argc); } return rb_str_aref(str, argv[0]); } static void rb_str_replace(str, beg, len, val) VALUE str, val; long beg; long len; { if (RSTRING(str)->len < beg + len) { len = RSTRING(str)->len - beg; } if (len < RSTRING(val)->len) { /* expand string */ REALLOC_N(RSTRING(str)->ptr, char, RSTRING(str)->len+RSTRING(val)->len-len+1); } if (RSTRING(val)->len != len) { memmove(RSTRING(str)->ptr + beg + RSTRING(val)->len, RSTRING(str)->ptr + beg + len, RSTRING(str)->len - (beg + len)); } if (RSTRING(str)->len < beg && len < 0) { MEMZERO(RSTRING(str)->ptr + RSTRING(str)->len, char, -len); } if (RSTRING(val)->len > 0) { memmove(RSTRING(str)->ptr+beg, RSTRING(val)->ptr, RSTRING(val)->len); } RSTRING(str)->len += RSTRING(val)->len - len; RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; OBJ_INFECT(str, val); } static VALUE rb_str_sub_bang _((int, VALUE*, VALUE)); static VALUE rb_str_aset(str, indx, val) VALUE str; VALUE indx, val; { long idx, beg; switch (TYPE(indx)) { case T_FIXNUM: num_index: idx = NUM2INT(indx); if (RSTRING(str)->len <= idx) { out_of_range: rb_raise(rb_eIndexError, "index %d out of string", idx); } if (idx < 0) { if (-idx > RSTRING(str)->len) goto out_of_range; idx += RSTRING(str)->len; } if (FIXNUM_P(val)) { if (RSTRING(str)->len == idx) { RSTRING(str)->len += 1; REALLOC_N(RSTRING(str)->ptr, char, RSTRING(str)->len); } RSTRING(str)->ptr[idx] = NUM2INT(val) & 0xff; } else { if (TYPE(val) != T_STRING) val = rb_str_to_str(val); rb_str_replace(str, idx, 1, val); } return val; case T_REGEXP: { VALUE args[2]; args[0] = indx; args[1] = val; rb_str_sub_bang(2, args, str); } return val; case T_STRING: beg = rb_str_index(str, indx, 0); if (beg != -1) { if (TYPE(val) != T_STRING) val = rb_str_to_str(val); rb_str_replace(str, beg, RSTRING(indx)->len, val); } return val; default: /* check if indx is Range */ { long beg, len; if (rb_range_beg_len(indx, &beg, &len, RSTRING(str)->len, 2)) { if (TYPE(val) != T_STRING) val = rb_str_to_str(val); rb_str_replace(str, beg, len, val); return val; } } idx = NUM2LONG(indx); goto num_index; } } static VALUE rb_str_aset_m(argc, argv, str) int argc; VALUE *argv; VALUE str; { rb_str_modify(str); if (argc == 3) { long beg, len; if (TYPE(argv[2]) != T_STRING) argv[2] = rb_str_to_str(argv[2]); beg = NUM2INT(argv[0]); len = NUM2INT(argv[1]); if (len < 0) rb_raise(rb_eIndexError, "negative length %d", len); if (RSTRING(str)->len < beg) { out_of_range: rb_raise(rb_eIndexError, "index %d out of string", beg); } if (beg < 0) { if (-beg > RSTRING(str)->len) { goto out_of_range; } beg += RSTRING(str)->len; } if (beg + len > RSTRING(str)->len) { len = RSTRING(str)->len - beg; } rb_str_replace(str, beg, len, argv[2]); return argv[2]; } if (argc != 2) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)", argc); } return rb_str_aset(str, argv[0], argv[1]); } static VALUE rb_str_slice_bang(argc, argv, str) int argc; VALUE *argv; VALUE str; { VALUE result; VALUE buf[3]; int i; if (argc < 1 || 2 < argc) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)", argc); } for (i=0; i<argc; i++) { buf[i] = argv[i]; } buf[i] = rb_str_new(0,0); result = rb_str_aref_m(argc, buf, str); rb_str_aset_m(argc+1, buf, str); return result; } static VALUE get_pat(pat) VALUE pat; { switch (TYPE(pat)) { case T_REGEXP: break; case T_STRING: pat = rb_reg_regcomp(pat); break; default: /* type failed */ Check_Type(pat, T_REGEXP); } return pat; } static VALUE rb_str_sub_bang(argc, argv, str) int argc; VALUE *argv; VALUE str; { VALUE pat, repl, match; struct re_registers *regs; int iter = 0; int tainted = 0; long plen; if (argc == 1 && rb_block_given_p()) { iter = 1; } else if (argc == 2) { repl = rb_str_to_str(argv[1]);; if (OBJ_TAINTED(repl)) tainted = 1; } else { rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)", argc); } pat = get_pat(argv[0]); if (rb_reg_search(pat, str, 0, 0) >= 0) { rb_str_modify(str); match = rb_backref_get(); regs = RMATCH(match)->regs; if (iter) { rb_match_busy(match); repl = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match))); rb_backref_set(match); } else { repl = rb_reg_regsub(repl, str, regs); } if (OBJ_TAINTED(repl)) tainted = 1; plen = END(0) - BEG(0); if (RSTRING(repl)->len > plen) { REALLOC_N(RSTRING(str)->ptr, char, RSTRING(str)->len + RSTRING(repl)->len - plen + 1); } if (RSTRING(repl)->len != plen) { memmove(RSTRING(str)->ptr + BEG(0) + RSTRING(repl)->len, RSTRING(str)->ptr + BEG(0) + plen, RSTRING(str)->len - BEG(0) - plen); } memcpy(RSTRING(str)->ptr + BEG(0), RSTRING(repl)->ptr, RSTRING(repl)->len); RSTRING(str)->len += RSTRING(repl)->len - plen; RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; if (tainted) OBJ_TAINT(str); return str; } return Qnil; } static VALUE rb_str_sub(argc, argv, str) int argc; VALUE *argv; VALUE str; { str = rb_str_dup(str); rb_str_sub_bang(argc, argv, str); return str; } static VALUE str_gsub(argc, argv, str, bang) int argc; VALUE *argv; VALUE str; int bang; { VALUE pat, val, repl, match; struct re_registers *regs; long beg, n; long offset, blen, len; int iter = 0; char *buf, *bp, *cp; int tainted = 0; if (argc == 1 && rb_block_given_p()) { iter = 1; } else if (argc == 2) { repl = rb_str_to_str(argv[1]); if (OBJ_TAINTED(repl)) tainted = 1; } else { rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)", argc); } pat = get_pat(argv[0]); offset=0; n=0; beg = rb_reg_search(pat, str, 0, 0); if (beg < 0) { if (bang) return Qnil; /* no match, no substitution */ return rb_str_dup(str); } blen = RSTRING(str)->len + 30; /* len + margin */ buf = ALLOC_N(char, blen); bp = buf; cp = RSTRING(str)->ptr; while (beg >= 0) { n++; match = rb_backref_get(); regs = RMATCH(match)->regs; if (iter) { rb_match_busy(match); val = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match))); rb_backref_set(match); } else { val = rb_reg_regsub(repl, str, regs); } if (OBJ_TAINTED(val)) tainted = 1; len = (bp - buf) + (beg - offset) + RSTRING(val)->len + 3; if (blen < len) { while (blen < len) blen *= 2; len = bp - buf; REALLOC_N(buf, char, blen); bp = buf + len; } len = beg - offset; /* copy pre-match substr */ memcpy(bp, cp, len); bp += len; memcpy(bp, RSTRING(val)->ptr, RSTRING(val)->len); bp += RSTRING(val)->len; if (BEG(0) == END(0)) { /* * Always consume at least one character of the input string * in order to prevent infinite loops. */ len = mbclen2(RSTRING(str)->ptr[END(0)], pat); if (RSTRING(str)->len > END(0)) { memcpy(bp, RSTRING(str)->ptr+END(0), len); bp += len; } offset = END(0) + len; } else { offset = END(0); } cp = RSTRING(str)->ptr + offset; if (offset > RSTRING(str)->len) break; beg = rb_reg_search(pat, str, offset, 0); } if (RSTRING(str)->len > offset) { len = bp - buf; if (blen - len < RSTRING(str)->len - offset + 1) { REALLOC_N(buf, char, len + RSTRING(str)->len - offset + 1); bp = buf + len; } memcpy(bp, cp, RSTRING(str)->len - offset); bp += RSTRING(str)->len - offset; } rb_backref_set(match); if (bang) { if (str_independent(str)) { free(RSTRING(str)->ptr); } else { RSTRING(str)->orig = 0; } } else { NEWOBJ(dup, struct RString); OBJSETUP(dup, rb_cString, T_STRING); OBJ_INFECT(dup, str); RBASIC(dup)->klass = rb_obj_class(str); str = (VALUE)dup; dup->orig = 0; } RSTRING(str)->ptr = buf; RSTRING(str)->len = len = bp - buf; RSTRING(str)->ptr[len] = '\0'; if (tainted) OBJ_TAINT(str); return str; } static VALUE rb_str_gsub_bang(argc, argv, str) int argc; VALUE *argv; VALUE str; { return str_gsub(argc, argv, str, 1); } static VALUE rb_str_gsub(argc, argv, str) int argc; VALUE *argv; VALUE str; { return str_gsub(argc, argv, str, 0); } static VALUE rb_str_replace_m(str, str2) VALUE str, str2; { if (str == str2) return str; if (TYPE(str2) != T_STRING) str2 = rb_str_to_str(str2); if (RSTRING(str2)->orig && !FL_TEST(str2, STR_NO_ORIG)) { if (str_independent(str)) { free(RSTRING(str)->ptr); } RSTRING(str)->len = RSTRING(str2)->len; RSTRING(str)->ptr = RSTRING(str2)->ptr; RSTRING(str)->orig = RSTRING(str2)->orig; } else { rb_str_modify(str); rb_str_resize(str, RSTRING(str2)->len); memcpy(RSTRING(str)->ptr, RSTRING(str2)->ptr, RSTRING(str2)->len); } if (OBJ_TAINTED(str2)) OBJ_TAINT(str); return str; } static VALUE uscore_get() { VALUE line; line = rb_lastline_get(); if (TYPE(line) != T_STRING) { rb_raise(rb_eTypeError, "$_ value need to be String (%s given)", NIL_P(line)?"nil":rb_class2name(CLASS_OF(line))); } return line; } static VALUE rb_f_sub_bang(argc, argv) int argc; VALUE *argv; { return rb_str_sub_bang(argc, argv, uscore_get()); } static VALUE rb_f_sub(argc, argv) int argc; VALUE *argv; { VALUE str = rb_str_dup(uscore_get()); if (NIL_P(rb_str_sub_bang(argc, argv, str))) return str; rb_lastline_set(str); return str; } static VALUE rb_f_gsub_bang(argc, argv) int argc; VALUE *argv; { return rb_str_gsub_bang(argc, argv, uscore_get()); } static VALUE rb_f_gsub(argc, argv) int argc; VALUE *argv; { VALUE str = rb_str_dup(uscore_get()); if (NIL_P(rb_str_gsub_bang(argc, argv, str))) return str; rb_lastline_set(str); return str; } static VALUE rb_str_reverse_bang(str) VALUE str; { char *s, *e; char c; rb_str_modify(str); s = RSTRING(str)->ptr; e = s + RSTRING(str)->len - 1; while (s < e) { c = *s; *s++ = *e; *e-- = c; } return str; } static VALUE rb_str_reverse(str) VALUE str; { VALUE obj; char *s, *e, *p; if (RSTRING(str)->len <= 1) return rb_str_dup(str); obj = rb_str_new(0, RSTRING(str)->len); s = RSTRING(str)->ptr; e = s + RSTRING(str)->len - 1; p = RSTRING(obj)->ptr; while (e >= s) { *p++ = *e--; } OBJ_INFECT(obj, str); RBASIC(obj)->klass = rb_obj_class(str); return obj; } static VALUE rb_str_include(str, arg) VALUE str, arg; { long i; if (FIXNUM_P(arg)) { int c = FIX2INT(arg); long len = RSTRING(str)->len; char *p = RSTRING(str)->ptr; for (i=0; i<len; i++) { if (p[i] == c) { return Qtrue; } } return Qfalse; } if (TYPE(arg) != T_STRING) arg = rb_str_to_str(arg); i = rb_str_index(str, arg, 0); if (i == -1) return Qfalse; return Qtrue; } static VALUE rb_str_to_i(str) VALUE str; { return rb_str2inum(str, 10); } static VALUE rb_str_to_f(str) VALUE str; { double f = strtod(RSTRING(str)->ptr, 0); return rb_float_new(f); } static VALUE rb_str_to_s(str) VALUE str; { return str; } VALUE rb_str_inspect(str) VALUE str; { char *p, *pend; VALUE result = rb_str_new2("\""); char s[5]; p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len; while (p < pend) { char c = *p++; if (ismbchar(c) && p < pend) { int len = mbclen(c); rb_str_cat(result, p - 1, len); p += len - 1; } else if (c == '"'|| c == '\\') { s[0] = '\\'; s[1] = c; rb_str_cat(result, s, 2); } else if (ISPRINT(c)) { s[0] = c; rb_str_cat(result, s, 1); } else if (c == '\n') { s[0] = '\\'; s[1] = 'n'; rb_str_cat(result, s, 2); } else if (c == '\r') { s[0] = '\\'; s[1] = 'r'; rb_str_cat(result, s, 2); } else if (c == '\t') { s[0] = '\\'; s[1] = 't'; rb_str_cat(result, s, 2); } else if (c == '\f') { s[0] = '\\'; s[1] = 'f'; rb_str_cat(result, s, 2); } else if (c == '\013') { s[0] = '\\'; s[1] = 'v'; rb_str_cat(result, s, 2); } else if (c == '\007') { s[0] = '\\'; s[1] = 'a'; rb_str_cat(result, s, 2); } else if (c == 033) { s[0] = '\\'; s[1] = 'e'; rb_str_cat(result, s, 2); } else { sprintf(s, "\\%03o", c & 0377); rb_str_cat2(result, s); } } rb_str_cat2(result, "\""); OBJ_INFECT(result, str); return result; } static VALUE rb_str_dump(str) VALUE str; { long len; char *p, *pend; char *q, *qend; VALUE result; len = 2; /* "" */ p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len; while (p < pend) { char c = *p++; switch (c) { case '"': case '\\': case '\n': case '\r': case '\t': case '\f': case '#': case '\013': case '\007': case '\033': len += 2; break; default: if (ISPRINT(c)) { len++; } else { len += 4; /* \nnn */ } break; } } result = rb_str_new(0, len); p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len; q = RSTRING(result)->ptr; qend = q + len; *q++ = '"'; while (p < pend) { char c = *p++; if (c == '"' || c == '\\') { *q++ = '\\'; *q++ = c; } else if (c == '#') { *q++ = '\\'; *q++ = '#'; } else if (ISPRINT(c)) { *q++ = c; } else if (c == '\n') { *q++ = '\\'; *q++ = 'n'; } else if (c == '\r') { *q++ = '\\'; *q++ = 'r'; } else if (c == '\t') { *q++ = '\\'; *q++ = 't'; } else if (c == '\f') { *q++ = '\\'; *q++ = 'f'; } else if (c == '\013') { *q++ = '\\'; *q++ = 'v'; } else if (c == '\007') { *q++ = '\\'; *q++ = 'a'; } else if (c == '\033') { *q++ = '\\'; *q++ = 'e'; } else { *q++ = '\\'; sprintf(q, "%03o", c&0xff); q += 3; } } *q++ = '"'; OBJ_INFECT(result, str); return result; } static VALUE rb_str_upcase_bang(str) VALUE str; { char *s, *send; int modify = 0; rb_str_modify(str); s = RSTRING(str)->ptr; send = s + RSTRING(str)->len; while (s < send) { if (ismbchar(*s)) { s+=mbclen(*s) - 1; } else if (ISLOWER(*s)) { *s = toupper(*s); modify = 1; } s++; } if (modify) return str; return Qnil; } static VALUE rb_str_upcase(str) VALUE str; { str = rb_str_dup(str); rb_str_upcase_bang(str); return str; } static VALUE rb_str_downcase_bang(str) VALUE str; { char *s, *send; int modify = 0; rb_str_modify(str); s = RSTRING(str)->ptr; send = s + RSTRING(str)->len; while (s < send) { if (ismbchar(*s)) { s+=mbclen(*s) - 1; } else if (ISUPPER(*s)) { *s = tolower(*s); modify = 1; } s++; } if (modify) return str; return Qnil; } static VALUE rb_str_downcase(str) VALUE str; { str = rb_str_dup(str); rb_str_downcase_bang(str); return str; } static VALUE rb_str_capitalize_bang(str) VALUE str; { char *s, *send; int modify = 0; rb_str_modify(str); s = RSTRING(str)->ptr; send = s + RSTRING(str)->len; if (ISLOWER(*s)) { *s = toupper(*s); modify = 1; } while (++s < send) { if (ismbchar(*s)) { s+=mbclen(*s) - 1; } else if (ISUPPER(*s)) { *s = tolower(*s); modify = 1; } } if (modify) return str; return Qnil; } static VALUE rb_str_capitalize(str) VALUE str; { str = rb_str_dup(str); rb_str_capitalize_bang(str); return str; } static VALUE rb_str_swapcase_bang(str) VALUE str; { char *s, *send; int modify = 0; rb_str_modify(str); s = RSTRING(str)->ptr; send = s + RSTRING(str)->len; while (s < send) { if (ismbchar(*s)) { s+=mbclen(*s) - 1; } else if (ISUPPER(*s)) { *s = tolower(*s); modify = 1; } else if (ISLOWER(*s)) { *s = toupper(*s); modify = 1; } s++; } if (modify) return str; return Qnil; } static VALUE rb_str_swapcase(str) VALUE str; { str = rb_str_dup(str); rb_str_swapcase_bang(str); return str; } typedef unsigned char *USTR; struct tr { int gen, now, max; char *p, *pend; }; static int trnext(t) struct tr *t; { for (;;) { if (!t->gen) { if (t->p == t->pend) return -1; if (t->p < t->pend - 1 && *t->p == '\\') { t->p++; } t->now = *(USTR)t->p++; if (t->p < t->pend - 1 && *t->p == '-') { t->p++; if (t->p < t->pend) { if (t->now > *(USTR)t->p) { t->p++; continue; } t->gen = 1; t->max = *(USTR)t->p++; } } return t->now; } else if (++t->now < t->max) { return t->now; } else { t->gen = 0; return t->max; } } } static VALUE rb_str_delete_bang _((int,VALUE*,VALUE)); static VALUE tr_trans(str, src, repl, sflag) VALUE str, src, repl; int sflag; { struct tr trsrc, trrepl; int cflag = 0; int trans[256]; int i, c, modify = 0; char *s, *send; rb_str_modify(str); if (TYPE(src) != T_STRING) src = rb_str_to_str(src); trsrc.p = RSTRING(src)->ptr; trsrc.pend = trsrc.p + RSTRING(src)->len; if (RSTRING(src)->len >= 2 && RSTRING(src)->ptr[0] == '^') { cflag++; trsrc.p++; } if (TYPE(repl) != T_STRING) repl = rb_str_to_str(repl); if (RSTRING(repl)->len == 0) { return rb_str_delete_bang(1, &src, str); } trrepl.p = RSTRING(repl)->ptr; trrepl.pend = trrepl.p + RSTRING(repl)->len; trsrc.gen = trrepl.gen = 0; trsrc.now = trrepl.now = 0; trsrc.max = trrepl.max = 0; if (cflag) { for (i=0; i<256; i++) { trans[i] = 1; } while ((c = trnext(&trsrc)) >= 0) { trans[c & 0xff] = -1; } while ((c = trnext(&trrepl)) >= 0) /* retrieve last replacer */; for (i=0; i<256; i++) { if (trans[i] >= 0) { trans[i] = trrepl.now; } } } else { int r; for (i=0; i<256; i++) { trans[i] = -1; } while ((c = trnext(&trsrc)) >= 0) { r = trnext(&trrepl); if (r == -1) r = trrepl.now; trans[c & 0xff] = r; } } s = RSTRING(str)->ptr; send = s + RSTRING(str)->len; if (sflag) { char *t = s; int c0, last = -1; while (s < send) { c0 = *s++; if ((c = trans[c0 & 0xff]) >= 0) { if (last == c) continue; last = c; *t++ = c & 0xff; modify = 1; } else { last = -1; *t++ = c0; } } if (RSTRING(str)->len > (t - RSTRING(str)->ptr)) { RSTRING(str)->len = (t - RSTRING(str)->ptr); modify = 1; *t = '\0'; } } else { while (s < send) { if ((c = trans[*s & 0xff]) >= 0) { *s = c & 0xff; modify = 1; } s++; } } if (modify) return str; return Qnil; } static VALUE rb_str_tr_bang(str, src, repl) VALUE str, src, repl; { return tr_trans(str, src, repl, 0); } static VALUE rb_str_tr(str, src, repl) VALUE str, src, repl; { str = rb_str_dup(str); tr_trans(str, src, repl, 0); return str; } static void tr_setup_table(str, table, init) VALUE str; char table[256]; int init; { char buf[256]; struct tr tr; int i, c; int cflag = 0; tr.p = RSTRING(str)->ptr; tr.pend = tr.p + RSTRING(str)->len; tr.gen = tr.now = tr.max = 0; if (RSTRING(str)->len > 1 && RSTRING(str)->ptr[0] == '^') { cflag = 1; tr.p++; } if (init) { for (i=0; i<256; i++) { table[i] = 1; } } for (i=0; i<256; i++) { buf[i] = cflag; } while ((c = trnext(&tr)) >= 0) { buf[c & 0xff] = !cflag; } for (i=0; i<256; i++) { table[i] = table[i]&&buf[i]; } } static VALUE rb_str_delete_bang(argc, argv, str) int argc; VALUE *argv; VALUE str; { char *s, *send, *t; char squeez[256]; int modify = 0; int init = 1; int i; if (argc < 1) { rb_raise(rb_eArgError, "wrong # of arguments"); } for (i=0; i<argc; i++) { VALUE s = argv[i]; if (TYPE(s) != T_STRING) s = rb_str_to_str(s); tr_setup_table(s, squeez, init); init = 0; } rb_str_modify(str); s = t = RSTRING(str)->ptr; send = s + RSTRING(str)->len; while (s < send) { if (squeez[*s & 0xff]) modify = 1; else *t++ = *s; s++; } *t = '\0'; RSTRING(str)->len = t - RSTRING(str)->ptr; if (modify) return str; return Qnil; } static VALUE rb_str_delete(argc, argv, str) int argc; VALUE *argv; VALUE str; { str = rb_str_dup(str); rb_str_delete_bang(argc, argv, str); return str; } static VALUE rb_str_squeeze_bang(argc, argv, str) int argc; VALUE *argv; VALUE str; { char squeez[256]; char *s, *send, *t; int c, save, modify = 0; int init = 1; int i; if (argc == 0) { for (i=0; i<256; i++) { squeez[i] = 1; } } else { for (i=0; i<argc; i++) { VALUE s = argv[i]; if (TYPE(s) != T_STRING) s = rb_str_to_str(s); tr_setup_table(s, squeez, init); init = 0; } } rb_str_modify(str); s = t = RSTRING(str)->ptr; send = s + RSTRING(str)->len; save = -1; while (s < send) { c = *s++ & 0xff; if (c != save || !squeez[c]) { *t++ = save = c; } } *t = '\0'; if (t - RSTRING(str)->ptr != RSTRING(str)->len) { RSTRING(str)->len = t - RSTRING(str)->ptr; modify = 1; } if (modify) return str; return Qnil; } static VALUE rb_str_squeeze(argc, argv, str) int argc; VALUE *argv; VALUE str; { str = rb_str_dup(str); rb_str_squeeze_bang(argc, argv, str); return str; } static VALUE rb_str_tr_s_bang(str, src, repl) VALUE str, src, repl; { return tr_trans(str, src, repl, 1); } static VALUE rb_str_tr_s(str, src, repl) VALUE str, src, repl; { str = rb_str_dup(str); tr_trans(str, src, repl, 1); return str; } static VALUE rb_str_count(argc, argv, str) int argc; VALUE *argv; VALUE str; { char table[256]; char *s, *send; int init = 1; int i; if (argc < 1) { rb_raise(rb_eArgError, "wrong # of arguments"); } for (i=0; i<argc; i++) { VALUE s = argv[i]; if (TYPE(s) != T_STRING) s = rb_str_to_str(s); tr_setup_table(s, table, init); init = 0; } s = RSTRING(str)->ptr; send = s + RSTRING(str)->len; i = 0; while (s < send) { if (table[*s++ & 0xff]) { i++; } } return INT2NUM(i); } static VALUE rb_str_split_m(argc, argv, str) int argc; VALUE *argv; VALUE str; { VALUE spat; VALUE limit; int char_sep = -1; long beg, end, i; int lim = 0; VALUE result, tmp; if (rb_scan_args(argc, argv, "02", &spat, &limit) == 2) { lim = NUM2INT(limit); if (lim <= 0) limit = Qnil; else if (lim == 1) return rb_ary_new3(1, str); i = 1; } if (argc == 0) { if (!NIL_P(rb_fs)) { spat = rb_fs; goto fs_set; } char_sep = ' '; } else { fs_set: switch (TYPE(spat)) { case T_STRING: if (RSTRING(spat)->len == 1) { char_sep = (unsigned char)RSTRING(spat)->ptr[0]; } else { spat = rb_reg_regcomp(spat); } break; case T_REGEXP: break; default: rb_raise(rb_eArgError, "bad separator"); } } result = rb_ary_new(); beg = 0; if (char_sep >= 0) { char *ptr = RSTRING(str)->ptr; long len = RSTRING(str)->len; char *eptr = ptr + len; if (char_sep == ' ') { /* AWK emulation */ int skip = 1; for (end = beg = 0; ptr<eptr; ptr++) { if (skip) { if (ISSPACE(*ptr)) { beg++; } else { end = beg+1; skip = 0; } } else { if (ISSPACE(*ptr)) { rb_ary_push(result, rb_str_substr(str, beg, end-beg)); skip = 1; beg = end + 1; if (!NIL_P(limit) && lim <= ++i) break; } else { end++; } } } } else { for (end = beg = 0; ptr<eptr; ptr++) { if (*ptr == (char)char_sep) { rb_ary_push(result, rb_str_substr(str, beg, end-beg)); beg = end + 1; if (!NIL_P(limit) && lim <= ++i) break; } end++; } } } else { long start = beg; long idx; int last_null = 0; struct re_registers *regs; while ((end = rb_reg_search(spat, str, start, 0)) >= 0) { regs = RMATCH(rb_backref_get())->regs; if (start == end && BEG(0) == END(0)) { if (last_null == 1) { rb_ary_push(result, rb_str_substr(str, beg, mbclen2(RSTRING(str)->ptr[beg],spat))); beg = start; } else { start += mbclen2(RSTRING(str)->ptr[start],spat); last_null = 1; continue; } } else { rb_ary_push(result, rb_str_substr(str, beg, end-beg)); beg = start = END(0); } last_null = 0; for (idx=1; idx < regs->num_regs; idx++) { if (BEG(idx) == -1) continue; if (BEG(idx) == END(idx)) tmp = rb_str_new(0, 0); else tmp = rb_str_substr(str, BEG(idx), END(idx)-BEG(idx)); rb_ary_push(result, tmp); } if (!NIL_P(limit) && lim <= ++i) break; } } if (!NIL_P(limit) || RSTRING(str)->len > beg || lim < 0) { if (RSTRING(str)->len == beg) tmp = rb_str_new(0, 0); else tmp = rb_str_substr(str, beg, RSTRING(str)->len-beg); rb_ary_push(result, tmp); } if (NIL_P(limit) && lim == 0) { while (RARRAY(result)->len > 0 && RSTRING(RARRAY(result)->ptr[RARRAY(result)->len-1])->len == 0) rb_ary_pop(result); } return result; } VALUE rb_str_split(str, sep0) VALUE str; const char *sep0; { VALUE sep; if (TYPE(str) != T_STRING) str = rb_str_to_str(str); sep = rb_str_new2(sep0); return rb_str_split_m(1, &sep, str); } static VALUE rb_f_split(argc, argv) int argc; VALUE *argv; { return rb_str_split_m(argc, argv, uscore_get()); } static VALUE rb_str_each_line(argc, argv, str) int argc; VALUE *argv; VALUE str; { VALUE rs; int newline; int rslen; char *p = RSTRING(str)->ptr, *pend = p + RSTRING(str)->len, *s; char *ptr = p; long len = RSTRING(str)->len; VALUE line; if (rb_scan_args(argc, argv, "01", &rs) == 0) { rs = rb_rs; } if (NIL_P(rs)) { rb_yield(str); return str; } if (TYPE(rs) != T_STRING) { rs = rb_str_to_str(rs); } rslen = RSTRING(rs)->len; if (rslen == 0) { newline = '\n'; } else { newline = RSTRING(rs)->ptr[rslen-1]; } for (s = p, p += rslen; p < pend; p++) { if (rslen == 0 && *p == '\n') { if (*++p != '\n') continue; while (*p == '\n') p++; } if (p[-1] == newline && (rslen <= 1 || rb_memcmp(RSTRING(rs)->ptr, p-rslen, rslen) == 0)) { line = rb_str_new(s, p - s); OBJ_INFECT(line, str); rb_yield(line); if (RSTRING(str)->ptr != ptr || RSTRING(str)->len != len) rb_raise(rb_eArgError, "string modified"); s = p; } } if (s != pend) { if (p > pend) p = pend; line = rb_str_new(s, p - s); OBJ_INFECT(line, str); rb_yield(line); } return str; } static VALUE rb_str_each_byte(str) VALUE str; { long i; for (i=0; i<RSTRING(str)->len; i++) { rb_yield(INT2FIX(RSTRING(str)->ptr[i] & 0xff)); } return str; } static VALUE rb_str_chop_bang(str) VALUE str; { if (RSTRING(str)->len > 0) { rb_str_modify(str); RSTRING(str)->len--; if (RSTRING(str)->ptr[RSTRING(str)->len] == '\n') { if (RSTRING(str)->len > 0 && RSTRING(str)->ptr[RSTRING(str)->len-1] == '\r') { RSTRING(str)->len--; } } RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; return str; } return Qnil; } static VALUE rb_str_chop(str) VALUE str; { str = rb_str_dup(str); rb_str_chop_bang(str); return str; } static VALUE rb_f_chop_bang(str) VALUE str; { return rb_str_chop_bang(uscore_get()); } static VALUE rb_f_chop() { VALUE str = uscore_get(); if (RSTRING(str)->len > 0) { str = rb_str_dup(str); rb_str_chop_bang(str); rb_lastline_set(str); } return str; } static VALUE rb_str_chomp_bang(argc, argv, str) int argc; VALUE *argv; VALUE str; { VALUE rs; int newline; int rslen; char *p = RSTRING(str)->ptr; long len = RSTRING(str)->len; if (rb_scan_args(argc, argv, "01", &rs) == 0) { rs = rb_rs; } if (NIL_P(rs)) return Qnil; if (TYPE(rs) != T_STRING) rs = rb_str_to_str(rs); rslen = RSTRING(rs)->len; if (rslen == 0) { while (len>0 && p[len-1] == '\n') { len--; } if (len < RSTRING(str)->len) { rb_str_modify(str); RSTRING(str)->len = len; RSTRING(str)->ptr[len] = '\0'; return str; } return Qnil; } if (rslen > len) return Qnil; newline = RSTRING(rs)->ptr[rslen-1]; if (p[len-1] == newline && (rslen <= 1 || rb_memcmp(RSTRING(rs)->ptr, p+len-rslen, rslen) == 0)) { rb_str_modify(str); RSTRING(str)->len -= rslen; RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; return str; } return Qnil; } static VALUE rb_str_chomp(argc, argv, str) int argc; VALUE *argv; VALUE str; { str = rb_str_dup(str); rb_str_chomp_bang(argc, argv, str); return str; } static VALUE rb_f_chomp_bang(argc, argv) int argc; VALUE *argv; { return rb_str_chomp_bang(argc, argv, uscore_get()); } static VALUE rb_f_chomp(argc, argv) int argc; VALUE *argv; { VALUE str = uscore_get(); VALUE dup = rb_str_dup(str); if (NIL_P(rb_str_chomp_bang(argc, argv, dup))) return str; rb_lastline_set(dup); return dup; } static VALUE rb_str_strip_bang(str) VALUE str; { char *s, *t, *e; rb_str_modify(str); s = RSTRING(str)->ptr; e = t = s + RSTRING(str)->len; /* remove spaces at head */ while (s < t && ISSPACE(*s)) s++; /* remove trailing spaces */ t--; while (s <= t && ISSPACE(*t)) t--; t++; RSTRING(str)->len = t-s; if (s > RSTRING(str)->ptr) { char *p = RSTRING(str)->ptr; RSTRING(str)->ptr = ALLOC_N(char, RSTRING(str)->len+1); memcpy(RSTRING(str)->ptr, s, RSTRING(str)->len); RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; free(p); } else if (t < e) { RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; } else { return Qnil; } return str; } static VALUE rb_str_strip(str) VALUE str; { str = rb_str_dup(str); rb_str_strip_bang(str); return str; } static VALUE scan_once(str, pat, start) VALUE str, pat; long *start; { VALUE result, match; struct re_registers *regs; long i; if (rb_reg_search(pat, str, *start, 0) >= 0) { match = rb_backref_get(); regs = RMATCH(match)->regs; if (BEG(0) == END(0)) { /* * Always consume at least one character of the input string */ *start = END(0)+mbclen2(RSTRING(str)->ptr[END(0)],pat); } else { *start = END(0); } if (regs->num_regs == 1) { return rb_reg_nth_match(0, match); } result = rb_ary_new2(regs->num_regs); for (i=1; i < regs->num_regs; i++) { rb_ary_push(result, rb_reg_nth_match(i, match)); } return result; } return Qnil; } static VALUE rb_str_scan(str, pat) VALUE str, pat; { VALUE result; long start = 0; VALUE match = Qnil; pat = get_pat(pat); if (!rb_block_given_p()) { VALUE ary = rb_ary_new(); while (!NIL_P(result = scan_once(str, pat, &start))) { match = rb_backref_get(); rb_ary_push(ary, result); } rb_backref_set(match); return ary; } while (!NIL_P(result = scan_once(str, pat, &start))) { match = rb_backref_get(); rb_match_busy(match); rb_yield(result); rb_backref_set(match); /* restore $~ value */ } rb_backref_set(match); return str; } static VALUE rb_f_scan(self, pat) VALUE self, pat; { return rb_str_scan(uscore_get(), pat); } static VALUE rb_str_hex(str) VALUE str; { return rb_str2inum(str, 16); } static VALUE rb_str_oct(str) VALUE str; { int base = 8; if (RSTRING(str)->len > 2 && RSTRING(str)->ptr[0] == '0') { switch (RSTRING(str)->ptr[1]) { case 'x': case 'X': base = 16; break; case 'b': case 'B': base = 2; break; } } return rb_str2inum(str, base); } static VALUE rb_str_crypt(str, salt) VALUE str, salt; { extern char *crypt(); VALUE result; if (TYPE(salt) != T_STRING) salt = rb_str_to_str(salt); if (RSTRING(salt)->len < 2) rb_raise(rb_eArgError, "salt too short(need >=2 bytes)"); result = rb_str_new2(crypt(RSTRING(str)->ptr, RSTRING(salt)->ptr)); OBJ_INFECT(result, str); return result; } static VALUE rb_str_intern(str) VALUE str; { ID id; if (strlen(RSTRING(str)->ptr) != RSTRING(str)->len) rb_raise(rb_eArgError, "string contains `\\0'"); id = rb_intern(RSTRING(str)->ptr); return ID2SYM(id); } static VALUE rb_str_sum(argc, argv, str) int argc; VALUE *argv; VALUE str; { VALUE vbits; int bits; char *p, *pend; if (rb_scan_args(argc, argv, "01", &vbits) == 0) { bits = 16; } else bits = NUM2INT(vbits); p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len; if (bits > sizeof(long)*CHAR_BIT) { VALUE res = INT2FIX(0); VALUE mod; mod = rb_funcall(INT2FIX(1), rb_intern("<<"), 1, INT2FIX(bits)); mod = rb_funcall(mod, '-', 1, INT2FIX(1)); while (p < pend) { res = rb_funcall(res, '+', 1, INT2FIX((unsigned int)*p)); p++; } res = rb_funcall(res, '&', 1, mod); return res; } else { unsigned int res = 0; unsigned int mod = (1<<bits)-1; if (mod == 0) { mod = -1; } while (p < pend) { res += (unsigned int)*p; p++; } res &= mod; return rb_int2inum(res); } } static VALUE rb_str_ljust(str, w) VALUE str; VALUE w; { long width = NUM2LONG(w); VALUE res; char *p, *pend; if (width < 0 || RSTRING(str)->len >= width) return str; res = rb_str_new(0, width); RBASIC(res)->klass = rb_obj_class(str); memcpy(RSTRING(res)->ptr, RSTRING(str)->ptr, RSTRING(str)->len); p = RSTRING(res)->ptr + RSTRING(str)->len; pend = RSTRING(res)->ptr + width; while (p < pend) { *p++ = ' '; } OBJ_INFECT(res, str); return res; } static VALUE rb_str_rjust(str, w) VALUE str; VALUE w; { long width = NUM2LONG(w); VALUE res; char *p, *pend; if (width < 0 || RSTRING(str)->len >= width) return str; res = rb_str_new(0, width); RBASIC(res)->klass = rb_obj_class(str); p = RSTRING(res)->ptr; pend = p + width - RSTRING(str)->len; while (p < pend) { *p++ = ' '; } memcpy(pend, RSTRING(str)->ptr, RSTRING(str)->len); OBJ_INFECT(res, str); return res; } static VALUE rb_str_center(str, w) VALUE str; VALUE w; { long width = NUM2LONG(w); VALUE res; char *p, *pend; long n; if (width < 0 || RSTRING(str)->len >= width) return str; res = rb_str_new(0, width); RBASIC(res)->klass = rb_obj_class(str); n = (width - RSTRING(str)->len)/2; p = RSTRING(res)->ptr; pend = p + n; while (p < pend) { *p++ = ' '; } memcpy(pend, RSTRING(str)->ptr, RSTRING(str)->len); p = pend + RSTRING(str)->len; pend = RSTRING(res)->ptr + width; while (p < pend) { *p++ = ' '; } OBJ_INFECT(res, str); return res; } void rb_str_setter(val, id, var) VALUE val; ID id; VALUE *var; { if (!NIL_P(val) && TYPE(val) != T_STRING) { rb_raise(rb_eTypeError, "value of %s must be String", rb_id2name(id)); } *var = val; } void Init_String() { rb_cString = rb_define_class("String", rb_cObject); rb_include_module(rb_cString, rb_mComparable); rb_include_module(rb_cString, rb_mEnumerable); rb_define_singleton_method(rb_cString, "new", rb_str_s_new, -1); rb_define_method(rb_cString, "initialize", rb_str_replace_m, 1); rb_define_method(rb_cString, "clone", rb_str_clone, 0); rb_define_method(rb_cString, "dup", rb_str_dup, 0); rb_define_method(rb_cString, "<=>", rb_str_cmp_m, 1); rb_define_method(rb_cString, "==", rb_str_equal, 1); rb_define_method(rb_cString, "===", rb_str_equal, 1); rb_define_method(rb_cString, "eql?", rb_str_equal, 1); rb_define_method(rb_cString, "hash", rb_str_hash_m, 0); rb_define_method(rb_cString, "+", rb_str_plus, 1); rb_define_method(rb_cString, "*", rb_str_times, 1); rb_define_method(rb_cString, "%", rb_str_format, 1); rb_define_method(rb_cString, "[]", rb_str_aref_m, -1); rb_define_method(rb_cString, "[]=", rb_str_aset_m, -1); rb_define_method(rb_cString, "length", rb_str_length, 0); rb_define_method(rb_cString, "size", rb_str_length, 0); rb_define_method(rb_cString, "empty?", rb_str_empty, 0); rb_define_method(rb_cString, "=~", rb_str_match, 1); rb_define_method(rb_cString, "~", rb_str_match2, 0); rb_define_method(rb_cString, "succ", rb_str_succ, 0); rb_define_method(rb_cString, "succ!", rb_str_succ_bang, 0); rb_define_method(rb_cString, "next", rb_str_succ, 0); rb_define_method(rb_cString, "next!", rb_str_succ_bang, 0); rb_define_method(rb_cString, "upto", rb_str_upto_m, 1); rb_define_method(rb_cString, "index", rb_str_index_m, -1); rb_define_method(rb_cString, "rindex", rb_str_rindex, -1); rb_define_method(rb_cString, "replace", rb_str_replace_m, 1); rb_define_method(rb_cString, "to_i", rb_str_to_i, 0); rb_define_method(rb_cString, "to_f", rb_str_to_f, 0); rb_define_method(rb_cString, "to_s", rb_str_to_s, 0); rb_define_method(rb_cString, "to_str", rb_str_to_s, 0); rb_define_method(rb_cString, "inspect", rb_str_inspect, 0); rb_define_method(rb_cString, "dump", rb_str_dump, 0); rb_define_method(rb_cString, "upcase", rb_str_upcase, 0); rb_define_method(rb_cString, "downcase", rb_str_downcase, 0); rb_define_method(rb_cString, "capitalize", rb_str_capitalize, 0); rb_define_method(rb_cString, "swapcase", rb_str_swapcase, 0); rb_define_method(rb_cString, "upcase!", rb_str_upcase_bang, 0); rb_define_method(rb_cString, "downcase!", rb_str_downcase_bang, 0); rb_define_method(rb_cString, "capitalize!", rb_str_capitalize_bang, 0); rb_define_method(rb_cString, "swapcase!", rb_str_swapcase_bang, 0); rb_define_method(rb_cString, "hex", rb_str_hex, 0); rb_define_method(rb_cString, "oct", rb_str_oct, 0); rb_define_method(rb_cString, "split", rb_str_split_m, -1); rb_define_method(rb_cString, "reverse", rb_str_reverse, 0); rb_define_method(rb_cString, "reverse!", rb_str_reverse_bang, 0); rb_define_method(rb_cString, "concat", rb_str_concat, 1); rb_define_method(rb_cString, "<<", rb_str_concat, 1); rb_define_method(rb_cString, "crypt", rb_str_crypt, 1); rb_define_method(rb_cString, "intern", rb_str_intern, 0); rb_define_method(rb_cString, "include?", rb_str_include, 1); rb_define_method(rb_cString, "scan", rb_str_scan, 1); rb_define_method(rb_cString, "ljust", rb_str_ljust, 1); rb_define_method(rb_cString, "rjust", rb_str_rjust, 1); rb_define_method(rb_cString, "center", rb_str_center, 1); rb_define_method(rb_cString, "sub", rb_str_sub, -1); rb_define_method(rb_cString, "gsub", rb_str_gsub, -1); rb_define_method(rb_cString, "chop", rb_str_chop, 0); rb_define_method(rb_cString, "chomp", rb_str_chomp, -1); rb_define_method(rb_cString, "strip", rb_str_strip, 0); rb_define_method(rb_cString, "sub!", rb_str_sub_bang, -1); rb_define_method(rb_cString, "gsub!", rb_str_gsub_bang, -1); rb_define_method(rb_cString, "strip!", rb_str_strip_bang, 0); rb_define_method(rb_cString, "chop!", rb_str_chop_bang, 0); rb_define_method(rb_cString, "chomp!", rb_str_chomp_bang, -1); rb_define_method(rb_cString, "tr", rb_str_tr, 2); rb_define_method(rb_cString, "tr_s", rb_str_tr_s, 2); rb_define_method(rb_cString, "delete", rb_str_delete, -1); rb_define_method(rb_cString, "squeeze", rb_str_squeeze, -1); rb_define_method(rb_cString, "count", rb_str_count, -1); rb_define_method(rb_cString, "tr!", rb_str_tr_bang, 2); rb_define_method(rb_cString, "tr_s!", rb_str_tr_s_bang, 2); rb_define_method(rb_cString, "delete!", rb_str_delete_bang, -1); rb_define_method(rb_cString, "squeeze!", rb_str_squeeze_bang, -1); rb_define_method(rb_cString, "each_line", rb_str_each_line, -1); rb_define_method(rb_cString, "each", rb_str_each_line, -1); rb_define_method(rb_cString, "each_byte", rb_str_each_byte, 0); rb_define_method(rb_cString, "sum", rb_str_sum, -1); rb_define_global_function("sub", rb_f_sub, -1); rb_define_global_function("gsub", rb_f_gsub, -1); rb_define_global_function("sub!", rb_f_sub_bang, -1); rb_define_global_function("gsub!", rb_f_gsub_bang, -1); rb_define_global_function("chop", rb_f_chop, 0); rb_define_global_function("chop!", rb_f_chop_bang, 0); rb_define_global_function("chomp", rb_f_chomp, -1); rb_define_global_function("chomp!", rb_f_chomp_bang, -1); rb_define_global_function("split", rb_f_split, -1); rb_define_global_function("scan", rb_f_scan, 1); rb_define_method(rb_cString, "slice", rb_str_aref_m, -1); rb_define_method(rb_cString, "slice!", rb_str_slice_bang, -1); id_to_s = rb_intern("to_s"); rb_fs = Qnil; rb_define_hooked_variable("$;", &rb_fs, 0, rb_str_setter); rb_define_hooked_variable("$-F", &rb_fs, 0, rb_str_setter); }
__label__pos
0.999753
Login Dump a model instance and related objects as a Python data structure Author: akaihola Posted: January 31, 2012 Language: Python Version: 1.3 Score: 0 (after 0 ratings) This utility makes a text dump of a model instance, including objects related by a forward or reverse foreign key. The result is a hierarchical data structure where • each instance is represented as a list of fields, • each field as a (<name>, <value>) tuple, • each <value> as a primitive type, a related object (as a list of fields), or a list of related objects. See the docstring for examples. We used this to make text dumps of parts of the database before and after running a batch job. The format was more useful than stock dumpdata output since all related data is included with each object. These dumps lend themselves particularly well for comparison with a visual diff tool like Meld. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 from django.db import models def shift_paths(exclude, name): return tuple(item.split('.', 1)[1] for item in exclude if item.startswith(('{0}.'.format(name), '*.'))) def deep_dump_instance(instance, depth=1, exclude=(), include=(), order_by=(), seen=None): """Deep-dumps fields of a model instance as (name, value) tuples Examples:: # create a fixture >>> my_poll = Poll.objects.create(question=u"What's up?", pub_date=datetime.datetime.now()) >>> choice_1 = my_poll.choice_set.create(choice='Not much', votes=5) >>> choice_2.choice_set.create(choice='The sky', votes=2) # recurse all related objects >>> deep_dump_instance(my_poll) [('question', u"What's up?"), ('pub_date', datetime.datetime(2012, 1, 30, 9, 48)), ('choice_set', [[('choice', u'Not much'), ('votes', 5)], [('choice', u'The sky'), ('votes', 2)]])] # skip all related objects >>> deep_dump_instance(my_poll, depth=0) [('question', u"What's up?"), ('pub_date', datetime.datetime(2012, 1, 30, 9, 48))] # exclude a field >>> deep_dump_instance(my_poll, exclude=['pub_date']) [('question', u"What's up?"), ('choice_set', [[('choice', u'Not much'), ('votes', 5)], [('choice', u'The sky'), ('votes', 2)]])] # only include a field in related objects >>> deep_dump_instance(choice_1, ... exclude=['*', 'question.*'], ... include=['poll', 'poll.pub_date']) [[('poll', [('pub_date', datetime.datetime(2012, 1, 30, 9, 48))])]] # sort related objects >>> deep_dump_instance(my_poll, ... exclude=['*'], ... include=['choice_set'], ... order_by=['choice_set.votes']) [('choice_set', [[('choice', u'The sky'), ('votes', 2)], [('choice', u'Not much'), ('votes', 5)]])] """ if not seen: seen = set() if (instance.__class__, instance.pk) in seen: return '<recursive>' seen.add((instance.__class__, instance.pk)) field_names = sorted( [field.name for field in instance._meta.fields] + [f.get_accessor_name() for f in instance._meta.get_all_related_objects()]) dump = [] exclude_all = '*' in exclude for name in field_names: if name in include or (not exclude_all and name not in exclude): try: value = getattr(instance, name) except models.ObjectDoesNotExist: value = None if value.__class__.__name__ == 'RelatedManager': if depth >= 1: related_objects = value.all() for ordering in order_by: parts = ordering.split('.') if len(parts) == 2 and parts[0] == name: related_objects = related_objects.order_by(parts[1]) value = [deep_dump_instance(related, depth=depth-1, exclude=shift_paths(exclude, name), include=shift_paths(include, name), order_by=shift_paths(order_by, name), seen=seen) for related in related_objects] else: continue elif isinstance(value, models.Model): if depth >= 1: value = deep_dump_instance(value, depth=depth-1, exclude=shift_paths(exclude, name), include=shift_paths(include, name), order_by=shift_paths(order_by, name), seen=seen) else: continue dump.append((name, value)) return dump More like this 1. Generate and render HTML Table by LLyaudet 4 days, 16 hours ago 2. My firs Snippets by GutemaG 1 week, 1 day ago 3. FileField having auto upload_to path by junaidmgithub 1 month, 2 weeks ago 4. LazyPrimaryKeyRelatedField by LLyaudet 1 month, 3 weeks ago 5. CacheInDictManager by LLyaudet 1 month, 3 weeks ago Comments ckarrie2 (on January 31, 2012): Interesting. Is there a way to "load" the data back? # Please login first before commenting.
__label__pos
0.995107
WP_REST_URL_Details_Controller::get_item_schema()publicWP 5.9.0 Retrieves the item's schema, conforming to JSON Schema. {} It's a method of the class: WP_REST_URL_Details_Controller{} No Hooks. Return Array. Item schema data. Usage $WP_REST_URL_Details_Controller = new WP_REST_URL_Details_Controller(); $WP_REST_URL_Details_Controller->get_item_schema(); Changelog Since 5.9.0 Introduced. Code of WP_REST_URL_Details_Controller::get_item_schema() WP 6.0 public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $this->schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'url-details', 'type' => 'object', 'properties' => array( 'title' => array( 'description' => sprintf( /* translators: %s: HTML title tag. */ __( 'The contents of the %s element from the URL.' ), '<title>' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'icon' => array( 'description' => sprintf( /* translators: %s: HTML link tag. */ __( 'The favicon image link of the %s element from the URL.' ), '<link rel="icon">' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'description' => array( 'description' => sprintf( /* translators: %s: HTML meta tag. */ __( 'The content of the %s element from the URL.' ), '<meta name="description">' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'image' => array( 'description' => sprintf( /* translators: 1: HTML meta tag, 2: HTML meta tag. */ __( 'The Open Graph image link of the %1$s or %2$s element from the URL.' ), '<meta property="og:image">', '<meta property="og:image:url">' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ); return $this->add_additional_fields_schema( $this->schema ); }
__label__pos
0.675106
function integral = disk01_quarter_monomial_integral ( e ) %*****************************************************************************80 % %% DISK01_QUARTER_MONOMIAL_INTEGRAL: monomial integrals in unit quarter disk. % % Discussion: % % The integration region is % % X^2 + Y^2 <= 1. % 0 <= X, 0 <= Y. % % The monomial is F(X,Y) = X^E(1) * Y^E(2). % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 05 May 2016 % % Author: % % John Burkardt % % Input: % % integer E(2), the exponents of X and Y in the % monomial. Each exponent must be nonnegative. % % Output: % % real INTEGRAL, the integral. % f1 = gamma ( ( e(1) + 3 ) / 2.0 ); f2 = gamma ( ( e(2) + 1 ) / 2.0 ); f3 = gamma ( ( e(1) + e(2) + 4 ) / 2.0 ); integral = f1 * f2 / f3 / 2.0 / ( 1.0 + e(1) ); return end
__label__pos
0.971058
Find Files and Folders with `find` in Bash Cameron Nokes InstructorCameron Nokes Share this video with your friends Send Tweet Published 5 years ago Updated 4 years ago find is a powerful tool that can not only find files but it can run a command on each matching file too. In this lesson, we’ll learn how to find all the images that match a pattern and run an image optimization tool on them. Instructor: [00:00] In my current working directory, I have an images folder. The images folder has several images in it, as you can see. Let's say that I wanted to find all of the PNGs in the folder. To do that, I would use the find command. I'll pass the images folder, and then I'll pass the name flag, and I'll do wildcard.png. [00:20] This might look like a regex, but it's not, actually. This is just a string that supports some special characters that do matching, so this will match any file name that ends with .png. [00:31] Let's run that. We can see it finds those two PNG files. If we do the same thing for JPGs, we can see it just returns that one, but we have two JPEGs in there. [00:43] Instead of using name, we can use iname. The iname is a case-insensitive name search. If we run that now, we can see this one is returned, as well. [00:53] Another useful one, for example, is if we do find. If I just wanted to find all folders in my current working directory, I would pass type D, and that'll return the images folder we just looked at. [01:05] I have another folder in here called dist, so we can just confirm that with the list here. We can combine type with name. If I wanted to find all folders named images, that would work, and just returns the one here. [01:21] Find also supports running an action on each match. For example, in my dist folder, I have two JS files, and then an image file. [01:32] Let's say that I wanted to delete all the JS files from the dist folder. I'll do find dist. I'll do name, and I'll do wildcard.built.js, and then I'll pass the delete flag. If we list it out, now we can see that that had to lead in my two JavaScript files in there. [01:51] If we want, we can get more custom, too. For example, if I wanted to run an image compression and optimization tool on each of the matching images, I could do that. [02:00] I do find images. I'll do name, and I'll just run this on the PNGs. I'll pass the exec flag. That lets us run an arbitrary command on each match. [02:11] I have a tool called pngquant that I have installed previously. Pngquant just optimizes PNG files and makes them smaller. [02:19] Find supports this special character. The two curly braces stand further from each matching file. [02:25] To end this little expression, you have to do your backslash, and then semicolon. Strange syntax, but if we run that, and then let's list out images, we can see that it worked. Pngquant, I've created these two optimized image files. [02:40] Find's a really handy tool. Refer to the documentation on it for more possibilities. The easy way to look at the documentation is if you run man-find. Man stands for manual, and so this will bring up all of find's options right here in your terminal. Vinícius Melo Vinícius Melo ~ 4 years ago Very Good Course... help me a lot in understand the linux bash/shell. Pascal Chouinard Pascal Chouinard ~ 4 years ago I hate find ... I now use https://github.com/sharkdp/fd Alex Alex ~ 4 years ago I am building a script that allows me to copy files (including a hashed js bundle) to a new folder. The filename is of the format bundle.[hash].js. Given that I want to do this every time I build the file (with a new hash), how can I find the file name so that I can use it in the cp command, without finding any other files that might be of the same format in child folders? Cameron Nokes Cameron Nokesinstructor ~ 4 years ago how can I find the file name so that I can use it in the cp command, without finding any other files that might be of the same format in child folders? find dist -name 'bundle.*.js' -maxdepth 1 -exec cp {} somewhere \; Sounds like something like that would work. You can use the -maxdepth option to prevent find from searching deeper than you want it to. Hopefully that works for you!
__label__pos
0.643206
Java Internalization - Quick Guide Advertisements Java Internalization - Overview Internalization Internalization or I18N refers to the capability of an Application to be able to serve users in multiple and different languages. Java has in-built support for Internalization. Java also provides formatting of numbers, currencies and adjustment of date and time accordingly. Java Internationalization helps to make a java application handle different languages, number formats, currencies, region specific time formatting. Localization Localization or L10N is the adaptability of an application that is how an application adapts itself with a specific language, number formats, date and time settings etc. A java application should be internationalized in order to be able to localize itself. Culturally Dependent Information Following information items often varies with different time zones or cultures. • Messages • Date • Time • Number • Currency • Measurements • Phone Numbers • Postal Addresses • GUI labels Internationalization Classes Java has a set of built-in classes which help in internationalization of an application. These classes are following: Sr.No.Class & Description 1 Locale Represents a language along with country/region. 2 ResourceBundle Contains localized text or objects. 3 NumberFormat Use to format numbers/currencies as per the locale. 4 DecimalFormat Use to format numbers as per customized format and as per locale. 5 DateFormat Use to format dates as per locale. 6 SimpleDateFormat Use to format dates as per customized format and as per locale. Java Internalization - Environment Setup In this chapter, we will discuss on the different aspects of setting up a congenial environment for Java. Local Environment Setup If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Following are the steps to set up the environment. Java SE is freely available from the link Download Java. You can download a version based on your operating system. Follow the instructions to download Java and run the .exe to install Java on your machine. Once you installed Java on your machine, you will need to set environment variables to point to correct installation directories − Setting Up the Path for Windows Assuming you have installed Java in c:\Program Files\java\jdk directory − • Right-click on 'My Computer' and select 'Properties'. • Click the 'Environment variables' button under the 'Advanced' tab. • Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'. Setting Up the Path for Linux, UNIX, Solaris, FreeBSD Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this. Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH = /path/to/java:$PATH' Popular Java Editors To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following − • Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. • Netbeans − A Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html. • Eclipse − A Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/. What is Next? Next chapter will teach you how to write and run your first Java program and some of the important basic syntaxes in Java needed for developing applications. Java Internalization - Locale Class A Locale object represents a specific geographical/political/cultural region. Any operation requiring a Locale to perform its task is called locale-sensitive operation and uses the Locale to master information relative to the user. For example, displaying a number is a locale-sensitive operation. The number should be formatted as per the customs and conventions of the user's native country, region, or culture. Locale Contents A Locale object contains the following: • Language - ISO 639 alpha-2 or alpha-3 language code, or registered language subtags up to 8 alpha letters. alpha-2 code must be used if both alpha-2 and alpha-3 code are present. The language field is case insensitive, but Locale always canonicalizes to lower case. • Script - ISO 15924 alpha-4 script code. The script field is case insensitive, but Locale always canonicalizes to title case. • Country (region) - ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code. The country field is case insensitive, but Locale always canonicalizes to upper case. • Variant - Any arbitrary value used to indicate a variation of a Locale. Where there are two or more variant values each indicating its own semantics, these values should be ordered by importance, with most important first, separated by underscore('_'). The variant field is case sensitive. • Extensions - A map from single character keys to string values, indicating extensions apart from language identification. The extensions in Locale implement the semantics and syntax of BCP 47 extension subtags and private use subtags. The extensions are case insensitive, but Locale canonicalizes all extension keys and values to lower case. Java Internalization - Example - Locale Details In this example, we'll get default locale and print its details. Then create a locale for "fr" and print its details. I18NTester.java import java.util.Locale; public class I18NTester { public static void main(String[] args) { Locale locale =Locale.getDefault(); System.out.println("Default Locale Properties:\n"); System.out.println(locale.getDisplayCountry()); System.out.println(locale.getDisplayLanguage()); System.out.println(locale.getDisplayName()); System.out.println(locale.getISO3Country()); System.out.println(locale.getISO3Language()); System.out.println(locale.getLanguage()); System.out.println(locale.getCountry()); Locale frenchLocale = new Locale("fr","fr"); System.out.println("\nfr Locale Properties:\n"); System.out.println(frenchLocale.getDisplayCountry()); System.out.println(frenchLocale.getDisplayLanguage()); System.out.println(frenchLocale.getDisplayName()); System.out.println(frenchLocale.getISO3Country()); System.out.println(frenchLocale.getISO3Language()); System.out.println(frenchLocale.getLanguage()); System.out.println(frenchLocale.getCountry()); } } Output It will print the following result. Default Locale Properties: United States English English (United States) USA eng en US fr Locale Properties: France French French (France) FRA fra fr FR Java Internalization - Example - Display Language In this example, we'll get display language per locale passed as an argument. I18NTester.java import java.util.Locale; public class I18NTester { public static void main(String[] args) { Locale defaultLocale = Locale.getDefault(); Locale enLocale = new Locale("en", "US"); Locale frLocale = new Locale("fr", "FR"); Locale esLocale = new Locale("es", "ES"); System.out.println(defaultLocale.getDisplayLanguage(enLocale)); System.out.println(defaultLocale.getDisplayLanguage(frLocale)); System.out.println(defaultLocale.getDisplayLanguage(esLocale)); } } Output It will print the following result. English anglais inglés Java Internalization - ResourceBundle Class ResourceBundle class is used to store text and objects which are locale sensitive. Generally we use property files to store locale specific text and then represent them using ResourceBundle object. Following are the steps to use locale specific properties file in a java based application. Step 1: Create properties files. Suppose we need properties file for English locale. Then create a properties file name XXX_en_US.properties where XXX is the name of the file and en_US represents the locale for English(US). Messages_en_US.properties message=Welcome to TutorialsPoint.COM! Let's now create properties file for French locale. Then create a properties file name XXX_fr_FR.properties where XXX is the name of the file and fr_FR represents the locale for French(France). Messages_fr_FR.properties message=Bienvenue sur TutorialsPoint.COM! Here you can figure out that the key is same but the value is locale specific in both the properties file. Step 2: Create ResourceBundle object Create ResourceBundle object with properties file name and locale using following syntax. ResourceBundle bundle = ResourceBundle.getBundle("Messages", Locale.US); Step 3: Get the value from ResourceBundle object. Get the value from ResourceBundle object by passing the key. String value = bundle.getString("message"); Example Following example illustrate the use of ResourceBundle objects to display locale specific values from properties files. IOTester.java import java.util.Locale; import java.util.ResourceBundle; public class I18NTester { public static void main(String[] args) { ResourceBundle bundle = ResourceBundle.getBundle("Messages", Locale.US); System.out.println("Message in "+Locale.US +": "+bundle.getString("message")); bundle = ResourceBundle.getBundle("Messages", Locale.FRANCE); System.out.println("Message in "+Locale.FRANCE +": "+bundle.getString("message")); } } Output It will print the following result. Message in en_US: Welcome to TutorialsPoint.COM! Message in fr_FR: Bienvenue sur TutorialsPoint.COM! Notes for Naming Conventions Following are the naming conventions for the properties file. • For properties file mapped to default locale, no prefix is mandatory. message_en_US.properties is equivalent to message.properties. • For properties file mapped to locale, prefix can be attached in two ways. message_fr.properties is equivalent to message_fr_FR.properties. Java Internalization - NumberFormat Class The java.text.NumberFormat class is used for formatting numbers and currencies as per a specific Locale. Number formats varies from country to country. For example, In Denmark fractions of a number are separated from the integer part using a comma whereas in England they use a dot as separator. Example - Format Numbers In this example, we're formatting numbers based on US locale and Danish Locale. IOTester.java import java.text.NumberFormat; import java.util.Locale; public class I18NTester { public static void main(String[] args) { Locale enLocale = new Locale("en", "US"); Locale daLocale = new Locale("da", "DK"); NumberFormat numberFormat = NumberFormat.getInstance(daLocale); System.out.println(numberFormat.format(100.76)); numberFormat = NumberFormat.getInstance(enLocale); System.out.println(numberFormat.format(100.76)); } } Output It will print the following result. 100,76 100.76 Java Internalization - Format Currencies In this example, we're formatting currencies based on US locale and Danish Locale. IOTester.java import java.text.NumberFormat; import java.util.Locale; public class I18NTester { public static void main(String[] args) { Locale enLocale = new Locale("en", "US"); Locale daLocale = new Locale("da", "DK"); NumberFormat numberFormat = NumberFormat.getCurrencyInstance(daLocale); System.out.println(numberFormat.format(100.76)); numberFormat = NumberFormat.getCurrencyInstance(enLocale); System.out.println(numberFormat.format(100.76)); } } Output It will print the following result. kr 100,76 $100.76 Java Internalization - Format Percentages In this example, we're formatting numbers in percentage format. IOTester.java import java.text.NumberFormat; import java.util.Locale; public class I18NTester { public static void main(String[] args) { Locale enLocale = new Locale("en", "US"); NumberFormat numberFormat = NumberFormat.getPercentInstance(enLocale); System.out.println(numberFormat.format(0.76)); } } Output It will print the following result. 76% Java Internalization - Set Min/Max Precision In this example, we're setting min and max digits for both integer as well as fractional part of a number. IOTester.java import java.text.NumberFormat; import java.util.Locale; public class I18NTester { public static void main(String[] args) { Locale enLocale = new Locale("en", "US"); NumberFormat numberFormat = NumberFormat.getInstance(enLocale); numberFormat.setMinimumIntegerDigits(2); numberFormat.setMaximumIntegerDigits(3); numberFormat.setMinimumFractionDigits(2); numberFormat.setMaximumFractionDigits(3); System.out.println(numberFormat.format(12234.763443)); } } Output It will print the following result. 234.763 Java Internalization - Set Rounding Mode In this example, we're showcasing Rounding Mode. IOTester.java import java.math.RoundingMode; import java.text.NumberFormat; import java.util.Locale; public class I18NTester { public static void main(String[] args) { Locale enLocale = new Locale("en", "US"); NumberFormat numberFormat = NumberFormat.getInstance(enLocale); numberFormat.setMinimumFractionDigits(0); numberFormat.setMaximumFractionDigits(0); System.out.println(numberFormat.format(99.50)); numberFormat.setRoundingMode(RoundingMode.HALF_DOWN); System.out.println(numberFormat.format(99.50)); } } Output It will print the following result. 100 99 Java Internalization - Parsing Numbers In this example, we're showcasing parsing of number present in different locale. IOTester.java import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; public class I18NTester { public static void main(String[] args) throws ParseException { Locale enLocale = new Locale("en", "US"); Locale daLocale = new Locale("da", "DK"); NumberFormat numberFormat = NumberFormat.getInstance(daLocale); System.out.println(numberFormat.parse("100,76")); numberFormat = NumberFormat.getInstance(enLocale); System.out.println(numberFormat.parse("100,76")); } } Output It will print the following result. 100.76 10076 Java Internalization - DecimalFormat Class The java.text.DecimalFormat class is used for formatting numbers as per customized format and as per locale. Example - Format Numbers In this example, we're formatting numbers based on a given pattern. IOTester.java import java.text.DecimalFormat; public class I18NTester { public static void main(String[] args) { String pattern = "####,####.##"; double number = 123456789.123; DecimalFormat numberFormat = new DecimalFormat(pattern); System.out.println(number); System.out.println(numberFormat.format(number)); } } Output It will print the following result. 1.23456789123E8 1,2345,6789.12 Java Internalization - Format Patterns Followings is the use of characters in formatting patterns. Sr.No.Class & Description 1 0 To display 0 if less digits are present. 2 # To display digit ommitting leading zeroes. 3 . Decimal separator. 4 , Grouping separator. 5 E Mantissa and Exponent separator for exponential formats. 6 ; Format separator. 7 - Negative number prefix. 8 % Shows number as percentage after multiplying with 100. 9 ? Shows number as mille after multiplying with 1000. 10 X To mark character as number prefix/suffix. 11 ' To mark quote around special characters. In this example, we're formatting numbers based on different patterns. IOTester.java import java.text.DecimalFormat; public class I18NTester { public static void main(String[] args) { String pattern = "###.###"; double number = 123456789.123; DecimalFormat numberFormat = new DecimalFormat(pattern); System.out.println(number); //pattern ###.### System.out.println(numberFormat.format(number)); //pattern ###.# numberFormat.applyPattern("###.#"); System.out.println(numberFormat.format(number)); //pattern ###,###.## numberFormat.applyPattern("###,###.##"); System.out.println(numberFormat.format(number)); number = 9.34; //pattern 000.### numberFormat.applyPattern("000.##"); System.out.println(numberFormat.format(number)); } } Output It will print the following result. 1.23456789123E8 1,2345,6789.12 Java Internalization - Locale Specific DecimalFormat By default, DecimalFormat object is using the JVM's locale. We can change the default locale while creating the DecimalFormat object using NumberFormat class. In the example below, we'll use same pattern for two different locale and you can spot the difference in the output. IOTester.java import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; public class I18NTester { public static void main(String[] args) { String pattern = "###.##"; double number = 123.45; Locale enlocale = new Locale("en", "US"); Locale dalocale = new Locale("da", "DK"); DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(enlocale); decimalFormat.applyPattern(pattern); System.out.println(decimalFormat.format(number)); decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(dalocale); decimalFormat.applyPattern(pattern); System.out.println(decimalFormat.format(number)); } } Output It will print the following result. 123.45 123,45 Java Internalization - DecimalFormatSymbols Class Using DecimalFormatSymbols class, the default separator symbols, grouping separator symbols etc. can be changed. Following example is illustrating the same. IOTester.java import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; public class I18NTester { public static void main(String[] args) { String pattern = "#,###.###"; double number = 126473.4567; DecimalFormat decimalFormat = new DecimalFormat(pattern); System.out.println(decimalFormat.format(number)); DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); decimalFormatSymbols.setDecimalSeparator(';'); decimalFormatSymbols.setGroupingSeparator(':'); decimalFormat = new DecimalFormat(pattern, decimalFormatSymbols); System.out.println(decimalFormat.format(number)); } } Output It will print the following result. 126,473.457 126:473;457 Java Internalization - Grouping Digits Using setGroupingSize() method of DecimalFormat, default grouping of numbers can be changed. Following example is illustrating the same. IOTester.java import java.text.DecimalFormat; public class I18NTester { public static void main(String[] args) { double number = 121223232473.4567; DecimalFormat decimalFormat = new DecimalFormat(); System.out.println(number); System.out.println(decimalFormat.format(number)); decimalFormat.setGroupingSize(4); System.out.println(decimalFormat.format(number)); } } Output It will print the following result. 1.212232324734567E11 121,223,232,473.457 1212,2323,2473.457 Java Internalization - DateFormat Class java.text.DateFormat class formats dates as per the locale. As different coutries use different formats to display dates. This class is extremely useful in dealing with dates in internalization of application. Following example show how to create and use DateFormat Class. IOTester.java import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class I18NTester { public static void main(String[] args) { Locale locale = new Locale("da","DK"); DateFormat dateFormat = DateFormat.getDateInstance(); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); System.out.println(dateFormat.format(new Date())); } } Output It will print the following result. Nov 29, 2017 29-11-2017 Java Internalization - Formatting Dates DateFormat class provides various formats to format the date. Following is list of some of the formats. • DateFormat.DEFAULT • DateFormat.SHORT • DateFormat.MEDIUM • DateFormat.LONG • DateFormat.FULL In following example we'll show how to use different formats. IOTester.java import java.text.DateFormat; import java.util.Date; public class I18NTester { public static void main(String[] args) { DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getDateInstance(DateFormat.SHORT); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getDateInstance(DateFormat.LONG); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getDateInstance(DateFormat.FULL); System.out.println(dateFormat.format(new Date())); } } Output It will print the following result. Nov 29, 2017 11/29/17 Nov 29, 2017 November 29, 2017 Wednesday, November 29, 2017 Java Internalization - Formatting Time DateFormat class provides various formats to format the time. DateFormat.getTimeInstance() method is to be used. See the example below. In following example we'll show how to use different formats to format time. IOTester.java import java.text.DateFormat; import java.util.Date; public class I18NTester { public static void main(String[] args) { DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getTimeInstance(DateFormat.LONG); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getTimeInstance(DateFormat.FULL); System.out.println(dateFormat.format(new Date())); } } Output It will print the following result. 4:11:21 PM 4:11 PM 4:11:21 PM 4:11:21 PM IST 4:11:21 PM IST Java Internalization - Formatting Date and Time DateFormat class provides various formats to format the date and time together. DateFormat.getDateTimeInstance() method is to be used. See the example below. In following example we'll show how to use different formats to format date and time. IOTester.java import java.text.DateFormat; import java.util.Date; public class I18NTester { public static void main(String[] args) { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); System.out.println(dateFormat.format(new Date())); dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); System.out.println(dateFormat.format(new Date())); } } Output It will print the following result. Nov 29, 2017 4:16:13 PM 11/29/17 4:16 PM Nov 29, 2017 4:16:13 PM November 29, 2017 4:16:13 PM IST Wednesday, November 29, 2017 4:16:13 PM IST Java Internalization - SimpleDateFormat Class java.text.SimpleDateFormat class formats dates as per the given pattern. It is also used to parse dates from string where string contains date in mentioned format. See the following example of using SimpleDateFormat class. IOTester.java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class I18NTester { public static void main(String[] args) throws ParseException { String pattern = "dd-MM-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); Date date = new Date(); System.out.println(date); System.out.println(simpleDateFormat.format(date)); String dateText = "29-11-2017"; date = simpleDateFormat.parse(dateText); System.out.println(simpleDateFormat.format(date)); } } Output It will print the following result. Wed Nov 29 17:01:22 IST 2017 29-11-2017 29-11-2017 Java Internalization - Locale specific SimpleDateFormat Locale can be used to create locale specific formatting over a pattern in SimpleDateFormat class. See the following example of using locale specific SimpleDateFormat class. IOTester.java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class I18NTester { public static void main(String[] args) throws ParseException { Locale locale = new Locale("da", "DK"); String pattern = "EEEEE MMMMM yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); Date date = new Date(); System.out.println(date); System.out.println(simpleDateFormat.format(date)); simpleDateFormat = new SimpleDateFormat(pattern,locale); System.out.println(simpleDateFormat.format(date)); } } Output It will print the following result. Wed Nov 29 17:48:14 IST 2017 Wednesday November 2017 onsdag november 2017 Java Internalization - DecimalFormatSymbols Class Using DecimalFormatSymbols class, the default separator symbols, grouping separator symbols etc. can be changed. Following example is illustrating the same. IOTester.java import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; public class I18NTester { public static void main(String[] args) { String pattern = "#,###.###"; double number = 126473.4567; DecimalFormat decimalFormat = new DecimalFormat(pattern); System.out.println(decimalFormat.format(number)); DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); decimalFormatSymbols.setDecimalSeparator(';'); decimalFormatSymbols.setGroupingSeparator(':'); decimalFormat = new DecimalFormat(pattern, decimalFormatSymbols); System.out.println(decimalFormat.format(number)); } } Output It will print the following result. 126,473.457 126:473;457 Java Internalization - Date Format Patterns Followings is the use of characters in date formatting patterns. Sr.No.Class & Description 1 G To display Era. 2 y To display Year. Valid values yy, yyyy. 3 M To display Month. Valid values MM, MMM or MMMMM. 4 d To display day of month. Valid values d, dd. 5 h To display hour of day (1-12 AM/PM). Valid value hh. 6 H To display hour of day (0-23). Valid value HH. 7 m To display minute of hour (0-59). Valid value mm. 8 s To display second of minute (0-59). Valid value ss. 9 S To display milliseconds of minute (0-999). Valid value SSS. 10 E To display Day in week (e.g Monday, Tuesday etc.) 11 D To display Day in year (1-366). 12 F To display Day of week in month (e.g. 1st Thursday of December). 13 w To display Week in year (1-53). 14 W To display Week in month (0-5) 15 a To display AM / PM 16 k To display Hour in day (1-24). 17 K To display Hour in day, AM / PM (0-11). 18 z To display Time Zone. In this example, we're formatting dates based on different patterns. IOTester.java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class I18NTester { public static void main(String[] args) throws ParseException { String pattern = "dd-MM-yy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); Date date = new Date(); System.out.println(simpleDateFormat.format(date)); pattern = "MM-dd-yyyy"; simpleDateFormat = new SimpleDateFormat(pattern); System.out.println(simpleDateFormat.format(date)); pattern = "yyyy-MM-dd HH:mm:ss"; simpleDateFormat = new SimpleDateFormat(pattern); System.out.println(simpleDateFormat.format(date)); pattern = "EEEEE MMMMM yyyy HH:mm:ss.SSSZ"; simpleDateFormat = new SimpleDateFormat(pattern); System.out.println(simpleDateFormat.format(date)); } } Output It will print the following result. 29-11-17 11-29-2017 2017-11-29 18:47:42 Wednesday November 2017 18:47:42.787+0530 Java Internalization - UTC UTC stands for Co-ordinated Universal Time. It is time standard and is commonly used across the world. All time zones are computed comparatively with UTC as offset. For example, time in Copenhagen, Denmark is UTC + 1 means UTC time plus one hour. It is independent of Day light savings and should be used to store date and time in databases. Conversion of time zones Following example will showcase conversion of various time zones. We'll print hour of the day and time in milliseconds. First will vary and second will remain same. IOTester.java import java.text.ParseException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; public class I18NTester { public static void main(String[] args) throws ParseException { Calendar date = new GregorianCalendar(); date.setTimeZone(TimeZone.getTimeZone("Etc/UTC")); date.set(Calendar.HOUR_OF_DAY, 12); System.out.println("UTC: " + date.get(Calendar.HOUR_OF_DAY)); System.out.println("UTC: " + date.getTimeInMillis()); date.setTimeZone(TimeZone.getTimeZone("Europe/Copenhagen")); System.out.println("CPH: " + date.get(Calendar.HOUR_OF_DAY)); System.out.println("CPH: " + date.getTimeInMillis()); date.setTimeZone(TimeZone.getTimeZone("America/New_York")); System.out.println("NYC: " + date.get(Calendar.HOUR_OF_DAY)); System.out.println("NYC: " + date.getTimeInMillis()); } } Output It will print the following result. UTC: 12 UTC: 1511956997540 CPH: 13 CPH: 1511956997540 NYC: 7 NYC: 1511956997540 Available Time Zones Following example will showcase the time zones available with the system. IOTester.java import java.text.ParseException; import java.util.TimeZone; public class I18NTester { public static void main(String[] args) throws ParseException { String[] availableIDs = TimeZone.getAvailableIDs(); for(String id : availableIDs) { System.out.println("Timezone = " + id); } } } Output It will print the following result. Timezone = Africa/Abidjan Timezone = Africa/Accra ... Timezone = VST Java Internalization - Unicode Conversion from/to String In java, text is internally stored in Unicode format. If input/output is in different format then conversion is required. Conversion Following example will showcase conversion of a Unicode String to UTF8 byte[] and UTF8 byte[] to Unicode byte[]. IOTester.java import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.text.ParseException; public class I18NTester { public static void main(String[] args) throws ParseException, UnsupportedEncodingException { String unicodeString = "\u00C6\u00D8\u00C5" ; //convert Unicode to UTF8 format byte[] utf8Bytes = unicodeString.getBytes(Charset.forName("UTF-8")); printBytes(utf8Bytes, "UTF 8 Bytes"); //convert UTF8 format to Unicode String converted = new String(utf8Bytes, "UTF8"); byte[] unicodeBytes = converted.getBytes(); printBytes(unicodeBytes, "Unicode Bytes"); } public static void printBytes(byte[] array, String name) { for (int k = 0; k < array.length; k++) { System.out.println(name + "[" + k + "] = " + array[k]); } } } Output It will print the following result. UTF 8 Bytes[0] = -61 UTF 8 Bytes[1] = -122 UTF 8 Bytes[2] = -61 UTF 8 Bytes[3] = -104 UTF 8 Bytes[4] = -61 UTF 8 Bytes[5] = -123 Unicode Bytes[0] = -58 Unicode Bytes[1] = -40 Unicode Bytes[2] = -59 Java Internalization - Unicode Conversion from/to Reader/Writer Reader and Writer classes are character oriented stream classes. These can be used to read and convert Unicode characters. Conversion Following example will showcase conversion of a Unicode String to UTF8 byte[] and UTF8 byte[] to Unicode byte[] using Reader and Writer classes. IOTester.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.text.ParseException; public class I18NTester { public static void main(String[] args) throws ParseException, IOException { String input = "This is a sample text" ; InputStream inputStream = new ByteArrayInputStream(input.getBytes()); //get the UTF-8 data Reader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8")); //convert UTF-8 to Unicode int data = reader.read(); while(data != -1){ char theChar = (char) data; System.out.print(theChar); data = reader.read(); } reader.close(); System.out.println(); //Convert Unicode to UTF-8 Bytes ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(outputStream, Charset.forName("UTF-8")); writer.write(input); writer.close(); String out = new String(outputStream.toByteArray()); System.out.println(out); } } Output It will print the following result. This is a sample text This is a sample text Print Advertisements
__label__pos
0.994131
Export (0) Print Expand All Send-SmigServerData Windows Server 2012 R2 and Windows 8.1 Updated: November 20, 2013 Applies To: Windows 8.1, Windows PowerShell 4.0, Windows Server 2012 R2 Send-SmigServerData Migrates folders, files, and associated permissions and share properties from a source server to a destination server through port 7000. The cmdlet Receive-SmigServerData must be run on the destination server at the same time Send-SmigServerData is running on the source server. Syntax Parameter Set: Default Send-SmigServerData [-ComputerName] <String> [-Password] <SecureString> [-Include] <MigrationIncludeTypes> {All | Data | Share} [-SourcePath] <String> [-DestinationPath] <String> [[-Recurse]] [[-Force]] [-Confirm] [-WhatIf] [ <CommonParameters>] Detailed Description Migrates folders, files, and associated permissions and share properties from the local server to a destination server through port 7000. The cmdlet Receive-SmigServerData must be started on the destination server to receive data. By default, the cmdlet Send-SmigServerData can wait for a maximum of five minutes to establish a connection with the cmdlet Receive-SmigServerData on the destination server. You can use a registry key to change the default maximum connection time; for more information about this registry setting, see the Notes. In this release of Windows Server, you can send and receive data between servers that are not necessarily on the same subnets. You can also specify IP addresses as the names of the source or destination servers. To support migration across subnets, and migrate by specifying IP addresses, port numbers 7001 and 7002 must be opened on source and destination servers. File access rights are maintained during the migration; the same set of users is able to access files on the destination server after they have been migrated. Because files are sent by using an encrypted connection, a password must be provided to decrypt migrated files on both the source and destination servers. Transporting encrypted files (EFS) and junction points is not supported. For online Help about the Windows Server Migration Tools cmdlets, see http://go.microsoft.com/fwlink/?LinkId=246313. Parameters -ComputerName<String> Specifies the name or IP address of the destination server to which you want to copy data. Aliases none Required? true Position? 1 Default Value none Accept Pipeline Input? false Accept Wildcard Characters? false -DestinationPath<String> Specifies the path on the destination server to which you want to copy data. To avoid migration failures, verify that the destination path you specify exists for share-only migration. For other migration types, verify that the path can be created on the destination computer. The path must be a valid local path. The path length cannot be longer than 246 characters. Wildcard characters are not supported. Aliases none Required? true Position? 5 Default Value none Accept Pipeline Input? false Accept Wildcard Characters? false -Force Overwrites existing files automatically if the files that you are migrating from the source server are newer. Also overwrites existing shares' properties if the shares' names already exist on the source server. Aliases none Required? false Position? 9 Default Value none Accept Pipeline Input? false Accept Wildcard Characters? false -Include<MigrationIncludeTypes> Specifies the type of content to copy to the destination server. The following are acceptable values for this parameter:      - Data: Copies only files in the folder designated by the SourcePath parameter to the folder designated by the -DestinationPath parameter. Subfolders and their content are not copied unless the Recurse parameter is added.      - Share : Copies only the share properties assigned to the folder specified in the SourcePath parameter to the folder specified in the DestinationPath parameter. For example, if a folder was shared on the source server, it is shared on the destination server if the Share value is provided in the cmdlet, thereby preserving all share properties and permissions. Share properties for subfolders and their content are not copied unless the Recurse parameter is added. The files and subfolders in the folder designated by SourcePath are not migrated. To avoid migration failures, verify that the folder specified in the DestinationPath parameter (and all subfolders if the Recurse parameter is added) exists.      - All: Copies both data and associated share properties. Aliases none Required? true Position? 3 Default Value none Accept Pipeline Input? false Accept Wildcard Characters? false -Password<SecureString> Specifies the password, as a secure string, to encrypt the data transfer by using the 256-bit advanced encryption standard (AES). The secure string can be obtained by entering the command Read-Host -AsSecureString or ConvertTo-Securestring. You must specify a password to protect your data because transferred data is broadcast over a network. If the Password parameter is not added to your command, you are prompted to specify a password after entering your command. The password length must be a minimum of six characters and a maximum of 260 characters. Aliases none Required? true Position? 2 Default Value none Accept Pipeline Input? false Accept Wildcard Characters? false -Recurse Copies all content of the type specified by Include parameter in the path specified in the SourcePath parameter. If this parameter is not used, subfolders of the SourcePath are not copied. Aliases none Required? false Position? 7 Default Value none Accept Pipeline Input? false Accept Wildcard Characters? false -SourcePath<String> Specifies the folder on the source server from which you want to copy data. To avoid migration failures, it is required that you first verify that the source path you specify exists on the source computer, except in the case of share-only migration. The path must be a valid local path. The path length cannot be longer than 246 characters. Wild card characters are not supported. Aliases none Required? true Position? 4 Default Value none Accept Pipeline Input? false Accept Wildcard Characters? false -Confirm Prompts you for confirmation before running the cmdlet. Required? false Position? named Default Value false Accept Pipeline Input? false Accept Wildcard Characters? false -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. Required? false Position? named Default Value false Accept Pipeline Input? false Accept Wildcard Characters? false <CommonParameters> This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see    about_CommonParameters. Inputs The input type is the type of the objects that you can pipe to the cmdlet. Outputs The output type is the type of the objects that the cmdlet emits. • Microsoft.Windows.ServerManager.Migration.Commands.MigrationResult [] A MigrationResult object contains basic information about the success or failure of a requested migration item. Notes • The Windows Server Migration Tools deployment log file is located in %windir%\Logs\SmigDeploy.log. Other Windows Server Migration Tools log files are created at the following locations:      - %windir%\Logs\ServerMigration.log      - On Windows Server 2008 and later versions: %localappdata%\SvrMig\Log      - On Windows Server 2003: %userprofile%\Local Settings\Application Data\SvrMig\Log If the log files cannot be created at these locations, ServerMigration.log and SmigDeploy.log will be created at %temp%, and other logs will be created at %windir%\System32. The maximum size of all log files (in MB) is stored in the following registry key. When the log file grows larger than the size specified in the registry key, the log file is deleted. Logging begins again in a new log file that uses the same file name and path. The default maximum log size is 200 MB.      - Key: HKLM\Software\Microsoft\ServerMigration      - Value: MaxLogSize (REG_DWORD)      - Data: Whole numbers between 1 and 1000 (represents log size, in MB) The maximum connection time for Send-SmigServerData and Receive-SmigServerData cmdlet is stored in the following registry key. Send-SmigServerData and Receive-SmigServerData operations terminate if a connection cannot be established within the specified time. The default maximum connection time is 300 seconds, or five minutes.      - Key: HKLM\Software\Microsoft\ServerMigration      - Value: MaxConnectionTime (REG_DWORD)      - Data: Between 1 and 3600 (represents connection time, in seconds). If a value larger than 3600 is specified, 3600 seconds is used as the maximum connection time. Examples EXAMPLE 1 This sample command migrates all files from the folder c:\users on the local (source) computer to the folder d:\shares\users on the destination computer. By default, subfolders in c:\users are not transferred. The command uses the computer name Server2, as provided in the ComputerName parameter, to find the destination server in the subnet. Because a password is not provided in this sample command, after entering the command, the user is prompted to enter a password for encrypting the migrated data. Password characters are displayed as asterisks (*).When the password is entered, the value is passed to the command as a SecureString. By using the -Verbose parameter, the command also displays detailed information about the migration operation. PS C:\> Send-SmigServerData -include Data -ComputerName "Server2" -SourcePath "c:\users" -DestinationPath "d:\shares\users" -Verbose EXAMPLE 2 In this example, the first line of the command instructs the migration utilities to convert the data encryption password, represented by "password," to a secure string, and store it in the variable $pass. The second sample command migrates only share status and permissions for folder c:\users and for all subfolders by using the -Include Share and the Recurse parameters. The files and subfolders in folder c:\users are not migrated. This command also sets the value of the variable $pass, specified in the first command, as the password to encrypt the data transfer. The command uses the computer name Server2, as provided in the ComputerName parameter, to find the destination server in the subnet. By using the -Verbose parameter, the command also displays detailed information about the migration operation. PS C:\> $pass = convertto-securestring -string "password" -asplaintext -force PS C:\> Send-SmigServerData -include Share -ComputerName "Server2" -SourcePath "c:\users" -DestinationPath "d:\shares\users" -Recurse -Password $pass -Verbose EXAMPLE 3 In this example, the command migrates all migration data in the folder C:\users on the local server to the folder D:\shares\users on a remote server, Server2. Because the Recurse parameter has been added, the command also migrates data that is stored in subfolders of the source folder. To encrypt the data as it is transferred to the destination server, the Password parameter is added. The value of the Password parameter is actually a second command, (Read-Host "Enter a Password:" -AsSecureString), to prompt the administrator to provide a password, and encrypt the provided password as a secure string. Finally, the Verbose parameter is added to display full details about the actions and progress of the command. PS C:\> Send-SmigServerData -include All -ComputerName "Server2" -SourcePath "c:\users" -DestinationPath "d:\shares\users" -Recurse -Password (Read-Host "Enter a Password:" -AsSecureString) -Verbose Was this page helpful? (1500 characters remaining) Thank you for your feedback Show: © 2014 Microsoft
__label__pos
0.999734
Shortcuts Guards Overview From a UX perspective, TorchDynamo is very easy to use. The user invokes torchdynamo.optimize as an annotation: @torchdynamo.optimize(my_compiler) def fn_foo(bar): Where a complete example looks like this: from typing import List import torch from torch import _dynamo as torchdynamo def my_compiler(gm: torch.fx.GraphModule, example_inputs: List[torch.Tensor]): print("my_compiler() called with FX graph:") gm.graph.print_tabular() return gm.forward # return a python callable @torchdynamo.optimize(my_compiler) def toy_example(a, b): x = a / (torch.abs(a) + 1) if b.sum() < 0: b = b * -1 return x * b for _ in range(100): toy_example(torch.randn(10), torch.randn(10)) This allows TorchDynamo to capture the interpreted Python frames, grab any and all relevant information, and speed things up wherever it can. The speedup comes from a few places, and can be rather dependent on the backend (my_compiler in the example above) provided, but the one speedup that is important in this section is caching. Caching itself is not a direct speedup but a critical enablement that prevents recompilation. We dig a hole with dynamo, and caching allows us to get out. It enables us to hold perf neutrality while then enabling backends - the true source of our speedups. With even a pass-through no-op backend provided: def my_compiler(gm: torch.fx.GraphModule, example_inputs: List[torch.Tensor]): return gm.forward We can see TorchDynamo speeding up Python execution even on regular Python, not just PyTorch. Caching and Guards Overview TorchDynamo operates through caching transformed (by TorchDynamo) user bytecode. When TorchDynamo receives a frame for evaluation, it checks if the objects referenced in the frame have changed in certain ways, and if not, TorchDynamo reads the previously transformed user bytecode to evaluate it. In this section, we will focus on how we can identify whether or not the objects referenced in the frame have changed. This is a critical piece of functionality in TorchDynamo, because it drives the entire invalidation lifecycle. This functionality is called guards. At a very high level, the flow can be summarized like this: 1. TorchDynamo receives a Python frame. 2. It converts the frame (1) passing it through instruction translation. 3. For the objects captured in (2), TorchDynamo creates tracking objects that are: * tracked on an output graph, which is an internal specialization of a torch.fx.Tracer * guards 4. TorchDynamo processes the guard objects created in (3), turning them into a generated Python function, check_fn, associated with a piece of code. 5. The check_fn is evaluated whenever we encounter this code a subsequent time - if a check_fn passes and evaluates to True, TorchDynamo identifies the code in the cache and the code encountered here as same, and can be safely used. If it fails and evaluates to False, TorchDynamo identifies the code in the cache as not valid, and can be thrown out in favor of a new entry, through recompilation or a graph break. Python Frame Evaluation and PEP 523 The functionality of TorchDynamo is based on PEP 523. TorchDynamo installs a frame evaluation function on Python by using _PyInterpreterState_SetEvalFrameFunc. TorchDynamo has a hook where Python can hand control back to us during evaluation. The function we have installed is convert_frame or convert_frame_assert in the nopython=True case, but glossing over that nuance for now, let’s take a look at convert_frame_assert, as convert_frame proxies to it. We can find it on line 20 of convert_frame.py, with a signature as follows: def convert_frame_assert(compiler_fn: Callable, one_graph=True): This function wraps the entry point of where Python invokes TorchDynamo with a frame: def _convert_frame_assert(frame: types.FrameType, cache_size: int): Here is what this function does: 1. Checks if it has seen this code(see: f_code here) before and exits early if it did. 2. Checks if the code is an unsupported case. 3. Checks if the cache_size (second arg above) crosses the limit defined in the config, cache_size_limit. If it has, the function drops the frame and logs warnings. This helps to avoid constant recompilation of a frame as it generally means that the frame is hot in an unexpected way and caching it produces needless overhead, as it is likely to get evicted the next time it is encountered. 4. Passes the frame, alongside a function that creates an InstructionTranslator through bytecode transformation, via transform_code_object. A few crucial things happen under the hood here: 1. New code is produced through transform_code_object. 2. An FX tracer named output is produced through InstructionTranslator. This can be a bit confusing, as InstructionTranslator is not an fx tracer, but its stored in a variable named tracer, and its output*isan `fx`tracer. 3. The function produces guards and stores them on output above. 4. The function produces output_instructions and stores them on output above. 5. The function maps the newly produced transformed code to the initial code it read off the frame. This mapping is worth remembering, we will refer to it much later on below where we cover guard failures. 5. Using the transformed code from 4.1 and the guards from 4.3, the function produces a GuardedCode. Now that we have learned about frame evaluation, let’s review InstructionTranslator, and see how it turns the frame we handed it over into TorchDynamo internal types. InstructionTranslator InstructionTranslator does a lot! We won’t cover the details of everything it does, but most importantly for this document, it produces a mapping of symbolic_locals which maintains a mapping from the frame’s f_locals to TorchDynamo internal Variable objects (more on these in a moment. symbolic_locals is filled via traversing the frame’s locals: self.symbolic_locals = collections.OrderedDict( (k, VariableBuilder(self, LocalSource(k))(f_locals[k])) for k in vars if k in f_locals ) The important component here is the invocation of a call into VariableBuilder. VariableBuilder’s call implementation proxies into a function called _wrap, which in turn both constructs instances of VariableTracker and calls make_guards on them. More on that later. This mapping, in turn, is critical as each Variable has associated guards, which are then passed to self.output, the instance of OutputGraph, an fx tracer, mentioned in 4.2 of the section above. If you recall, this OutputGraph, stored in a variable called output is where our guards are stored before being passed on to become GuardedCode How does InstructionTranslator do this? At the heart of it, there is a loop that is pumped, which drives a function step. step is just that - a single processing step, taking exactly one instruction and doing something with it. Note These are real instructions processed by TorchDynamo’s transform_code_object, and it is pretty cool. Note This section purposely skips the details of dis.get_instructions. For the example above, here is a snippet of a what a few Instruction's may look like: Instruction(opcode=124, opname='LOAD_FAST', arg=0, argval='b', offset=32, starts_line=8, is_jump_target=True, target=None) Instruction(opcode=100, opname='LOAD_CONST', arg=3, argval=-1, offset=34, starts_line=None, is_jump_target=False, target=None) Instruction(opcode=20, opname='BINARY_MULTIPLY', arg=None, argval=None, offset=36, starts_line=None, is_jump_target=False, target=None) This is the core functionality of this function. Take a look at the opname, and then take a look at this little snippet from inside step; if not hasattr(self, inst.opname): unimplemented(f"missing: {inst.opname}") getattr(self, inst.opname)(inst) As we can see, the function checks if the current class, the InstructionTranslator has an attribute set matching the operator name (for example, LOAD_CONST). If it does, the function invokes it, passing the whole instruction object in. If it does not, the function drops the frame as unimplemented. For the LOAD_CONST example, we can see that we do indeed support it, with a relatively straightforward definition: def LOAD_CONST(self, inst): self.push(ConstantVariable(value=inst.argval)) We can see that this function creates a new instance of the class ConstantVariable , with a value, in our example case, -1, and then pushes it onto the stack. There are dozens of such methods - see symbolic_convert.py for all of them. Generally, we implement as many matching methods to Python bytecode instructions as possible. Across both the logic downstream of step and the logic from invoking VariableBuilder - we now have a lot of VariableTrackers and of course, we’ve spoken about creating guards quiet a bit. Let’s dig into what Variables are, and get a little closer to understanding guards. Variables A ConstantVariable is an instance ofVariableTracker. VariableTracker represents a tracked Python local or stack value. When it comes to representing an object inside TorchDynamo, a VariableTracker does exactly what it says - it tracks a given variable. It is an extremely flexible class, but there are a few points to keep in mind: • It manages the guard relationship around the underlying object through: • make_guard • replace_guards • add_guard(s) • propagate - propagate(*vars: List[List["VariableTracker"]]) - Perhaps the most important of all, in that it combines guards from all the provided VariableTracker instances passed in. It visits the guards and combines the guards from these onto itself. • It acts as a proxy on behalf of the underlying object, implementing methods for the rest of TorchDynamo to get information about the tracked object: • call_method • call_function • python_type • as_proxy • is/as_python_proxy • It stores the variable source of type Source, from torchdynamo/source.py. This source type is a relatively self contained class that helps us organize and bookkeep where the original source came from, and helps provide convenience methods for things like getting the name, and importantly for us, producing guards. And this class (VariableTracker) is built around subclassing, somewhere between a full Abstract Base Class and fully fleshed out class - it leaves many methods raising NotImplementedError - with reliance on subclasses. See torchdynamo/variables/ for all subclasses to fulfill contracts and custom behaviors. Knowing what we know now, we can see an example of how an instruction from dis, BUILD_TUPLE: BUILD_TUPLE(count) Creates a tuple consuming count items from the stack, and pushes the resulting tuple onto the stack. In our case, our signature will be a little different due to the way we create Instruction objects, but the gist of it will be the same. Instead of passing in count, we pass in an object with a little extra bookkeeping, and of course, we deal with turning regular old python objects into TorchDynamo notions: def BUILD_TUPLE(self, inst): items = self.popn(inst.argval) options = VariableTracker.propagate(items) self.push(TupleVariable(items, **options)) Here is what this code does: 1. The function reads argval, which in this case, is analogous to counts in the pydoc for the equivalent instruction. 2. The function popn the items, in this case, the signature is def  popn(self, n: int) -> List[TensorVariable]: this hints at an underlying contract - we are returning TensorVariables. If we take a closer look at sybmolic_convert.py and InstructionTranslatorBase/InstructionTranslatorwe see that the only thing pushed onto and popped from our stack are VariableTrackers. 1. The function calls VariableTracker.propagate. This takes the guards from every single item popped off the stack in 2, and recursively traverses it and combines all the guards into options: py  return {      "guards": guards,  } 2. The function then makes a new instance of a VariableTracker, TupleVariableout of the items and options. This then allows us to install all the appropriate guards from the items that make up the new TupleVariable Note Where did the first guards come from? Propagation is a good technique, but we need something created before it can be propagated. VariableBuilder calls make_guards as it creates VariableTracker instances, from f_locals. This in turn calls into the source, to have it create guards. After all this, bytecode translation is done and we are one step closer to producing GuardedCode. We now understand how locals become VariableTrackers, how instructions are handled, and where guards are called on for creation. Before we can go into seeing how code and guards are combined into a GuardedCode object, we need to dig a little bit into those make_guard and source.make_guard calls above. We can then understand, what was going on when we made guards alongside, and on, VariableTracker instances. Making Guards Guards are just Python objects, of the class Guard. Let’s look at them in more detail. Looking at the definition of the dataclass (and therefore, ctor signature), we see that it has a name, a source, and a create function. @dataclasses.dataclass class Guard: name: str source: GuardSource create_fn: Callable The name should be the name of the variable. The source here is an enum indicating what kind of source the guard belongs to. Note Not to be confused with Source and the other types in source.py, as stored on VariableTracker. create_fn provides the main functionality to transition from a simple dataclass to actually producing valid Python code to be invoked for knowing whether or not things have changed in between invocations, and whether we can safely read from the code cache or not. The most common code paths for getting an instance of a guard are through make_guards on VariableTracker. make_guards->``source.make_guard``->``return Guard(self.name(), self.guard_source(), fn)`` Or, in a concrete example: ... elif istype(value, range): guards = self.make_guards(GuardBuilder.EQUALS_MATCH) return RangeVariable(value=value, guards=guards) Since source was set at the construction time of this VariableTracker, all that was needed here was to provide the fn, GuardBuilder.EQUALS_MATCH to the create_fn field. This create_fn must be a method on GuardBuilder. The reason for this becomes apparent in our next step. Once we have all the guards created for a frame, we move on to CheckFunctionManager and compile_check_fn. Before the convert_frame function can produce a GuardedCode, it needs to run the CheckFunctionManager, with all the guards, to produce a check_fn which will then, in turn get passed in alongside the code into GuardedCode. This is the same check_fn that we store in our cache entry, and the same one we run to know whether or not to retrieve the code stored alongside. For reference, here is that code: static CacheEntry *create_cache_entry(CacheEntry *next, PyObject *guarded_code) { CacheEntry *e = (CacheEntry *)malloc(sizeof(CacheEntry)); DEBUG_NULL_CHECK(e); e->check_fn = PyObject_GetAttrString(guarded_code, "check_fn"); NULL_CHECK(e->check_fn); e->code = (PyCodeObject *)PyObject_GetAttrString(guarded_code, "code"); NULL_CHECK(e->code); e->next = next; return e; } We now know how a check_fn function is used, and who makes it, and what it is composed of, but what we do not yet know is how. How does a list of Guard objects become a function we can run later on? First, we iterate these guards: for guard in sorted(guards or [], key=Guard.sort_key): if not config.guard_nn_modules and guard.is_nn_module(): continue guard.create(local_builder, global_builder) Calling guard.create runs that create_fn we set on the Guard class above (don’t confuse it with the check_fn we are working on producing, the names are similar, so it can get a little confusing). In our example above, our create_fn is GuardBuilder.EQUALS_MATCH. So we are now invoking it, passing in the self, the guard itself, in. The signature is: def EQUALS_MATCH(self, guard: Guard): And internally to that function, we can use the name on the guard to get back our original object, querying it for data and type information, which in turn gets us to the most important bit: appending code. At its simplest, EQUALS_MATCH appends just one line of code: self.code.append(f"{ref} == {val!r}"). Where ref is the name of the variable, and val is the value. It might produce code like this: y == 2 This is a basic example. But if we append a few other kinds of GuardBuilder functions and then combine them all with and in between each statement (as we do), we might get something like this: ___guarded_code.valid and ___check_type_id(y, 94367738391392) and y == 2 and ___check_tensors(x) Here is what this code performs: 1. A check for .valid 2. A type ID check 3. A value check 4. A tensor check This becomes the heart of the code our check_fn, which in turn is evaluated the next time we encounter this code. It will then check: 1. Is this code still valid? 2. If (1), Does y still have a type of 94367738391392? 3. If (2), is y still 2? 4. If (3), let’s check on if tensor x changed in some specific ways. If all of these are still true, then we can use the code cached alongside this check_fn. Note For a deeper dive for how and where this happens you can read static PyCodeObject *lookup(CacheEntry *e, PyObject *f_locals) { of _eval_frame.c. If not, then, we can move on to recompiling the code anew, and storing that in the cache alongside this code, and a whole new check_fn, again to be checked on yet another subsequent frame. There are lots of other such functions on GuardBuilder which get coalesced into, at times massive, strings which then get evaluated as Python code and stored into check_fn. The example above illustrates of a simple case. To understand this functionality better, read the other functions on GuardBuilder, or better yet, dump the code variable in compile_check_fn to see what is getting produced, especially on larger, real models. Summary In this section, we have reviewed: • The role of .valid and invalidation around weak references (and potentially soon to be NN Moduleinvalidations). • How the C++ side of guard functions (___check_type_id, ___check_tensors, etc) operate • What happens when guards fail. • What happens if we produce invalid guard code. We covered how user provided code wrapped in a TorchDynamo context goes on to get traced and tracked internally, organized into VariableTrackers Sources and subsequently Guards, and how those Guards in turn guide cache entry selection and invalidation when handing Python code. Docs Access comprehensive developer documentation for PyTorch View Docs Tutorials Get in-depth tutorials for beginners and advanced developers View Tutorials Resources Find development resources and get your questions answered View Resources
__label__pos
0.987799
6 out of 14 rated this helpful - Rate this topic Walkthrough: Creating a Local Database File in Visual Studio You can explore basic tasks, such as adding tables and defining columns, by using Visual Studio to create and update a local database file in SQL Server Express LocalDB, which Local Data Overview describes. After you finish this walkthrough, you can discover more advanced capabilities by using your local database as a starting point for other walkthroughs that require it. For information about how to create a database by using SQL Server Management Studio or Transact-SQL, see Create a Database. During this walkthrough, you'll explore the following tasks: To complete this walkthrough, install Visual Studio Express 2013 for Windows, Visual Studio Professional 2013, Visual Studio Premium 2013, or Visual Studio Ultimate 2013. These versions of Visual Studio include SQL Server Data Tools. To create a project and a database file 1. Create a Windows Forms project that's named SampleDatabaseWalkthrough. See Creating Solutions and Projects. 2. On the menu bar, choose Project, Add New Item. The Add New Item dialog box appears so that you can add items that are appropriate in a Windows Form project. 3. In the list of item templates, scroll down until Service-based Database appears, and then choose it. Item Templates dialog box 4. Name the database SampleDatabase, and then choose the Add button. 5. If the Data Sources window isn't open, open it by choosing the Shift-Alt-D keys or, on the menu bar, choosing View, Other Windows, Data Sources. 6. In the Data Sources window, choose the Add New Data Source link. 7. In the Data Source Configuration Wizard, choose the Next button four times to accept the default settings, and then choose the Finish button. By opening the properties window for the database, you can view its connection string and the location of the primary .mdf file. • In Visual Studio Express, choose View, Other Windows, Database Explorer if that window isn't already open. Open the properties window by expanding the Data Connections node, opening the shortcut menu for SampleDatabase.mdf, and then choosing Properties. • In other versions of Visual Studio, choose View, Server Explorer if that window isn't already open. Open the properties window by expanding the Data Connections node, opening the shortcut menu for SampleDatabase.mdf, and then choosing Properties. In this section, you'll create a couple of tables, a primary key in each table, and a few rows of sample data. In the next walkthrough, you'll get an idea of how that information might appear in an application. You'll also create a foreign key to specify how records in one table might correspond to records in the other table. To create the Customers table 1. In Server Explorer or Database Explorer, expand the Data Connections node, and then expand the SampleDatabase.mdf node. If the explorer for your version of Visual Studio isn't open, choose View, Server Explorer or View, Other Windows, Database Explorer on the menu bar. 2. Open the shortcut menu for Tables, and then choose Add New Table. The Table Designer opens and shows a grid with one default row, which represents a single column in the table that you're creating. By adding rows to the grid, you'll add columns in the table. 3. In the grid, add a row for each of the following entries: Column name Data type Allow nulls CustomerID nchar(5) False (cleared) CompanyName nvarchar(40) False (cleared) ContactName nvarchar (30) True (selected) Phone nvarchar (24) True (selected) 4. Open the shortcut menu for the CustomerID row, and then choose Set Primary Key. 5. Open the shortcut menu for the default row, and then choose Delete. 6. Name the Customers table by updating the first line in the script pane to match the following sample: CREATE TABLE [dbo].[Customers] 7. In the upper-left corner of the Table Designer, choose the Update button, as the following illustration shows. Update button for Table Designer 8. In the Preview Database Updates dialog box, choose the Update Database button. Your changes are saved to the local database file. To create the Orders table 1. Add another table, and then add a row for each entry in the following table: Column name Data type Allow nulls OrderID int False (cleared) CustomerID nchar(5) False (cleared) OrderDate datetime True (selected) OrderQuantity int True (selected) 2. Set the OrderID as the primary key, and then delete the default row. 3. Name the Orders table by updating the first line in the script pane to match the following sample: CREATE TABLE [dbo].[Orders] 4. In the upper-left corner of the Table Designer, choose the Update button. 5. In the Preview Database Updates dialog box, choose the Update Database button. Your changes are saved to the local database file. To create a foreign key 1. In the context pane on the right side of the grid, open the shortcut menu for Foreign Keys, and then choose Add New Foreign Key, as the following illustration shows. Adding a foreign key in Table Designer 2. In the text box that appears, replace ToTable with Customers. 3. In the script pane, update the last line to match the following sample: CONSTRAINT [FK_Orders_Customers] FOREIGN KEY ([CustomerID]) REFERENCES [Customers]([CustomerID]) 4. In the upper-left corner of the Table Designer, choose the Update button. 5. In the Preview Database Updates dialog box, choose the Update Database button. Your changes are saved to the local database file. To populate the tables with data 1. In Server Explorer or Database Explorer, expand the node for the sample database. 2. Open the shortcut menu for the Tables node, choose Refresh, and then expand the Tables node. 3. Open the shortcut menu for the Customers table, and then choose Show Table Data. 4. Add whatever data you want for at least three customers. You can specify any five characters you want as the customer IDs, but choose at least one that you can remember for use later in this procedure. 5. Open the shortcut menu for the Orders table, and then choose Show Table Data. 6. Add data for at least three orders. Important note Important Make sure that all order IDs and order quantities are integers and that each customer ID matches a value that you specified in the CustomerID column of the Customers table. 7. On the menu bar, choose File, Save All. 8. On the menu bar, choose File, Close Solution. Note Note As a best practice, you can back up the database file that you just created by copying it and then either pasting the copy in another location or giving the copy a different name. Now that you have a local database file with some sample data, you can complete Walkthrough: Connecting to Data in a Local Database File (Windows Forms), in addition to other walkthroughs that demonstrate database tasks. Did you find this helpful? (1500 characters remaining) Thank you for your feedback Show: © 2014 Microsoft. All rights reserved.
__label__pos
0.912362
How do you program a PF key? How do you program a PF key? How do you program a PF key? Directions 1. To open Function Keys click File from the Menu Bar. 2. Click Settings. 3. Click Client Options. 4. Click System. 5. Or, use the keyboard shortcut: [ALT] [f] [e] [o] [s] 6. From the System Parameters window, click the tab. 7. For directions on programming function keys, click more. 8. To view Function Key Commands, click more. What is PF key on keyboard? A PF key represents a command or a series of commands. Pressing one PF key is equivalent to typing the command on the COMMAND line and pressing the Enter key. Keyboards can have 12 or 24 PF keys. Generally the PF keys are preset to default values. How can I change my PF key in ISPF? To change PF key assignments 1. Enter the label that you prefer. 2. Enter NOSHOW to suppress showing this PF key on panels. The ISPF PFSHOW command tells ISPF to display the PF keys on panels. 3. Enter BLANK to display the key name (such as PF1) on panels but not the key’s label. How do I turn on function keys in mainframe? If you use a )PANEL section, you can use the KEYLIST command or the Keylist settings choice from the Function keys pull-down on the ISPF Settings panel to determine which keys appear in each form….Using function keys. Function key Function F8 DOWN F9 SWAP F10 LEFT F11 RIGHT What is the function of PF keys on ISPF screen? displays. Program function (PF) keys are keys on your keyboard that are programmed to issue a particular command. PF keys save time and reduce typing errors. Default PF keys are supplied with ISPF/PDF. What is the attention key in mainframe? Attention interrupt key. This key allows you to interrupt or end a process that is taking place. If you are in a process you want to stop or see a message requesting information you do not have, you can press the attention interrupt key to end the process. The attention interrupt key often is labeled “PA1”. What is the function of F3 key? The F3 key is a function key found at the top of almost all computer keyboards. The key is most often used to open the find or search feature of a program or operating system.
__label__pos
1
Edit Share via EntityKey Class Definition Provides a durable reference to an object that is an instance of an entity type. public ref class EntityKey sealed : IEquatable<System::Data::EntityKey ^> [System.Runtime.Serialization.DataContract(IsReference=true)] [System.Serializable] public sealed class EntityKey : IEquatable<System.Data.EntityKey> [<System.Runtime.Serialization.DataContract(IsReference=true)>] [<System.Serializable>] type EntityKey = class interface IEquatable<EntityKey> Public NotInheritable Class EntityKey Implements IEquatable(Of EntityKey) Inheritance EntityKey Attributes Implements Examples These examples show you how to create and use an EntityKey. using (AdventureWorksEntities context = new AdventureWorksEntities()) { Object entity = null; IEnumerable<KeyValuePair<string, object>> entityKeyValues = new KeyValuePair<string, object>[] { new KeyValuePair<string, object>("SalesOrderID", 43680) }; // Create the key for a specific SalesOrderHeader object. EntityKey key = new EntityKey("AdventureWorksEntities.SalesOrderHeaders", entityKeyValues); // Get the object from the context or the persisted store by its key. if (context.TryGetObjectByKey(key, out entity)) { Console.WriteLine("The requested " + entity.GetType().FullName + " object was found"); } else { Console.WriteLine("An object with this key " + "could not be found."); } } using (AdventureWorksEntities context = new AdventureWorksEntities()) { try { // Create the key that represents the order. EntityKey orderKey = new EntityKey("AdventureWorksEntities.SalesOrderHeaders", "SalesOrderID", orderId); // Create the stand-in SalesOrderHeader object // based on the specified SalesOrderID. SalesOrderHeader order = new SalesOrderHeader(); order.EntityKey = orderKey; // Assign the ID to the SalesOrderID property to matche the key. order.SalesOrderID = (int)orderKey.EntityKeyValues[0].Value; // Attach the stand-in SalesOrderHeader object. context.SalesOrderHeaders.Attach(order); // Create a new SalesOrderDetail object. // You can use the static CreateObjectName method (the Entity Framework // adds this method to the generated entity types) instead of the new operator: // SalesOrderDetail.CreateSalesOrderDetail(1, 0, 2, 750, 1, (decimal)2171.2942, 0, 0, // Guid.NewGuid(), DateTime.Today)); SalesOrderDetail detail = new SalesOrderDetail { SalesOrderID = orderId, SalesOrderDetailID = 0, OrderQty = 2, ProductID = 750, SpecialOfferID = 1, UnitPrice = (decimal)2171.2942, UnitPriceDiscount = 0, LineTotal = 0, rowguid = Guid.NewGuid(), ModifiedDate = DateTime.Now }; order.SalesOrderDetails.Add(detail); context.SaveChanges(); } catch (InvalidOperationException) { Console.WriteLine("Ensure that the key value matches the value of the object's ID property."); } catch (UpdateException) { Console.WriteLine("An error has occurred. Ensure that an object with the '{0}' key value exists.", orderId); } } Remarks The EntityKey objects are immutable; that is, after they are constructed they cannot be modified. For more information, see Working with Entity Keys. Constructors EntityKey() Initializes a new instance of the EntityKey class. EntityKey(String, IEnumerable<EntityKeyMember>) Initializes a new instance of the EntityKey class with an entity set name and an IEnumerable<T> collection of EntityKeyMember objects. EntityKey(String, IEnumerable<KeyValuePair<String,Object>>) Initializes a new instance of the EntityKey class with an entity set name and a generic KeyValuePair collection. EntityKey(String, String, Object) Initializes a new instance of the EntityKey class with an entity set name and specific entity key pair. Fields EntityNotValidKey A simple EntityKey identifying an entity that resulted from a failed TREAT operation. NoEntitySetKey A singleton EntityKey by which a read-only entity is identified. Properties EntityContainerName Gets or sets the name of the entity container. EntityKeyValues Gets or sets the key values associated with this EntityKey. EntitySetName Gets or sets the name of the entity set. IsTemporary Gets a value that indicates whether the EntityKey is temporary. Methods Equals(EntityKey) Returns a value that indicates whether this instance is equal to a specified EntityKey. Equals(Object) Returns a value that indicates whether this instance is equal to a specified object. GetEntitySet(MetadataWorkspace) Gets the entity set for this entity key from the given metadata workspace. GetHashCode() Serves as a hash function for the current EntityKey object. GetHashCode() is suitable for hashing algorithms and data structures such as a hash table. GetType() Gets the Type of the current instance. (Inherited from Object) MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object) OnDeserialized(StreamingContext) Helper method that is used to deserialize an EntityKey. OnDeserializing(StreamingContext) Helper method that is used to deserialize an EntityKey. ToString() Returns a string that represents the current object. (Inherited from Object) Operators Equality(EntityKey, EntityKey) Compares two EntityKey objects. Inequality(EntityKey, EntityKey) Compares two EntityKey objects. Applies to
__label__pos
0.988763
Skip to content Embed URL HTTPS clone URL Subversion checkout URL You can clone with or . Download ZIP Kleisli endo-morphisms are an instance of Monoid. {-# LANGUAGE FlexibleInstances, OverlappingInstances #-} module Main where import Data.Monoid import Control.Monad instance Monad m => Monoid (a -> m a) where mempty = return mappend = (>=>) main :: IO () main = do let m = \x -> [x * 2, x * 3] let m' = \x -> [x + 1, x, x - 1] let mm' = m `mappend` mempty `mappend` m' print $ mm' 2 Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment Something went wrong with that request. Please try again.
__label__pos
0.980225
Homelab, Linux, JS & ABAP (~˘▾˘)~   [PDF.js] Get PDF Viewer when it’s available in DOM and fully initialized https://github.com/mozilla/pdf.js/wiki/Third-party-viewer-usage <iframe id="pdf-js-viewer" src="/pdf/web/viewer.html?file=" title="webviewer" frameborder="0" width="100%" height="700" allowfullscreen="" webkitallowfullscreen=""/> displayPdf: async function (id) { const pdfArrayBuffer= await getPdf(id) const pdfViewerIFrame = await getPdfViewer() await pdfViewerIFrame.contentWindow.PDFViewerApplication.initializedPromise await pdfViewerIFrame.contentWindow.PDFViewerApplication.open(pdfArrayBuffer) }, getPdfViewer: function (id = 'pdf-js-viewer') { return new Promise((resolve, reject) => { let pdfViewerIFrame = document.getElementById(id) //if already loaded in DOM, return it if (pdfViewerIFrame?.contentWindow?.PDFViewerApplication) { resolve(pdfViewerIFrame) } else { //if not loaded yet, set up eventListener document.addEventListener("webviewerloaded", async () => { pdfViewerIFrame = document.getElementById(id) resolve(pdfViewerIFrame) }) } }) } This logic helped me to get the PDFViewerApplication in every situation correctly, for example when reloading the page with F5 or when having the PDF viewer already loaded and just wanting to open another PDF file.
__label__pos
0.505631
trireme-lib: go.aporeto.io/trireme-lib/controller/internal/supervisor Index | Files | Directories package supervisor import "go.aporeto.io/trireme-lib/controller/internal/supervisor" Index Package Files interfaces.go supervisor.go supervisormock.go type Config Uses type Config struct { sync.Mutex // contains filtered or unexported fields } Config is the structure holding all information about the supervisor func NewSupervisor Uses func NewSupervisor(collector collector.EventCollector, enforcerInstance enforcer.Enforcer, mode constants.ModeType, networks []string, p packetprocessor.PacketProcessor) (*Config, error) NewSupervisor will create a new connection supervisor that uses IPTables to redirect specific packets to userspace. It instantiates multiple data stores to maintain efficient mappings between contextID, policy and IP addresses. This simplifies the lookup operations at the expense of memory. func (*Config) ACLProvider Uses func (s *Config) ACLProvider() provider.IptablesProvider ACLProvider returns the ACL provider used by the supervisor that can be shared with other entities. func (*Config) CleanUp Uses func (s *Config) CleanUp() error CleanUp implements the cleanup interface func (*Config) Run Uses func (s *Config) Run(ctx context.Context) error Run starts the supervisor func (*Config) SetTargetNetworks Uses func (s *Config) SetTargetNetworks(networks []string) error SetTargetNetworks sets the target networks of the supervisor func (*Config) Supervise Uses func (s *Config) Supervise(contextID string, pu *policy.PUInfo) error Supervise creates a mapping between an IP address and the corresponding labels. it invokes the various handlers that process the parameter policy. func (*Config) Unsupervise Uses func (s *Config) Unsupervise(contextID string) error Unsupervise removes the mapping from cache and cleans up the iptable rules. ALL remove operations will print errors by they don't return error. We want to force as much cleanup as possible to avoid stale state type Implementor Uses type Implementor interface { // ConfigureRules configures the rules in the ACLs and datapath ConfigureRules(version int, contextID string, containerInfo *policy.PUInfo) error // UpdateRules updates the rules with a new version UpdateRules(version int, contextID string, containerInfo *policy.PUInfo, oldContainerInfo *policy.PUInfo) error // DeleteRules DeleteRules(version int, context string, tcpPorts, udpPorts string, mark string, uid string, proxyPort string, puType string, exclusions []string) error // SetTargetNetworks sets the target networks of the supervisor SetTargetNetworks([]string, []string) error // Start initializes any defaults Run(ctx context.Context) error // CleanUp requests the implementor to clean up all ACLs CleanUp() error // ACLProvider returns the ACL provider used by the implementor ACLProvider() provider.IptablesProvider } Implementor is the interface of the implementation based on iptables, ipsets, remote etc type Supervisor Uses type Supervisor interface { // Supervise adds a new supervised processing unit. Supervise(contextID string, puInfo *policy.PUInfo) error // Unsupervise unsupervises the given PU Unsupervise(contextID string) error // Start starts the Supervisor. Run(ctx context.Context) error // SetTargetNetworks sets the target networks of the supervisor SetTargetNetworks([]string) error // CleanUp requests the supervisor to clean up all ACLs CleanUp() error } A Supervisor is implementing the node control plane that captures the packets. type TestSupervisor Uses type TestSupervisor interface { Supervisor MockSupervise(t *testing.T, impl func(contextID string, puInfo *policy.PUInfo) error) MockUnsupervise(t *testing.T, impl func(contextID string) error) MockStart(t *testing.T, impl func() error) MockStop(t *testing.T, impl func() error) MockAddExcludedIPs(t *testing.T, impl func(ips []string) error) MockSetTargetNetworks(t *testing.T, impl func(networks []string) error) } TestSupervisor is a test implementation for IptablesProvider type TestSupervisorInst Uses type TestSupervisorInst struct { // contains filtered or unexported fields } A TestSupervisorInst is an empty TransactionalManipulator that can be easily mocked. func NewTestSupervisor Uses func NewTestSupervisor() *TestSupervisorInst NewTestSupervisor returns a new TestManipulator. func (*TestSupervisorInst) AddExcludedIPs Uses func (m *TestSupervisorInst) AddExcludedIPs(ips []string) error AddExcludedIPs is a test implementation of the AddExcludedIPs interface func (*TestSupervisorInst) MockAddExcludedIPs Uses func (m *TestSupervisorInst) MockAddExcludedIPs(t *testing.T, impl func(ip []string) error) MockAddExcludedIPs mocks AddExcludedIPs func (*TestSupervisorInst) MockSetTargetNetworks Uses func (m *TestSupervisorInst) MockSetTargetNetworks(t *testing.T, impl func(networks []string) error) MockSetTargetNetworks mocks the SetTargetNetworks method func (*TestSupervisorInst) MockStart Uses func (m *TestSupervisorInst) MockStart(t *testing.T, impl func() error) MockStart mocks the Start method func (*TestSupervisorInst) MockStop Uses func (m *TestSupervisorInst) MockStop(t *testing.T, impl func() error) MockStop mocks the Stop method func (*TestSupervisorInst) MockSupervise Uses func (m *TestSupervisorInst) MockSupervise(t *testing.T, impl func(contextID string, puInfo *policy.PUInfo) error) MockSupervise mocks the Supervise method func (*TestSupervisorInst) MockUnsupervise Uses func (m *TestSupervisorInst) MockUnsupervise(t *testing.T, impl func(contextID string) error) MockUnsupervise mocks the unsupervise method func (*TestSupervisorInst) SetTargetNetworks Uses func (m *TestSupervisorInst) SetTargetNetworks(networks []string) error SetTargetNetworks is a test implementation of the SetTargetNetworks interface method func (*TestSupervisorInst) Start Uses func (m *TestSupervisorInst) Start() error Start is a test implementation of the Start interface method func (*TestSupervisorInst) Stop Uses func (m *TestSupervisorInst) Stop() error Stop is a test implementation of the Stop interface method func (*TestSupervisorInst) Supervise Uses func (m *TestSupervisorInst) Supervise(contextID string, puInfo *policy.PUInfo) error Supervise is a test implementation of the Supervise interface func (*TestSupervisorInst) Unsupervise Uses func (m *TestSupervisorInst) Unsupervise(contextID string) error Unsupervise is a test implementation of the Unsupervise interface Directories PathSynopsis mocksupervisorPackage mocksupervisor is a generated GoMock package. Package supervisor imports 17 packages (graph) and is imported by 5 packages. Updated 2019-01-23. Refresh now. Tools for package owners.
__label__pos
0.865861
Count Rapport de recherche Datadog : Bilan sur l'adoption de l'informatique sans serveur Rapport : Bilan sur l'adoption de l'informatique sans serveur Count Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter. Count non zero FunctionDescriptionExample count_nonzero()Compute count of all non-zero values.count_nonzero(<METRIC_NAME>{*}) For a query grouped by one or more tag keys, count the number of tag values with non-zero metric values at each point. Example: count_nonzero(system.cpu.user{*} by {host}) returns a timeseries representing the number of hosts with non-zero system load at each point. Count not null FunctionDescriptionExample count_not_null()Compute count of all not null values.count_not_null(<METRIC_NAME>{*}) For a query grouped by one or more tag keys, count the number of tag values with non-null metric values at each point. A null metric value is when there is no finite value. Example: count_not_null(system.cpu.user{*} by {host}) returns a timeseries representing the number of hosts with non-null system load at each point. Other functions
__label__pos
0.945393
How to only use created at in Laravel 0 votes This can custom timestamps name const CREATED_AT = 'created'; const UPDATED_AT = 'updated'; This can disable timestamps public $timestamps = false; I want only use created_at , how to do it? Aug 11, 2020 in Laravel by kartik • 37,510 points 2,413 views 1 answer to this question. 0 votes Hello @kartik, Eloquent does not provide such functionality out of the box, but you can create it on your own using the creating event callback: class User extends Eloquent { public $timestamps = false; public static function boot() { parent::boot(); static::creating(function ($model) { $model->created_at = $model->freshTimestamp(); }); } } Hope it helps!! Thank you!! answered Aug 11, 2020 by Niroj • 82,860 points Related Questions In Laravel 0 votes 1 answer How to make a constant and use globally in laravel? Hii, You can create a constants.php page in config folder ...READ MORE answered Mar 24, 2020 in Laravel by Niroj • 82,860 points 3,290 views 0 votes 1 answer How to use multiple databases in Laravel? Hello @kartik, Laravel has inbuilt support for multiple ...READ MORE answered Jul 30, 2020 in Laravel by Niroj • 82,860 points 1,932 views 0 votes 1 answer How to use API Routes in Laravel? Hello @kartik, You call it by http://localhost:8080/api/test ...READ MORE answered Aug 10, 2020 in Laravel by Niroj • 82,860 points 6,948 views 0 votes 1 answer How to use GROUP_CONCAT in laravel? Hello @kartik, You can use relations as query ...READ MORE answered Sep 25, 2020 in Laravel by Niroj • 82,860 points 5,984 views +1 vote 1 answer How to make anchor tag with routing using Laravel? Hey @kartik, First you have to go to ...READ MORE answered Mar 18, 2020 in Laravel by Niroj • 82,860 points 20,520 views 0 votes 1 answer What is redirection in Laravel? Named route is used to give specific ...READ MORE answered Mar 18, 2020 in Laravel by Niroj • 82,860 points 2,437 views 0 votes 1 answer How to install Laravel via composer? Hello, This is simple you just need to ...READ MORE answered Mar 23, 2020 in Laravel by Niroj • 82,860 points 2,227 views +1 vote 1 answer What are named routes in Laravel and How can specify route names for controller actions? Hey @kartik, Named routing is another amazing feature of ...READ MORE answered Mar 23, 2020 in Laravel by Niroj • 82,860 points 35,641 views 0 votes 1 answer How to use Stored Procedures in Laravel? Hey, To create a Stored Procedure you can ...READ MORE answered Mar 24, 2020 in Laravel by Niroj • 82,860 points 4,267 views 0 votes 1 answer How to use mail() in laravel? Hello, Laravel provides a powerful and clean API ...READ MORE answered Mar 24, 2020 in Laravel by Niroj • 82,860 points 481 views webinar REGISTER FOR FREE WEBINAR X REGISTER NOW webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP
__label__pos
0.894754
  slot-gacor Strategies for Ensuring a Safe and Authentic Experience on Omegle Haziran 16, 2024by admin0 Strategies for Ensuring a Safe and Authentic Experience on Omegle Title: Strategies for Ensuring a Safe and Authentic Experience on Omegle Introduction: Omegle is a popular online platform that allows users to chat with strangers anonymously. While it can offer opportunities for genuine connections and interesting conversations, it is important to prioritize safety and authenticity. In this article, we will discuss some effective strategies to ensure a secure and genuine experience on Omegle. 1. Maintain Personal Privacy: – Avoid sharing personal information such as your full name, address, phone number, or social media handles. – Use a username that does not reveal your identity or personal details. – Refrain from sharing photos or videos that may compromise your privacy. 2. Be Cautious about Sharing Personal Media: – Think twice before sharing personal media, like photos or videos, as they can be easily misused or shared without your consent. – If you choose to share any media, make sure it does not reveal sensitive information or anything you’re not comfortable having made public. 3. Trust Your Instincts: – Be cautious of any user who seems suspicious or behaves inappropriately. Trust your gut feeling and discontinue conversation with someone who makes you uncomfortable. – Avoid engaging in conversations that involve illegal activities, hate speech, or harassment. 4. Report Suspicious or Violating Behavior: – Omegle provides reporting options for users who encounter inappropriate or dangerous behavior. Use this feature to report individuals who breach the platform’s terms of service or exhibit harmful behavior. – Reporting can help keep the platform safer and protect other users from potential risks. 5. Use the Interests Option: – Omegle offers an “Interests” feature where users can select specific topics to find conversations that match their interests. – Choosing interests wisely increases the chances of finding like-minded people and engaging in genuine conversations rather than encountering malicious users. 6. Engage Thoughtfully: – Be genuine and respectful while engaging in conversations. – Encourage others to have meaningful discussions by discussing topics of common interest or asking open-ended questions. – Avoid engaging in offensive or inappropriate behavior that could ruin your experience or that of others. 7. Consider Using Moderated Chatrooms: – Omegle provides moderated chatrooms that offer a safer environment for users. – Moderators monitor conversations to keep them free from inappropriate content and ensure user safety. Conclusion: By following these strategies, you can enhance your safety and overall experience on Omegle. It’s crucial to prioritize your privacy, report suspicious behavior, and engage thoughtfully with others. Remember, while Omegle can be an interesting place to meet new people, maintaining personal safety and authenticity should always be a top priority. Understanding the Risks: Tips for Staying Safe on Omegle Understanding the Risks: Tips for Staying Safe on Omegle Omegle, a popular online chat website, provides an opportunity to meet new people from all over the world. While it can be an exciting platform to engage with strangers, it is important to be aware of the potential risks involved. In this article, we will discuss some essential tips to help you stay safe while using Omegle. 1. Protect Your Personal Information One of the fundamental rules of online safety is to never share personal information with strangers. This includes details such as your full name, address, phone number, or any other sensitive information. By keeping this information private, you can prevent any potential misuse or harm. 2. Be Mindful of Your Conversations When chatting with strangers on Omegle, it is essential to be cautious and aware of the content of your conversations. Avoid sharing personal details, discussing sensitive topics, or engaging in inappropriate discussions. Remember, what you say online can have real-life consequences, so always think before you type. 3. Report Inappropriate Behavior Omegle provides features to report and block users engaging in inappropriate behavior. If you come across someone who is harassing, threatening, or making you uncomfortable in any way, make sure to report them immediately. This will not only help protect yourself but also contribute to creating a safer environment for others. 4. Use the Interests Feature Wisely Omegle offers an “Interests” feature that allows you to connect with people who share similar interests. While this can enhance your chatting experience, it is vital to exercise caution. Avoid revealing too much about yourself, and remember that common interests do not guarantee the other person’s intentions or trustworthiness. 5. Security Precautions To ensure a safer experience on Omegle, it is advisable to follow certain security precautions. Use strong, unique passwords for your Omegle account and avoid using the same password for multiple platforms. Additionally, keep your software and antivirus programs up to date to protect against potential cyber threats. Conclusion Staying safe on Omegle requires vigilance and awareness of the potential risks involved. By following these tips, you can minimize the chances of encountering harmful situations. Remember, your safety should always be a priority when engaging in online conversations. Stay informed, be cautious, and enjoy connecting with others in a safe and responsible manner. Reliable Verification Methods: Ensuring Authenticity on Omegle Omegle is a popular online platform that connects users from around the world through anonymous video chats. While the platform offers an exciting opportunity to meet new people and engage in interesting conversations, it also presents the challenge of verifying the authenticity of the individuals you encounter. Ensuring the authenticity of your Omegle connections is crucial to protect yourself from potential scams, harassment, or other malicious activities. By following reliable verification methods, you can enhance your safety and enjoy a more secure experience on the platform. 1. Be Wary of Suspicious Behavior One of the most effective ways to verify the authenticity of an individual on Omegle is to be cautious of any suspicious behavior. Pay attention to red flags such as: 1. Excessive requests for personal information 2. Refusal to engage in video chats 3. Inconsistent or evasive responses to your questions 4. Attempts to redirect the conversation to inappropriate or explicit topics 5. Multiple accounts or frequent account deletions If you encounter any of these warning signs, it’s advisable to terminate the conversation and report the user to Omegle’s support team. Remember, your safety should be your top priority. 2. Ask for Verification In cases where you have doubts about the authenticity of a user, don’t hesitate to ask for verification. Requesting simple verification steps can help you determine if the person you are chatting with is genuine or not. For example: 1. Ask the person to perform a specific action or hold an object in front of the camera to prove their identity. 2. Suggest switching to another platform, such as social media, where they can provide additional proof of their identity. While these methods are not foolproof, they can serve as initial steps to establish trust and authenticity. 3. Utilize Omegle’s Interests Feature Omegle offers an “Interests” feature that allows users to connect with individuals who share similar hobbies, interests, or preferences. By utilizing this feature, you can narrow down your connections to individuals who are more likely to be genuine and share common interests with you. When initiating a conversation, be sure to mention your shared interests right away. This can spark a more engaging and meaningful conversation, making it easier to assess the authenticity of the individual. 4. Report Suspicious Users If you come across any suspicious or malicious users during your Omegle experience, it is essential to report them. Omegle has a reporting feature that allows users to flag inappropriate behavior, scams, or any other concerns to the platform’s support team. By reporting suspicious users, you not only protect yourself but also contribute to creating a safer environment for all Omegle users. In conclusion, verifying the authenticity of individuals on Omegle is crucial for a safe and enjoyable experience. By being cautious of suspicious behavior, asking for verification, utilizing the platform’s interests feature, and promptly reporting any concerns, you can ensure a more secure environment for yourself and others. Effective Filtering Techniques: Protecting Yourself from Inappropriate Content on Omegle Omegle is a popular online platform that connects users with random strangers for chat sessions. However, it is important to take precautionary measures to protect yourself from encountering inappropriate or harmful content. In this article, we will explore effective filtering techniques to ensure a safer and more enjoyable experience on Omegle. Why is Filtering Important? Omegle is an anonymous platform where users can freely chat with strangers. While this aspect adds excitement to the experience, it also opens doors to potential risks. Inappropriate content, including explicit language, nudity, and harassment, can be found on Omegle channels. Therefore, having a robust filtering system in place is crucial to protect yourself from such unwanted encounters. Understanding Omegle Filters Omegle offers different filtering options to help users control the type of content they are exposed to. These filters categorize conversations into various topics, such as “clean” and “adult.” By selecting the appropriate filters, you can ensure that you engage in conversations that align with your comfort level. Enabling Advanced Filtering To enhance your protection, enable the advanced filtering feature on Omegle. This feature uses sophisticated algorithms to identify and block potentially inappropriate content. By enabling advanced filtering, you can significantly reduce the chances of encountering explicit content or engaging with malicious users. Utilizing Third-Party Filtering Software In addition to Omegle’s built-in filters, you can further enhance your safety by utilizing third-party filtering software. These software solutions employ advanced technologies to analyze conversations and flag any potentially harmful or inappropriate content. By integrating such software into your Omegle experience, you can enjoy an added layer of protection. Avoiding Personal Information Sharing Protecting your privacy is paramount when using Omegle. Avoid sharing any personal information, such as your name, age, location, or contact details, during conversations. By maintaining anonymity, you minimize the chances of encountering individuals with malicious intent. Reporting Inappropriate Behavior If you come across any inappropriate behavior or content on Omegle, it is crucial to report it immediately. The platform provides a reporting feature that allows users to flag any violations. By taking an active role in reporting, you contribute to creating a safer environment for yourself and other users. Conclusion In conclusion, while Omegle offers an exciting platform for connecting with strangers, it is essential to prioritize safety and protect yourself from inappropriate content. By utilizing effective filtering techniques, enabling advanced filters, utilizing third-party software, avoiding personal information sharing, and reporting any violations, you can enhance your protection and have a more enjoyable experience on Omegle. Building Resilience in Online Interactions on Omegle: : omelge Building Trust: Establishing Authentic Connections on Omegle Omegle, the popular online chat platform, allows users to connect with strangers from around the world. While it provides a unique opportunity to meet new people, it can also present challenges when it comes to building trust and establishing authentic connections. In this article, we will explore effective strategies to make meaningful connections on Omegle and foster trust. Be Genuine and Authentic When engaging in conversations on Omegle, it is important to be genuine and authentic. Avoid using scripted lines or trying to impress others. Instead, be yourself and show a genuine interest in getting to know the other person. This will help establish a sense of trust and make the connection more meaningful. Listen and Respond Thoughtfully One of the key aspects of building trust is active listening. When chatting on Omegle, make sure to listen attentively to what the other person is saying. Respond thoughtfully and show genuine curiosity about their thoughts and experiences. This will not only make the conversation more engaging but also demonstrate that you value their perspective. Respect Boundaries and Privacy Respecting boundaries and privacy is crucial when establishing authentic connections on Omegle. Understand that not everyone is comfortable sharing personal information or engaging in certain conversations. Always ask for consent before sharing any personal details and be respectful if the other person chooses not to disclose certain information. Stay Positive and Encouraging Positivity can go a long way in building trust and creating a pleasant atmosphere on Omegle. Avoid negative or offensive language and focus on being supportive and encouraging. Compliment the other person on their interests or achievements and try to uplift their mood. A positive and friendly approach will help to establish a genuine connection. Keep an Open Mind Omegle connects people from different backgrounds and cultures. Embrace the diversity and keep an open mind when conversing with strangers. Be curious about their perspectives and experiences, even if they differ from your own. This openness will pave the way for authentic connections built on mutual respect and understanding. • Be genuine and authentic • Listen and respond thoughtfully • Respect boundaries and privacy • Stay positive and encouraging • Keep an open mind Building trust and establishing authentic connections on Omegle requires effort and intention. By following these strategies, you can create meaningful connections and foster a positive environment for yourself and others. Remember, the key is to be genuine, respectful, and open-minded. Happy chatting! Reporting Suspicious Activity: Steps to Take in Ensuring a Secure Experience on Omegle In today’s digital age, the need for online safety cannot be stressed enough. With the rise of online platforms connecting people from all over the world, it is crucial to be aware of potential risks and take necessary measures to protect oneself. Omegle, a popular chat platform, offers a unique way to meet new people, but it is not without its own set of challenges. In this article, we will discuss the steps you can take to ensure a secure experience on Omegle, with a particular focus on reporting suspicious activity. But first, let’s understand the importance of reporting such activities. By reporting suspicious behavior on Omegle, you not only contribute to your own safety but also help create a safer environment for others. It is a collective effort to keep the online community secure. So, what are the steps you can take to report suspicious activity on Omegle? Here’s a handy guide: • Be observant: The first step in reporting suspicious activity is to be vigilant while using Omegle. Pay attention to any unusual behavior or conversations that make you uncomfortable. Trust your gut instincts and take note of any red flags. • Gather evidence: Whenever you encounter suspicious activity, it is essential to gather evidence to support your report. This can include screenshots of the conversation, usernames, or any other relevant information that can aid in the investigation process. • Report to Omegle: Once you have gathered the necessary evidence, it’s time to report the activity to Omegle. Visit their website or use their mobile app to find the reporting feature. Provide all the details and evidence you have collected, ensuring clarity in your report. • Inform authorities if necessary: In some cases, the suspicious activity you encounter on Omegle may constitute a serious offense or potential harm to yourself or others. If this is the case, it is crucial to involve the appropriate authorities. Contact your local law enforcement agency and provide them with the relevant information. Remember, reporting suspicious activity is not just about your personal safety; it is also about protecting fellow users from potential threats. By taking these steps, you actively contribute to making Omegle a safer platform for everyone. In conclusion, ensuring a secure experience on Omegle requires active participation and responsibility. By being observant, gathering evidence, reporting to Omegle, and involving authorities if necessary, you play a crucial role in maintaining a safe online environment. Stay vigilant, stay safe! Frequently Asked Questions Leave a Reply Your email address will not be published. Required fields are marked * Diğer Ulaşım Bilgileri Bize Ulaşın https://itepinnovation.com/wp-content/uploads/2020/04/img-footer-map.png [email protected] [email protected] Sosyal Medya Sosyal Medyada Biz Bize sosyal medya hesaplarımızdan ulaşabilirsiniz! itepinnovation.com Bize Ulaşın Diğer Ulaşım Bilgileri Bize Ulaşın https://itepinnovation.com/wp-content/uploads/2020/04/img-footer-map.png [email protected] [email protected] Sosyal Medya Sosyal Medyada Biz Bize sosyal medya hesaplarımızdan ulaşabilirsiniz! Copyright by ITEP INNOVATION. Tüm Hakları Saklıdır. Copyright by ITEP INNOVATION. Tüm Hakları Saklıdır. TurkishEnglishGerman
__label__pos
0.986557
4 I am working on a project where I implement two popular MST algorithms in C++ and then print how long each one takes to execute. Please ignore the actual algorithms, I have already tested them and am only interested in getting accurate measurements of how long they take. void Graph::krushkalMST(bool e){ size_t s2 = size * size; typedef struct{uint loc; uint val;} wcType; //struct used for storing a copy of the weights values to be sorted, with original locations wcType* weightsCopy = new wcType[s2]; //copy of the weights which will be sorted. for(int i = 0; i < s2; i++){ weightsCopy[i].loc = i; weightsCopy[i].val = weights[i]; } std::vector<uint> T(0); //List of edges in the MST auto start = std::chrono::high_resolution_clock::now(); //time the program was started typedef int (*cmpType)(const void*, const void*); //comparison function type static cmpType cmp = [](const void* ua, const void* ub){ //Compare function used by the sort as a C++ lambda uint a = ((wcType*)ua)->val, b = ((wcType*)ub)->val; return (a == b) ? 0 : (a == NULLEDGE) ? 1 : (b == NULLEDGE) ? -1 : (a < b) ? -1 : 1; }; std::qsort((void*)weightsCopy, s2, sizeof(wcType), cmp); //sort edges into ascending order using a quick sort (supposedly quick sort) uint* componentRefs = new uint[size]; //maps nodes to what component they currently belong to std::vector<std::vector<uint>> components(size); //vector of components, each component is a vector of nodes; for(int i = 0; i < size; i++){ //unOptimize(components); components[i] = std::vector<uint>({(uint)i}); componentRefs[i] = i; } for(int wcIndex = 0; components.size() >= 2 ; wcIndex++){ uint i = getI(weightsCopy[wcIndex].loc), j = getJ(weightsCopy[wcIndex].loc); //get pair of nodes with the smallest edge uint ci = componentRefs[i], cj = componentRefs[j]; //locations of nodes i and j if(ci != cj){ T.push_back(weightsCopy[wcIndex].loc); //push the edge into T for(int k = 0; k < components[cj].size(); k++) //move each member in j's component to i's component components[ci].push_back(components[cj][k]); for(int k = 0; k < components[cj].size(); k++) //copy this change into the reference locations componentRefs[components[cj][k]] = ci; components.erase(components.begin() + cj); //delete j's component for(int k = 0; k < size; k++) if(componentRefs[k] >= cj) componentRefs[k]--; } } auto end = std::chrono::high_resolution_clock::now(); uint time = std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); std::cout<<"\nMST found my krushkal's Algorithm:\n"; printData(time, T, e); delete[] weightsCopy; delete[] componentRefs; } void Graph::primMST(bool e){ std::vector<uint> T(0); //List of edges in the MST auto start = std::chrono::high_resolution_clock::now(); //Start calculating the time the algorithm takes bool* visited = new bool[size]; //Maps each node to a visited value visited[0] = true; for(int i = 1; i < size; i++) visited[i] = false; for(uint numVisited = 1; numVisited < size; numVisited++){ uint index = 0; //index of the smallest cost edge to unvisited node uint minCost = std::numeric_limits<uint>::max(); //cost of the smallest edge filling those conditions for(int i = 0; i < size; i++){ if(visited[i]){ for(int j = 0; j < size; j++){ if(!visited[j]){ uint curIndex = i * size + j, weight = dweights[curIndex]; if(weight != NULLEDGE && weight < minCost){ index = curIndex; minCost = weight; } } } } } T.push_back(index); visited[getI(index)] = true; } auto end = std::chrono::high_resolution_clock::now(); uint time = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count(); std::cout<<"\nMST found my Prim's Algorithm:\n"; printData(time, T, e); delete[] visited; } I initially used clock() from <ctime> to try and get an accurate measurement of how long this would take, my largest test file has a graph of 40 nodes with 780 edges (sufficiently large enough to warrant some compute time), and even then on a slow computer using g++ with -O0 i would get either 0 or 1 milliseconds. On my desktop I was only ever able to get 0 ms, however as I need a more accurate way to distinguish time between test cases I decided I would try for the high_resolution_clock provided by the <chrono> library. This is where the real trouble began, I would (and still) consistently get that the program took 0 nanoseconds to execute. Output of my program for the hardest test case In my search for a solution I came across multiple questions that deal with similar issues, most of which state that <chrono> is system dependent and you're unlikely to actually be able to get nanosecond or even microsecond values. Never the less, I tried using std::chrono::microsecond only to still consistently get 0. Eventually I found what I thought was someone who was having the same problem as me: counting duration with std::chrono gives 0 nanosecond when it should take long However, this is clearly a problem of an overactive optimizer which has deleted an unnecessary piece of code, whereas in my case the end result always depends on the results for series of complex loops which must be executed in full. I am on Windows 10, compiling with GCC using -O0. My best hypothesis is I'm doing something wrong or that windows doesn't support anything smaller then milliseconds while using std::chrono and std::chrono::nanoseconds are actually just milliseconds padded with 0s on the end (as I observe when I put a system("pause") in the algorithm and unpause at arbitrary times). Please let me know if you find anyway around this or if there is any other way I can achieve higher resolution time. At the request of @Ulrich Eckhardt, I am including minimal reproducible example as well as the results of the test I preformed using it, and I must say it is rather insightful. #include<iostream> #include<chrono> #include<cmath> int main() { double c = 1; for(int itter = 1; itter < 10000000; itter *= 10){ auto start = std::chrono::high_resolution_clock::now(); for(int i = 0; i < itter; i++) c += sqrt(c) + log(c); auto end = std::chrono::high_resolution_clock::now(); int time = std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count(); std::cout<<"calculated: "<<c<<". "<<itter<<" iterations took "<<time<<"ns\n"; } system("pause"); } For my loop I choose a random arbitrary mathematical formula and make sure to use the result of what the loop does so it's not optimized out of existence. Testing it with various iterations on my desktop yields: enter image description here This seems to imply that a certain threshold is required before the it starts counting time, since dividing the time taken by the first result that yields non-zero time by 10, we get another non-zero time which is not what the result says despite that being how it should work assuming this whole loop is takes O(n) time with n iterations that is. If anything this small example baffles me even further. 10 • 1 You need to extract and provide a minimal reproducible example. Also, please read How to Ask, because you are actually asking two questions! Nov 19, 2019 at 7:01 • 2 I use MSVC on Windows, and std::chrono::high_resolution_clock is able to measure time as precise as 100 nanoseconds. Also in UWP, TimeSpan struct has the resolution of 100 ns, so high_resolution_clock must work if GCC supports it. – paxbun Nov 19, 2019 at 7:03 • 4 Possibly relevant: C++ chrono::duration_cast always outputs “0 seconds”. Quoting: TL;DR: It looks like the std::chrono implementation (libstdc++) is quite poor on Windows and you won't get anything better than seconds. Another possibly relevant discussion. Nov 19, 2019 at 7:25 • 1 @UlrichEckhardt, Thanks for the feedback everyone, The code I gave was really just in place so you could see if for some odd reason the compiler was optimizing away those loops which don't contain anything super specific to the rest of the project (besides uint which i just assumed you would view as an unsigned integer). I now see this is a bigger issue and have included a minimal reproducible example demonstrating the same problem. Nov 19, 2019 at 7:36 • 2 Does this answer your question? C++ chrono::duration_cast always outputs "0 seconds" Nov 19, 2019 at 8:09 1 Answer 1 4 Switch to steady_clock and you get the correct results for both MSVC and MinGW GCC. You should avoid using the high_resolution_clock as it is just an alias to either steady_clock or system_clock. For measuring elapsed time in a stop watch like fashion, you always want steady_clock. high_resolution_clock is an unfortunate thing and should be avoided. I just checked and MSVC has the following: using high_resolution_clock = steady_clock; while MinGW GCC has: /** * @brief Highest-resolution clock * * This is the clock "with the shortest tick period." Alias to * std::system_clock until higher-than-nanosecond definitions * become feasible. */ using high_resolution_clock = system_clock; 2 • it can also be "a third, independent clock" – bolov Nov 19, 2019 at 10:20 • @bolov I guess it could be. The standard only says this of high_resolution_clock: Objects of class high_resolution_clock represent clocks with the shortest tick period. high_resolution_clock may be a synonym for system_clock or steady_clock. Nov 19, 2019 at 10:28 Your Answer By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.831832
Bundling Multiples Layer-2 MPLS circuits #1 Dears, Can I bundle multiples MPLS layer-2 circuits using PEPLINK to have a heigher capcity of total circuits. For example, bundling 2 MPLS circuits each of them with capacity 2 Mbps using two PEPlink boxes to have 4 Mbps as an output. Please note I dont want to distrbute the traffic and do load balancing for the traffic. See the attached diagram for more explenation. regards #2 This looks similar to SpeedFusion deployments that have wireless bridge links connecting the Balance routers. Private IP addresses can be used for WAN links, and no default gateway is required when WAN1 of Balance A can reach WAN1 of Balance B on the same IP network for example. Fake DNS entries should be used if there is no internet access. SpeedFusion will provide LAN to LAN communication, and one side can force all traffic through the SpeedFusion VPN.
__label__pos
0.616192
How VPNs Work To Protect Privacy Protecting your privacy online should be of the utmost importance and there are several ways in which you can do this. However, we are going to look at one method, a Virtual Private Network or VPN for short. VPN Security Facts Article Image IMAGE: PEXELS What Is A VPN? As you may expect, a VPN refers to a private network that allows you to connect to the Internet. By encrypting your connection at all times, it even protects you from your ISP. The easiest way to explain this approach is that it stops people from the outside seeing what you are doing thanks to the encryption used on these networks. There are additional methods out there that are more effective than a VPN, but this is easy to set up making it ideal for people with even a reduced level of knowledge. So, How Does It Work? A VPN is provided to you by a supplier, so you must make sure that the supplier is a company that is trustworthy. These companies run a number of different encryption methods that mask your activity to anything outside of the VPN. Encryption masks the connections and signals that you send out when you are connecting to the Internet or doing a search. It scrambles it to prevent people from eavesdropping on the messages and then using that data to identify you. View a VPN as being a method whereby a tunnel is created between you and the Internet. That tunnel is protected from every angle, so you feel safe when you are in there as you know that nothing can get in. hen you are in the tunnel it’s as if you are invisible to anything other than the VPN supplier, Eventually, your search or request does emerge from the other end of the tunnel. However, it is missing key information regarding your IP address, so it masks who your ISP is, who you are and where you come from. You may also want to know that there are apps for smartphones that allow you to use a VPN in order to secure all of your mobile data. This works in the same way as a VPN for your laptop, which makes it easy to get started. How To Set It Up To set up a VPN, you have two options. First, you can go to the great lengths of setting one up on your own via a series of online tools, but it’s not easy. here are also extra costs associated with this approach which you may want to avoid. The other option is to use the services of a low-priced VPN service. As mentioned earlier you must check that they can be trusted, and also determine if they keep their own records of what you are doing. You want to use a company that doesn’t keep records as that improves your privacy even further. To set it up, you simply follow the instructions or ask the VPN company for help and they will be happy to oblige. Potential Problems? The idea does sound rather impressive, but there are several potential problems to be aware of. First, do your research on the suppliers as some will spy on you. Facebook and its VPN is a great example of this. You must check this out thoroughly or you may be giving yourself a bigger headache. Another issue is that the speed of your Internet connection will drop when you connect to a VPN. This is due to you sharing the connection with other people rather than your own single connection. This may result in a marked difference in performance, so you must balance this out with your need for privacy. A VPN will be able to protect you from prying eyes but it does not come without its own problems. Weigh up your options and look into each supplier before you commit to any kind of contract. Prices will vary, but the main thing is the way in which they protect you when online. There are numerous companies out there, so do your research before using anyone in particular. If you are interested in even more technology-related articles and information from us here at Bit Rebels then we have a lot to choose from. VPN Security Facts Header Image IMAGE: PEXELS COMMENTS WORDPRESS: 0
__label__pos
0.603468
AZ-104 – Question 34 0 19 You have an Azure subscription named AZPT1 that contains the resources shown in the following table: You create a new Azure subscription named AZPT2. You need to identify which resources can be moved to AZPT2. Which resources should you identify? • A. VM1, storage1, VNET1, and VM1Managed only • B. VM1 and VM1Managed only • C. VM1, storage1, VNET1, VM1Managed, and RVAULT1 • D. RVAULT1 only Correct Answer: C  You can move a VM and its associated resources to a different subscription by using the Azure portal. You can now move an Azure Recovery Service (ASR) Vault to either a new resource group within the current subscription or to a new subscription. Reference:https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/move-resource-group-and-subscription LEAVE A REPLY Please enter your comment! Please enter your name here
__label__pos
0.877496
Grails comes with a predefined set of tags that you can use in your gsp pages. If you want to add your own tags, it is pretty simple and you can simply check the Dynamic Tag Libraries reference documentation. I created my own version of the <g:each> tag which allows you to provide a begin, end and separator attributes: class MyTagLib { static namespace = 'my' // Equivalent to g:each but allow for begin/end and separator attributes def each = { attrs, body -> def var = attrs.var ?: "var" def begin = attrs.begin ?: "" def end = attrs.end ?: "" def writer = out if(attrs.in) { // not null and not empty (definition of truth in groovy) attrs.in.eachWithIndex { elt, i -> if(i == 0) { writer << begin } else { writer << attrs.separator } writer << body((var):elt) } writer << end } else { if(attrs.alwaysBeginEnd?.toString() == "true") { writer << begin << end } } } } Here are some examples of rendering in gsp: <my:each in="${[1,2,3]}" var="i">${i}</my:each> produces: 123 <my:each in="${[1,2,3]}" var="i" begin="{" end="}" separator=",">${i}</my:each> produces: {1,2,3} <my:each in="${[1]}" var="i" begin="{" end="}" separator=",">${i}</my:each> produces: {1} <my:each in="${[]}" var="i" begin="{" end="}" separator=",">${i}</my:each> produces: <my:each in="${[]}" var="i" begin="{" end="}" separator="," alwaysBeginEnd="true">${i}</my:each> produces: {} This tag is pretty convenient as it automatically takes care of an empty list or one that has only one element to properly display the separator and the begin and end attributes. The last example shows how you can 'force' to display the begin and end attributes when the list is empty. Now, let's say I want to create another tag which will reuse the code I already wrote. In other words, I need to call a tag from within a tag. Here is how I would do it: def csv = { attrs, body -> def var = attrs.var ?: "var" out << my.each(in: attrs.in, var: 'v', separator: ',') { map -> def elt = map.v out << "{" out << body((var):elt) out << "}" } } And here is the rendering in gsp: <my:csv in="${[1,2,3]}" var="i">[${i}]</my:csv> produces: {[1]},{[2]},{[3]} It is actually not that trivial to call a tag from within a tag (and to my knowledge it is not documented)... let's cover each details: • referencing another tag is used with the notation: namespace.tagName (ex: my.each) • simply calling the other tag is not enough and the result must be sent to the writer (ex: out << my.each(...)) • each attribute is passed in as a map, so you simply use the groovy map notation (ex: (in: attrs.in, var: 'v', separator: ',')) • now the really tricky part is the closure which corresponds to the children tags in gsp... the argument that you get is a map (because in the my.each code, the body closure is called with a map!). Although it makes sense, it is not that trivial because in gsp you don't see it. This is why I need to use map.v to have access to the element that is being iterated over (the variable v is because it is the one that I used in the call (my.each(..., var: 'v', ...))) Although a little tricky to write, it is very powerful to be able to create tags that build upon other tags. There is one little caveat in how null is being handled and I opened a Jira ticket for it (GRAILS-4449) as it does not seem to be consistent.
__label__pos
0.984759
Basic Forms Customized Bootstrap forms to match Neptune's styles. Basic Input Here’s a quick example to demonstrate simple input field. Add .light-focus to .form-control to get lighter border on focus. We'll never share your email with anyone else. <label for="exampleInputEmail1" class="form-label">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> Rounded Add .form-control-rounded to .form-control to make fields rounded. <input type="email" class="form-control form-control-rounded" aria-describedby="..." placeholder="..."> <input type="password" class="form-control form-control-solid-bordered form-control-rounded" aria-describedby="..." placeholder="..."> Select Custom <select> menus need only a custom class, .form-select to trigger the custom styles. Custom styles are limited to the <select>’s initial appearance and cannot modify the <option>s due to browser limitations. <select class="form-select" aria-label="Default select example"> <option selected>Open this select menu</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> Disabled Add the disabled boolean attribute on an input to prevent user interactions and make it appear lighter. <input class="form-control" id="disabledInput" type="text" placeholder="Disabled input here..." disabled> Sizing Set heights using classes like .form-control-lg and .form-control-sm. <input class="form-control form-control-lg" type="text" placeholder=".form-control-lg" aria-label=".form-control-lg example"> <input class="form-control" type="text" placeholder="Default input" aria-label="default input example"> <input class="form-control form-control-sm" type="text" placeholder=".form-control-sm" aria-label=".form-control-sm example"> Radios <div class="form-check"> <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1"> <label class="form-check-label" for="flexRadioDefault1"> Default radio </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault2" checked> <label class="form-check-label" for="flexRadioDefault2"> Default checked radio </label> </div> Switches A switch has the markup of a custom checkbox but uses the .form-switch class to render a toggle switch. Switches also support the disabled attribute. <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label" for="flexSwitchCheckDefault">Default switch checkbox input</label> </div> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="flexSwitchCheckChecked" checked> <label class="form-check-label" for="flexSwitchCheckChecked">Checked switch checkbox input</label> </div> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="flexSwitchCheckDisabled" disabled> <label class="form-check-label" for="flexSwitchCheckDisabled">Disabled switch checkbox input</label> </div> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="flexSwitchCheckCheckedDisabled" checked disabled> <label class="form-check-label" for="flexSwitchCheckCheckedDisabled">Disabled checked switch checkbox input</label> </div> Custom Styles We offer some different custom styles for input fields to make your forms more beautiful. <input type="text" class="form-control form-control-solid-bordered" aria-describedby="..." placeholder="..."> <input type="text" class="form-control form-control-solid" aria-describedby="..." placeholder="..."> <input type="text" class="form-control form-control-material" aria-describedby="..." placeholder="..."> <input type="text" class="form-control form-control-transparent" aria-describedby="..." placeholder="..."> Floating Labels Wrap a pair of <input class="form-control"> and <label> elements in .form-floating to enable floating labels with Bootstrap’s textual form fields. A placeholder is required on each <input> as our method of CSS-only floating labels uses the :placeholder-shown pseudo-element. Also note that the <input> must come first so we can utilize a sibling selector (e.g., ~). <input type="text" class="form-control form-control-solid-bordered" aria-describedby="..." placeholder="..."> <input type="text" class="form-control form-control-solid" aria-describedby="..." placeholder="..."> <input type="text" class="form-control form-control-material" aria-describedby="..." placeholder="..."> <input type="text" class="form-control form-control-transparent" aria-describedby="..." placeholder="..."> Form Text Block-level or inline-level form text can be created using .form-text. Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji. <label for="inputPassword5" class="form-label">Password</label> <input type="password" id="inputPassword5" class="form-control" aria-describedby="passwordHelpBlock"> <div id="passwordHelpBlock" class="form-text"> Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji. </div> Checks <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault"> <label class="form-check-label" for="flexCheckDefault"> Default checkbox </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="flexCheckChecked" checked=""> <label class="form-check-label" for="flexCheckChecked"> Checked checkbox </label> </div> Inline Stacking Group checkboxes or radios on the same horizontal row by adding .form-check-inline to any .form-check. <div class="form-check form-check-inline"> <input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="option1"> <label class="form-check-label" for="inlineCheckbox1">1</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="checkbox" id="inlineCheckbox2" value="option2"> <label class="form-check-label" for="inlineCheckbox2">2</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="checkbox" id="inlineCheckbox3" value="option3" disabled> <label class="form-check-label" for="inlineCheckbox3">3 (disabled)</label> </div> Range Create custom <input type="range"> controls with .form-range. The track (the background) and thumb (the value) are both styled to appear the same across browsers. As only Edge Legacy and Firefox supports “filling” their track from the left or right of the thumb as a means to visually indicate progress, we do not currently support it. <label for="customRange1" class="form-label">Example range</label> <input type="range" class="form-range" id="customRange1"> By default, range inputs “snap” to integer values. To change this, you can specify a step value. In the example below, we double the number of steps by using step="0.5". <label for="customRange3" class="form-label">Range with steps</label> <input type="range" class="form-range" min="0" max="5" step="0.5" id="customRange3">
__label__pos
0.686594
CFD Online Logo CFD Online URL www.cfd-online.com [Sponsors] Home > Forums > OpenFOAM Installation Statically Compiling OpenFOAM Issues Register Blogs Members List Search Today's Posts Mark Forums Read Reply   LinkBack Thread Tools Display Modes Old   August 30, 2008, 14:10 Default I have a very large pool of co   #1 New Member   David Herzfeld Join Date: Mar 2009 Posts: 11 Rep Power: 10 herzfeldd is on a distinguished road Sponsored Links I have a very large pool of computational resources available using Condor, and would like to perform CFD simulations across this network. Since the software configuration of these computational nodes is largely unknown, I am attempting to statically compile OpenFOAM to allow for simple distribution of the executables I need (just simpleFOAM and icoFOAM). I am, however, running in to a large number of problems when trying to statically compile these needed executables. 1. I have changed the Allmake scripts to call wmake lib rather than wmake libso for all library instances. These libraries result in *.a's, without error. 2. I have added a -static flag to both the c and c++ rules files in wmake/rules/linuxGcc/c and wmake/rules/linuxGcc/c++ I am, however, still receiving an overwhelming number of errors during the compile/linking of any of the executables. See below: g++ -m32 -static -Dlinux -DDP -O3 -DNoRepository -ftemplate-depth-40 -I/home/user/OpenFOAM/OpenFOAM-1.5/src/finiteVolume/lnInclude -I/home/user/OpenFOAM/OpenFOAM-1.5/src/sampling/lnInclude -IlnInclude -I. -I/home/user/OpenFOAM/OpenFOAM-1.5/src/OpenFOAM/lnInclude -I/home/user/OpenFOAM/OpenFOAM-1.5/src/OSspecific/Unix/lnInclude -fPIC -pthread -lOpenFOAM -lPstream Make/linuxGccDPOpt/financialFoam.o -L/home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt \ -lsampling -lmeshTools -lfiniteVolume -lOpenFOAM -ldl -lm -o /home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/financialFoam /home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/libOpenFOAM.a(dlLibraryTable. o): In function `Foam::dlLibraryTable::open(Foam::fileName const&)': dlLibraryTable.C.text+0x404): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking Make/linuxGccDPOpt/financialFoam.o: In function `main': financialFoam.C.text+0x15ef): undefined reference to `Foam::cpuTime::elapsedCpuTime() const' Make/linuxGccDPOpt/financialFoam.o: In function `Foam::GeometricField<double,>::GeometricBoundaryF ield::evaluate()': financialFoam.C.text._ZN4Foam14GeometricFieldIdNS_12fvPatchFieldE NS_7volMeshEE22GeometricBounda ryField8evaluateEv[Foam::GeometricField<double,>::GeometricBoundaryFi eld::evalua te()]+0x469): undefined reference to `Foam::IPstream::waitRequests()' financialFoam.C.text._ZN4Foam14GeometricFieldIdNS_12fvPatchFieldE NS_7volMeshEE22GeometricBounda ryField8evaluateEv[Foam::GeometricField<double,>::GeometricBoundaryFi eld::evalua te()]+0x471): undefined reference to `Foam:Pstream::waitRequests()' /home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/libfiniteVolume.a(fvMeshGeome try.o): In function `Foam::GeometricField<foam::vector<double>, Foam::fvPatchField, Foam::volMesh>::GeometricBoundaryField::evaluate() ': fvMeshGeometry.C.text._ZN4Foam14GeometricFieldINS_6VectorIdEENS_12 fvPatchFieldENS_7volMeshEE22Ge ometricBoundaryField8evaluateEv[Foam::GeometricField<foam::vector<double>, Foam::fvPatchField, Foam::volMesh>::GeometricBoundaryField::evaluate()]+0x469): undefined reference to `Foam::IPstream::waitRequests()' fvMeshGeometry.C.text._ZN4Foam14GeometricFieldINS_6VectorIdEENS_12 fvPatchFieldENS_7volMeshEE22Ge ometricBoundaryField8evaluateEv[Foam::GeometricField<foam::vector<double>, Foam::fvPatchField, Foam::volMesh>::GeometricBoundaryField::evaluate()]+0x471): undefined reference to `Foam:Pstream::waitRequests()' /home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/libfiniteVolume.a(fvMesh.o): In function `Foam::fvMesh::fvMesh(Foam::IOobject const&)': fvMesh.C.text+0x300d): undefined reference to `Foam::file(Foam::fileName const&)' fvMesh.C.text+0x3290): undefined reference to `Foam::file(Foam::fileName const&)' /home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/libfiniteVolume.a(fvMesh.o): In function `Foam::fvMesh::fvMesh(Foam::IOobject const&)': fvMesh.C.text+0x400d): undefined reference to `Foam::file(Foam::fileName const&)' fvMesh.C.text+0x4290): undefined reference to `Foam::file(Foam::fileName const&)' /home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/libfiniteVolume.a(fvScalarMat rix.o): In function `Foam::fvMatrix<double>::setComponentReference(int , int, unsigned char, double)': fvScalarMatrix.C.text+0x18c1): undefined reference to `Foam::IPstream::read(Foam::Pstream::commsTypes, int, char*, int)' fvScalarMatrix.C.text+0x1944): undefined reference to `Foam:Pstream::write(Foam::Pstream::commsTypes, int, char const*, int)' fvScalarMatrix.C.text+0x19c9): undefined reference to `Foam::IPstream::read(Foam::Pstream::commsTypes, int, char*, int)' fvScalarMatrix.C.text+0x1a54): undefined reference to `Foam:Pstream::write(Foam::Pstream::commsTypes, int, char const*, int)' fvScalarMatrix.C.text+0x1c23): undefined reference to `Foam::IPstream::read(Foam::Pstream::commsTypes, int, char*, int)' fvScalarMatrix.C.text+0x1c4b): undefined reference to `Foam::IPstream::read(Foam::Pstream::commsTypes, int, char*, int)' fvScalarMatrix.C.text+0x1c73): undefined reference to `Foam:Pstream::write(Foam::Pstream::commsTypes, int, char const*, int)' fvScalarMatrix.C.text+0x1c9b): undefined reference to `Foam:Pstream::write(Foam::Pstream::commsTypes, int, char const*, int)' /home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/libfiniteVolume.a(surfaceInte rpolation.o): In function `Foam::surfaceInterpolation::makeCorrectionVectors () const': surfaceInterpolation.C.text+0x1c00): undefined reference to `Foam::IPstream::read(Foam::Pstream::commsTypes, int, char*, int)' surfaceInterpolation.C.text+0x1c31): undefined reference to `Foam:Pstream::write(Foam::Pstream::commsTypes, int, char const*, int)' surfaceInterpolation.C.text+0x1c78): undefined reference to `Foam::IPstream::read(Foam::Pstream::commsTypes, int, char*, int)' surfaceInterpolation.C.text+0x1cb9): undefined reference to `Foam:Pstream::write(Foam::Pstream::commsTypes, int, char const*, int)' surfaceInterpolation.C.text+0x1e5b): undefined reference to `Foam::IPstream::read(Foam::Pstream::commsTypes, int, char*, int)' surfaceInterpolation.C.text+0x1e8c): undefined reference to `Foam:Pstream::write(Foam::Pstream::commsTypes, int, char const*, int)' surfaceInterpolation.C.text+0x1ed3): undefined reference to `Foam::IPstream::read(Foam::Pstream::commsTypes, int, char*, int)' surfaceInterpolation.C.text+0x1f14): undefined reference to `Foam:Pstream::write(Foam::Pstream::commsTypes, int, char const*, int)' These errors continue and occur for the compile/link of every executable (resulting in no binaries at all). I remade libOpenFOAM, believing that it was the problem, but the errors were the same. I have also added -lOpenFOAM and -lPstream to the link lines in the rules directory, but with no result. In an act of final desperation, I actually added references to every *.a file located in /lib/linuxGcc to the link path in rules. I still receive the same errors. Oddly enough, removing the -static flag from the rules files results in working (but dynamically/shared linked) executables, with no errors. Am I missing another step in my static compilation that the shared libraries somehow account for? I have been working on this for a little over a month now, any help would be extremely appreciated. Thanks, David herzfeldd is offline   Reply With Quote Sponsored Links Old   September 1, 2008, 04:21 Default Easy way out is to run 'statif   #2 Super Moderator   Mattijs Janssens Join Date: Mar 2009 Posts: 1,419 Rep Power: 18 mattijs is on a distinguished road Easy way out is to run 'statifier'. Converts executable with its libraries into single statically linked executable. Google for 'ELF statifier'. mattijs is offline   Reply With Quote Old   September 1, 2008, 10:45 Default Thanks, I will try it.   #3 New Member   David Herzfeld Join Date: Mar 2009 Posts: 11 Rep Power: 10 herzfeldd is on a distinguished road Thanks, I will try it. herzfeldd is offline   Reply With Quote Old   September 1, 2008, 11:20 Default I have tried using statifier t   #4 New Member   David Herzfeld Join Date: Mar 2009 Posts: 11 Rep Power: 10 herzfeldd is on a distinguished road I have tried using statifier to compose the pseudo-static executables of both icoFoam and simpleFoam. However, when I try to run either of these new executables I receive a segmentation fault. I recieve the following output from both files: Exec : ./simpleFoamStatic Date : Sep 01 2008 Time : 02:56:47 Host : --------------- PID : 18460 Segmentation fault Thanks, David herzfeldd is offline   Reply With Quote Old   September 1, 2008, 11:22 Default Running the program in gdb, sh   #5 New Member   David Herzfeld Join Date: Mar 2009 Posts: 11 Rep Power: 10 herzfeldd is on a distinguished road Running the program in gdb, shows the following error messages: Exec : /home/herzfeldd/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoamStat ic Date : Sep 01 2008 Time : 03:01:20 Host : sunpassage.eng.mu.edu PID : 18469 [New Thread 0xb7f2cae0 (LWP 18469)] Program received signal SIGSEGV, Segmentation fault. 0x00899c48 in strcmp () from /lib/ld-linux.so.2 Missing separate debuginfos, use: debuginfo-install glibc.i686 David herzfeldd is offline   Reply With Quote Old   September 1, 2008, 12:58 Default I just did (with statifier 1.6   #6 Super Moderator   Mattijs Janssens Join Date: Mar 2009 Posts: 1,419 Rep Power: 18 mattijs is on a distinguished road I just did (with statifier 1.6.3) statifier `which icoFoam` icoFoam-static and then can run icoFoam-static on cavity tutorial without problems. mattijs is offline   Reply With Quote Old   September 1, 2008, 13:24 Default I am still receiving a segment   #7 New Member   David Herzfeld Join Date: Mar 2009 Posts: 11 Rep Power: 10 herzfeldd is on a distinguished road I am still receiving a segmentation fault from some executable (not sure if it is the static icoFoam though), perhaps you could shed some light on it. I performed the same commands that you did: cd ~/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/ statifier `which icoFoam` icoFoam-static An executable, icoFoam-static, results. Running the program with no input results in a segmentation fault. Running the original icoFoam executable on the cavity test cases results in no errors: Running blockMesh on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavity Running icoFoam on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavity Cloning cavityFine case from cavity Running blockMesh on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityFine Running mapFields from cavity to cavityFine Running icoFoam on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityFine Running blockMesh on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityGrade Running mapFields from cavityFine to cavityGrade Running icoFoam on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityGrade Cloning cavityHighRe case from cavity Setting cavityHighRe to generate a secondary vortex Copying cavity/0* directory to cavityHighRe Running blockMesh on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityHighRe Running icoFoam on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityHighRe Running blockMesh on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityClipped Running mapFields from cavity to cavityClipped Running icoFoam on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityClipped fluentMeshToFoam: converting mesh elbow/elbow.msh Running icoFoam on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/elbow Running foamMeshToFluent on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/elbow Running foamDataToFluent on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/elbow Then I ran ./Allclean and changed Allrun to use the icoFoam-static executable (ie replaced application=`basename $PWD` with application=icoFoam-static), here's the output: Running blockMesh on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavity Running icoFoam-static on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavity Cloning cavityFine case from cavity Running blockMesh on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityFine Running mapFields from cavity to cavityFine Running icoFoam-static on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityFine /home/user/OpenFOAM/OpenFOAM-1.5/bin/tools/RunFunctions: line 33: 21915 Segmentation fault $APP_RUN $* > log.$APP_RUN 2>&1 Running blockMesh on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityGrade Running mapFields from cavityFine to cavityGrade Running icoFoam-static on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityGrade /home/user/OpenFOAM/OpenFOAM-1.5/bin/tools/RunFunctions: line 33: 21921 Segmentation fault $APP_RUN $* > log.$APP_RUN 2>&1 Cloning cavityHighRe case from cavity Setting cavityHighRe to generate a secondary vortex Copying cavity/0* directory to cavityHighRe Running blockMesh on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityHighRe Running icoFoam-static on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityHighRe /home/user/OpenFOAM/OpenFOAM-1.5/bin/tools/RunFunctions: line 33: 21934 Segmentation fault $APP_RUN $* > log.$APP_RUN 2>&1 Running blockMesh on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityClipped Running mapFields from cavity to cavityClipped Running icoFoam-static on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/cavityClipped /home/user/OpenFOAM/OpenFOAM-1.5/bin/tools/RunFunctions: line 33: 21943 Segmentation fault $APP_RUN $* > log.$APP_RUN 2>&1 fluentMeshToFoam: converting mesh elbow/elbow.msh Running icoFoam-static on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/elbow /home/user/OpenFOAM/OpenFOAM-1.5/bin/tools/RunFunctions: line 33: 21946 Segmentation fault $APP_RUN $* > log.$APP_RUN 2>&1 Running foamMeshToFluent on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/elbow Running foamDataToFluent on /home/user/OpenFOAM/OpenFOAM-1.5/tutorials/icoFoam/elbow A BIG thanks for all your help thus far (in one day I am already father along that a whole month previous), David herzfeldd is offline   Reply With Quote Old   September 1, 2008, 15:13 Default Executables packed with statif   #8 New Member   Valery Reznic Join Date: Mar 2009 Posts: 9 Rep Power: 10 valery_reznic is on a distinguished road Executables packed with statifier doesn't like systems with vDSO and/or stack randomization. Executables packed with Ermine - http://magicErmine.com (while propertiary) usually behave themselv on such systems. valery_reznic is offline   Reply With Quote Old   September 2, 2008, 03:51 Default Hi David, ran all icoFoam t   #9 Super Moderator   Mattijs Janssens Join Date: Mar 2009 Posts: 1,419 Rep Power: 18 mattijs is on a distinguished road Hi David, ran all icoFoam testcases (since your cavity ran fine but not the other cases) successfully. This is on Suse10.2, gcc 4.3.1. Are you running something like Valery suggested (randomisation etc. How do you find this out?) mattijs is offline   Reply With Quote Old   September 2, 2008, 05:27 Default It's looks like you have LD_LI   #10 New Member   Valery Reznic Join Date: Mar 2009 Posts: 9 Rep Power: 10 valery_reznic is on a distinguished road It's looks like you have LD_LIBRARY_PATH environment variable set. You can try ./ErmineLight.i386 --ld_library_path="$LD_LIBRARY_PATH" icoFoam --output=icoFoam-static valery_reznic is offline   Reply With Quote Old   September 2, 2008, 10:20 Default Mattijs, I am not sure how to   #11 New Member   David Herzfeld Join Date: Mar 2009 Posts: 11 Rep Power: 10 herzfeldd is on a distinguished road Mattijs, I am not sure how to test for vDSO or stack randomization (or confirm that either exist on my system). However, IT WORKED! Sending LD_LIBRARY_PATH to Ermine produced an executable that works in all test cases. Valery, could you try to explain why Ermine worked but statifier did not? I am a running Fedora Core 9, with SMP enabled on two i686 processors. Thanks for all your help! David herzfeldd is offline   Reply With Quote Old   September 2, 2008, 10:30 Default Another problem just cropped u   #12 New Member   David Herzfeld Join Date: Mar 2009 Posts: 11 Rep Power: 10 herzfeldd is on a distinguished road Another problem just cropped up... The statically compiled executables (icoFoam-static and simpleFoam-static) work correctly on the original computer, but moving these executables over to a different computer with the same architecture produces a segmentation fault immediately. Here is the architecture of the computer that I created the static executables on (uname -a) Linux localhost.localdomain 2.6.25-14.fc9.i686 #1 SMP Thu May 1 06:28:41 EDT 2008 i686 i686 i386 GNU/Linux Here's the new box: Linux localhost2.localdomain 2.6.20-1.2320.fc5smp #1 SMP Tue Jun 12 19:40:16 EDT 2007 i686 i686 i386 GNU/Linux Could it be the differences in the kernel? herzfeldd is offline   Reply With Quote Old   September 2, 2008, 11:49 Default Hi David! Can't rule out th   #13 Assistant Moderator   Bernhard Gschaider Join Date: Mar 2009 Posts: 4,008 Rep Power: 43 gschaider will become famous soon enoughgschaider will become famous soon enough Hi David! Can't rule out the kernel. But another thing is that usually OF-executables need a "minimal" OF-environment that consists of (I'm doing this from memory so it's a bit vague) - one or two environment variables ($WM_something ...) - one or two files whose location depends on the environment variables (the system-wide controlDict is one of them I think) If your other machine "sees" your OF-installation (env-variables & files) this shouldn't be the problem) Try to run the executable with strace (this might give you more information on the why of the segmentation fault) Bernhard __________________ Note: I don't use "Friend"-feature on this forum out of principle. Ah. And by the way: I'm not on Facebook either. So don't be offended if I don't accept your invitation/friend request gschaider is offline   Reply With Quote Old   September 2, 2008, 12:12 Default Hi, David. When you wrote "st   #14 New Member   Valery Reznic Join Date: Mar 2009 Posts: 9 Rep Power: 10 valery_reznic is on a distinguished road Hi, David. When you wrote "static" you mean packed with Ermine ? If yes could you show output of strace <your_program> Valery. valery_reznic is offline   Reply With Quote Old   September 2, 2008, 14:02 Default Valey: Yes, when I said "stati   #15 New Member   David Herzfeld Join Date: Mar 2009 Posts: 11 Rep Power: 10 herzfeldd is on a distinguished road Valey: Yes, when I said "static" I meant packed with Ermine. Bernhard: I moved the icoFoam and simpleFoam packed executables with an updated kernel, still I receive a segmentation fault. Below is the output for strace and both the local and remote systems (I had to split it all up because it exceeds the size limit for the forum). David herzfeldd is offline   Reply With Quote Old   September 2, 2008, 14:05 Default Local System: execve("/home/u   #16 New Member   David Herzfeld Join Date: Mar 2009 Posts: 11 Rep Power: 10 herzfeldd is on a distinguished road Local System: execve("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam- static", ["icoFoam-static"], [/* 72 vars */]) = 0 readlink("/proc/self/exe", "/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-static" , 4096) = 83 uname({sys="Linux", node="locahost.eng.mu.edu", ...}) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 fstat64(3, {st_mode=S_IFREG|0775, st_size=28475548, ...}) = 0 old_mmap(NULL, 16384, PROT_READ, MAP_PRIVATE, 3, 0xd000) = 0xb7f7d000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 22077440, SEEK_SET) = 22077440 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\2\0\3\0\1\0\0\0\3 20\220\5\0104\0\0\0"..., 512) = 512 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 4 lseek(4, 69632, SEEK_SET) = 69632 read(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\000 08\210\0004\0\0\0"..., 512) = 512 readlink("/proc/self/exe", "/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-static" , 4096) = 83 lseek(3, -512, SEEK_CUR) = 22077440 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\2\0\3\0\1\0\0\0\3 20\220\5\0104\0\0\0"..., 512, 22077440) = 512 old_mmap(0x8048000, 368640, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x8048000 old_mmap(0x8048000, 364544, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x8048000 lseek(3, 22077440, SEEK_SET) = 22077440 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\2\0\3\0\1\0\0\0\3 20\220\5\0104\0\0\0"..., 364544, 22077440) = 364544 mprotect(0x8048000, 364544, PROT_READ|PROT_EXEC) = 0 old_mmap(0x80a1000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 3, 0x1566000) = 0x80a1000 close(3) = 0 lseek(4, -512, SEEK_CUR) = 69632 pread64(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\000 08\210\0004\0\0\0"..., 512, 69632) = 512 old_mmap(0x883000, 122880, PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x883000 old_mmap(0x883000, 114688, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x883000 lseek(4, 69632, SEEK_SET) = 69632 pread64(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\000 08\210\0004\0\0\0"..., 114688, 69632) = 114688 mprotect(0x883000, 114688, PROT_READ|PROT_EXEC) = 0 old_mmap(0x89f000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 4, 0x2d000) = 0x89f000 close(4) = 0 brk(0) = 0x109cc000 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7f7c000 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/tls", 0xbf97e430) = -1 ENOENT (No such file or directory) open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 6942720, SEEK_SET) = 6942720 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0`\ 207#\0004\0\0\0"..., 512) = 512 mmap2(NULL, 10675996, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x69f) = 0xb754d000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0`\ 207#\0004\0\0\0"..., 10675996, 6942720) = 10675996 mprotect(0xb754d000, 10531003, PROT_READ|PROT_EXEC) = 0 mmap2(0xb7f59000, 131072, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x10aa) = 0xb7f59000 mmap2(0xb7f79000, 10012, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb7f79000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 2469888, SEEK_SET) = 2469888 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0P\ 20\f\0004\0\0\0"..., 512) = 512 mmap2(NULL, 3829360, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x25b) = 0xb71a6000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0P\ 20\f\0004\0\0\0"..., 3829360, 2469888) = 3829360 mprotect(0xb71a6000, 3758785, PROT_READ|PROT_EXEC) = 0 mmap2(0xb753c000, 53248, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x5f0) = 0xb753c000 mmap2(0xb7549000, 15984, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb7549000 close(3) = 0 stat64("/home/user/OpenFOAM/ThirdParty/gcc-4.3.1/platforms/linux/lib/tls", 0xbf97e3f8) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/ThirdParty/gcc-4.3.1/platforms/linux/lib", {st_mode=S_IFDIR|0750, st_size=4096, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/openmpi-1.2.6/tls", 0xbf97e3f8) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/openmpi-1.2.6", {st_mode=S_IFDIR|0750, st_size=4096, ...}) = 0 stat64("/home/user/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/lib /tls", 0xbf97e3f8) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/lib ", {st_mode=S_IFDIR|0750, st_size=4096, ...}) = 0 stat64("/lib/tls", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 1970176, SEEK_SET) = 1970176 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0`\ 232\243\0004\0\0\0"..., 512) = 512 mmap2(0xa39000, 16500, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1e1) = 0xa39000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0`\ 232\243\0004\0\0\0"..., 16500, 1970176) = 16500 mprotect(0xa39000, 8364, PROT_READ|PROT_EXEC) = 0 mmap2(0xa3c000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1e3) = 0xa3c000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 22835200, SEEK_SET) = 22835200 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 00\352\3\0004\0\0\0"..., 512) = 512 mmap2(NULL, 952504, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x15c7) = 0xb70bd000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 00\352\3\0004\0\0\0"..., 952504, 22835200) = 952504 mprotect(0xb70bd000, 905520, PROT_READ|PROT_EXEC) = 0 mmap2(0xb719b000, 20480, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x16a4) = 0xb719b000 mmap2(0xb71a0000, 22712, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb71a0000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 1990656, SEEK_SET) = 1990656 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \24\241\0004\0\0\0"..., 512) = 512 mmap2(0xa0e000, 163952, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1e6) = 0xa0e000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \24\241\0004\0\0\0"..., 163952, 1990656) = 163952 mprotect(0xa0e000, 156364, PROT_READ|PROT_EXEC) = 0 mmap2(0xa35000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x20c) = 0xa35000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 22556672, SEEK_SET) = 22556672 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 40\30\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb70bc000 mmap2(NULL, 51528, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1583) = 0xb70af000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 40\30\0\0004\0\0\0"..., 51528, 22556672) = 51528 mprotect(0xb70af000, 46644, PROT_READ|PROT_EXEC) = 0 mmap2(0xb70bb000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x158e) = 0xb70bb000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 2318336, SEEK_SET) = 2318336 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 0(\246\0004\0\0\0"..., 512) = 512 mmap2(0xa5e000, 98784, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x236) = 0xa5e000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 0(\246\0004\0\0\0"..., 98784, 2318336) = 98784 mprotect(0xa5e000, 85088, PROT_READ|PROT_EXEC) = 0 mmap2(0xa73000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x24a) = 0xa73000 mmap2(0xa75000, 4576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xa75000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 208896, SEEK_SET) = 208896 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0@\ 227\213\0004\0\0\0"..., 512) = 512 mmap2(0x8a3000, 1476176, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x33) = 0x8a3000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0@\ 227\213\0004\0\0\0"..., 1476176, 208896) = 1476176 mprotect(0x8a3000, 1453240, PROT_READ|PROT_EXEC) = 0 mmap2(0xa06000, 12288, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x196) = 0xa06000 mmap2(0xa09000, 9808, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xa09000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 22511616, SEEK_SET) = 22511616 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 60*\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 38236, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1578) = 0xb70a5000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 60*\0\0004\0\0\0"..., 38236, 22511616) = 38236 mprotect(0xb70a5000, 33018, PROT_READ|PROT_EXEC) = 0 mmap2(0xb70ae000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1580) = 0xb70ae000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 21483520, SEEK_SET) = 21483520 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 60\334\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 454972, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x147d) = 0xb7035000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 60\334\0\0004\0\0\0"..., 454972, 21483520) = 454972 mprotect(0xb7035000, 450554, PROT_READ|PROT_EXEC) = 0 mmap2(0xb70a3000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x14eb) = 0xb70a3000 mmap2(0xb70a4000, 316, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb70a4000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 19566592, SEEK_SET) = 19566592 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\0 f\4\0004\0\0\0"..., 512) = 512 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7034000 mmap2(NULL, 1680608, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x12a9) = 0xb6e99000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\0 f\4\0004\0\0\0"..., 1680608, 19566592) = 1680608 mprotect(0xb6e99000, 1661926, PROT_READ|PROT_EXEC) = 0 mmap2(0xb702f000, 16384, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x143f) = 0xb702f000 mmap2(0xb7033000, 1248, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb7033000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 21987328, SEEK_SET) = 21987328 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \26\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 78564, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x14f8) = 0xb6e85000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \26\0\0004\0\0\0"..., 78564, 21987328) = 78564 mprotect(0xb6e85000, 77700, PROT_READ|PROT_EXEC) = 0 mmap2(0xb6e98000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x150b) = 0xb6e98000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 27205632, SEEK_SET) = 27205632 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 20*\1\0004\0\0\0"..., 512) = 512 mmap2(NULL, 510168, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x19f2) = 0xb6e08000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 20*\1\0004\0\0\0"..., 510168, 27205632) = 510168 mprotect(0xb6e08000, 452196, PROT_READ|PROT_EXEC) = 0 mmap2(0xb6e77000, 32768, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1a60) = 0xb6e77000 mmap2(0xb6e7f000, 22744, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb6e7f000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 19533824, SEEK_SET) = 19533824 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 40\"\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 21320, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x12a1) = 0xb6e02000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 40\"\0\0004\0\0\0"..., 21320, 19533824) = 21320 mprotect(0xb6e02000, 20208, PROT_READ|PROT_EXEC) = 0 mmap2(0xb6e07000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x12a6) = 0xb6e07000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 28073984, SEEK_SET) = 28073984 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 20\334\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb6e01000 mmap2(NULL, 339872, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1ac6) = 0xb6dae000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 20\334\0\0004\0\0\0"..., 339872, 28073984) = 339872 mprotect(0xb6dae000, 327544, PROT_READ|PROT_EXEC) = 0 mmap2(0xb6dfe000, 12288, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b16) = 0xb6dfe000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 27803648, SEEK_SET) = 27803648 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 20\233\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 362688, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1a84) = 0xb6d55000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 20\233\0\0004\0\0\0"..., 362688, 27803648) = 362688 mprotect(0xb6d55000, 213688, PROT_READ|PROT_EXEC) = 0 mmap2(0xb6d8a000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1ab8) = 0xb6d8a000 mmap2(0xb6d8c000, 137408, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb6d8c000 close(3) = 0 open("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/ lib/tls/i386/libnsl.so.1", O_RDONLY) = -1 ENOENT (No such file or directory) stat64("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOp t/lib/tls/i386", 0xbf97db74) = -1 ENOENT (No such file or directory) open("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/ lib/tls/libnsl.so.1", O_RDONLY) = -1 ENOENT (No such file or directory) stat64("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOp t/lib/tls", 0xbf97db74) = -1 ENOENT (No such file or directory) open("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/ lib/i386/libnsl.so.1", O_RDONLY) = -1 ENOENT (No such file or directory) stat64("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOp t/lib/i386", 0xbf97db74) = -1 ENOENT (No such file or directory) open("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/ lib/libnsl.so.1", O_RDONLY) = -1 ENOENT (No such file or directory) stat64("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOp t/lib", 0xbf97db74) = -1 ENOENT (No such file or directory) open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 2203648, SEEK_SET) = 2203648 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\000 0\321|\0004\0\0\0"..., 512) = 512 mmap2(0x7ca000, 104392, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x21a) = 0x7ca000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\000 0\321|\0004\0\0\0"..., 104392, 2203648) = 104392 mprotect(0x7ca000, 87276, PROT_READ|PROT_EXEC) = 0 mmap2(0x7e0000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x22f) = 0x7e0000 mmap2(0x7e2000, 6088, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7e2000 close(3) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoFoam-st atic", O_RDONLY) = 3 lseek(3, 2453504, SEEK_SET) = 2453504 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \332J\0074\0\0\0"..., 512) = 512 mmap2(0x74ad000, 12420, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x257) = 0x74ad000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \332J\0074\0\0\0"..., 12420, 2453504) = 12420 mprotect(0x74ad000, 6148, PROT_READ|PROT_EXEC) = 0 mmap2(0x74af000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x258) = 0x74af000 close(3) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb6d54000 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb6d53000 set_thread_area({entry_number:-1 -> 6, base_addr:0xb6d538e0, limit:1048575, seg_32bit:1, contents:0, read_exec_only:0, limit_in_pages:1, seg_not_present:0, useable:1}) = 0 set_tid_address(0xb6d53928) = 25610 set_robust_list(0xb6d53930, 0xc) = 0 futex(0xbf97eb80, FUTEX_WAKE_PRIVATE, 1) = 0 rt_sigaction(SIGRTMIN, {0xa622c0, [], SA_SIGINFO}, NULL, 8) = 0 rt_sigaction(SIGRT_1, {0xa62700, [], SA_RESTART|SA_SIGINFO}, NULL, 8) = 0 rt_sigprocmask(SIG_UNBLOCK, [RTMIN RT_1], NULL, 8) = 0 getrlimit(RLIMIT_STACK, {rlim_cur=10240*1024, rlim_max=RLIM_INFINITY}) = 0 uname({sys="Linux", node="locahost.eng.mu.edu", ...}) = 0 futex(0xb71a06dc, FUTEX_WAKE_PRIVATE, 2147483647) = 0 futex(0xb71a5848, FUTEX_WAKE_PRIVATE, 2147483647) = 0 futex(0xb71a5868, FUTEX_WAKE_PRIVATE, 2147483647) = 0 brk(0) = 0x109cc000 brk(0x109ed000) = 0x109ed000 stat64("/root/.OpenFOAM", 0xbf97e824) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM", {st_mode=S_IFDIR|0775, st_size=4096, ...}) = 0 stat64("/home/user/OpenFOAM/site/1.5/controlDict", 0xbf97e814) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/site/1.5/controlDict", 0xbf97e7d4) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/site/1.5/controlDict.gz", 0xbf97e7d4) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/site/controlDict", 0xbf97e814) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/site/controlDict", 0xbf97e7d4) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/site/controlDict.gz", 0xbf97e7d4) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/OpenFOAM-1.5", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/etc/controlDict", {st_mode=S_IFREG|0640, st_size=25240, ...}) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/etc/controlDict", O_RDONLY|O_LARGEFILE) = 3 read(3, "/*------------------------------"..., 8191) = 8191 read(3, "0;\n cellToCell 0;\n "..., 8191) = 8191 brk(0x10a0e000) = 0x10a0e000 brk(0x10a0d000) = 0x10a0d000 read(3, "orinsky 0;\n mixedUnburntEn"..., 8191) = 8191 read(3, "Universal gas constant [J/(kmol "..., 8191) = 667 read(3, "", 8191) = 0 close(3) = 0 brk(0x10a2e000) = 0x10a2e000 stat64("/dev/null.gz", 0xbf97e824) = -1 ENOENT (No such file or directory) stat64("/dev/null.gz.gz", 0xbf97e824) = -1 ENOENT (No such file or directory) open("/dev/null", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 3 stat64("/root/.OpenFOAM", 0xbf97e854) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM", {st_mode=S_IFDIR|0775, st_size=4096, ...}) = 0 stat64("/home/user/OpenFOAM/site/1.5/cellModels", 0xbf97e844) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/site/1.5/cellModels", 0xbf97e804) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/site/1.5/cellModels.gz", 0xbf97e804) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/site/cellModels", 0xbf97e844) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/site/cellModels", 0xbf97e804) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/site/cellModels.gz", 0xbf97e804) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/OpenFOAM-1.5", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/etc/cellModels", {st_mode=S_IFREG|0640, st_size=7754, ...}) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/etc/cellModels", O_RDONLY|O_LARGEFILE) = 4 read(4, "/*------------------------------"..., 8191) = 7754 close(4) = 0 uname({sys="Linux", node="locahost.eng.mu.edu", ...}) = 0 times({tms_utime=24, tms_stime=5, tms_cutime=0, tms_cstime=0}) = 558148283 brk(0x10a4f000) = 0x10a4f000 fstat64(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb6d52000 write(1, "/*------------------------------"..., 80/*---------------------------------------------------------------------------* \ ) = 80 write(1, "| ========= | "..., 160| ========= | | | \ / F ield | OpenFOAM: The Open Source CFD Toolbox | ) = 160 write(1, "| \\ / O peration | Ve"..., 320| \ / O peration | Version: 1.5 | | \ / A nd | Web: http://www.OpenFOAM.org | | \/ M anipulation | | \*---------------------------------------------------------------------------*/ Continued Below herzfeldd is offline   Reply With Quote Old   September 2, 2008, 14:06 Default ) = 320 time(NULL)   #17 New Member   David Herzfeld Join Date: Mar 2009 Posts: 11 Rep Power: 10 herzfeldd is on a distinguished road ) = 320 time(NULL) = 1220351549 open("/etc/localtime", O_RDONLY) = 4 fstat64(4, {st_mode=S_IFREG|0644, st_size=3543, ...}) = 0 fstat64(4, {st_mode=S_IFREG|0644, st_size=3543, ...}) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb6d51000 read(4, "TZif2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\5\0\0\0 \5\0\0\0\0"..., 4096) = 3543 _llseek(4, -24, [3519], SEEK_CUR) = 0 read(4, "\nCST6CDT,M3.2.0,M11.1.0\n", 4096) = 24 close(4) = 0 munmap(0xb6d51000, 4096) = 0 time(NULL) = 1220351549 stat64("/etc/localtime", {st_mode=S_IFREG|0644, st_size=3543, ...}) = 0 uname({sys="Linux", node="locahost.eng.mu.edu", ...}) = 0 write(1, "Exec : icoFoam-static\n", 24Exec : icoFoam-static ) = 24 write(1, "Date : Sep 02 2008\n", 21Date : Sep 02 2008 ) = 21 write(1, "Time : 05:32:29\n", 18Time : 05:32:29 ) = 18 write(1, "Host : locahost.eng.mu.edu\n", 31Host : locahost.eng.mu.edu ) = 31 write(1, "PID : 25610\n", 15PID : 25610 ) = 15 getuid32() = 0 socket(PF_FILE, SOCK_STREAM, 0) = 4 fcntl64(4, F_SETFL, O_RDWR|O_NONBLOCK) = 0 connect(4, {sa_family=AF_FILE, path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory) close(4) = 0 socket(PF_FILE, SOCK_STREAM, 0) = 4 fcntl64(4, F_SETFL, O_RDWR|O_NONBLOCK) = 0 connect(4, {sa_family=AF_FILE, path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory) close(4) = 0 open("/etc/nsswitch.conf", O_RDONLY) = 4 fstat64(4, {st_mode=S_IFREG|0644, st_size=1708, ...}) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb6d51000 read(4, "#\n# /etc/nsswitch.conf\n#\n# An ex"..., 4096) = 1708 read(4, "", 4096) = 0 close(4) = 0 munmap(0xb6d51000, 4096) = 0 open("/home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/tls/libnss_files.so.2", O_RDONLY) = -1 ENOENT (No such file or directory) open("/home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/libnss_files.so.2", O_RDONLY) = -1 ENOENT (No such file or directory) open("/home/user/OpenFOAM/ThirdParty/gcc-4.3.1/platforms/linux/lib/tls/libnss_fi les.so.2", O_RDONLY) = -1 ENOENT (No such file or directory) open("/home/user/OpenFOAM/ThirdParty/gcc-4.3.1/platforms/linux/lib/libnss_files. so.2", O_RDONLY) = -1 ENOENT (No such file or directory) open("/home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/openmpi-1.2.6/tls/libns s_files.so.2", O_RDONLY) = -1 ENOENT (No such file or directory) open("/home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/openmpi-1.2.6/libnss_fi les.so.2", O_RDONLY) = -1 ENOENT (No such file or directory) open("/home/user/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/lib/t ls/libnss_files.so.2", O_RDONLY) = -1 ENOENT (No such file or directory) open("/home/user/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/lib/l ibnss_files.so.2", O_RDONLY) = -1 ENOENT (No such file or directory) open("/lib/tls/libnss_files.so.2", O_RDONLY) = -1 ENOENT (No such file or directory) open("/lib/libnss_files.so.2", O_RDONLY) = 4 read(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 40\30\0\0004\0\0\0"..., 512) = 512 fstat64(4, {st_mode=S_IFREG|0755, st_size=54828, ...}) = 0 mmap2(NULL, 45712, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 4, 0) = 0x111000 mmap2(0x11b000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 4, 0xa) = 0x11b000 close(4) = 0 mprotect(0x11b000, 4096, PROT_READ) = 0 open("/etc/passwd", O_RDONLY|0x80000 /* O_??? */) = 4 fcntl64(4, F_GETFD) = 0x1 (flags FD_CLOEXEC) fstat64(4, {st_mode=S_IFREG|0644, st_size=1918, ...}) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb6d51000 read(4, "root:x:0:0:root:/root:/bin/bash\n"..., 4096) = 1918 close(4) = 0 munmap(0xb6d51000, 4096) = 0 getcwd("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt", 255) = 69 getppid() = 25609 getpgrp() = 25609 getcwd("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt", 255) = 69 write(1, "Case : /home/user/OpenFOA"..., 78Case : /home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt ) = 78 write(1, "nProcs : 1\n", 11nProcs : 1 ) = 11 rt_sigaction(SIGFPE, {0xb74bd220, [], SA_NOMASK}, {SIG_DFL}, 8) = 0 rt_sigaction(SIGINT, {0xb74bf2a0, [], SA_NOMASK}, {SIG_DFL}, 8) = 0 rt_sigaction(SIGQUIT, {0xb74bf680, [], SA_NOMASK}, {SIG_DFL}, 8) = 0 rt_sigaction(SIGSEGV, {0xb74beeb0, [], SA_NOMASK}, {SIG_DFL}, 8) = 0 write(1, "\n", 1 ) = 1 write(1, "// * * * * * * * * * * * * * * *"..., 80// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ) = 80 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt", {st_mode=S_IFDIR|0750, st_size=12288, ...}) = 0 write(1, "Create time\n", 12Create time ) = 12 write(1, "\n", 1 ) = 1 time(NULL) = 1220351549 times({tms_utime=24, tms_stime=5, tms_cutime=0, tms_cstime=0}) = 558148284 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/system/c ontrolDict", 0xbf97cdc4) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/system/c ontrolDict.gz", 0xbf97cdc4) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/system", 0xbf97cdf4) = -1 ENOENT (No such file or directory) open("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt", O_RDONLY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY|0x8000 0) = 4 fstat64(4, {st_mode=S_IFDIR|0750, st_size=12288, ...}) = 0 fcntl64(4, F_GETFD) = 0x1 (flags FD_CLOEXEC) getdents(4, /* 153 entries */, 4096) = 4084 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/subsetMe sh", {st_mode=S_IFREG|0775, st_size=1037469, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/molConfi g", {st_mode=S_IFREG|0775, st_size=103337, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/flattenM esh", {st_mode=S_IFREG|0775, st_size=42625, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/rhoPimpl eFoam", {st_mode=S_IFREG|0775, st_size=501106, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/lesCavit atingFoam", {st_mode=S_IFREG|0775, st_size=810876, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/wallGrad U", {st_mode=S_IFREG|0775, st_size=114253, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/mergeMes hes", {st_mode=S_IFREG|0775, st_size=80454, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/foamToEn sightParts", {st_mode=S_IFREG|0775, st_size=478454, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/surfaceT oPatch", {st_mode=S_IFREG|0775, st_size=61049, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/patchInt egrate", {st_mode=S_IFREG|0775, st_size=149773, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/PDRFoam" , {st_mode=S_IFREG|0775, st_size=1413336, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/rhoSimpl eFoam", {st_mode=S_IFREG|0775, st_size=470034, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/insideCe lls", {st_mode=S_IFREG|0775, st_size=24585, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/splitCel ls", {st_mode=S_IFREG|0775, st_size=69648, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/surfaceC oarsen", {st_mode=S_IFREG|0775, st_size=64313, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/momentSc alarError", {st_mode=S_IFREG|0775, st_size=401656, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/nonNewto nianIcoFoam", {st_mode=S_IFREG|0775, st_size=429898, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/surfaceC onvert", {st_mode=S_IFREG|0775, st_size=23431, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/plot3dTo Foam", {st_mode=S_IFREG|0775, st_size=53279, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/foamToFi eldview9", {st_mode=S_IFREG|0775, st_size=454568, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/enstroph y", {st_mode=S_IFREG|0775, st_size=283835, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/tetgenTo Foam", {st_mode=S_IFREG|0775, st_size=58406, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/stressCo mponents", {st_mode=S_IFREG|0775, st_size=400764, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/rhoPorou sSimpleFoam", {st_mode=S_IFREG|0775, st_size=580651, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/netgenNe utralToFoam", {st_mode=S_IFREG|0775, st_size=44938, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/splitMes hRegions", {st_mode=S_IFREG|0775, st_size=1002549, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/twoLiqui dMixingFoam", {st_mode=S_IFREG|0775, st_size=741090, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/Lambda2" , {st_mode=S_IFREG|0775, st_size=361430, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/moveDyna micMesh", {st_mode=S_IFREG|0775, st_size=17227, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/settling Foam", {st_mode=S_IFREG|0775, st_size=876824, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/compress ibleLesInterFoam", {st_mode=S_IFREG|0775, st_size=818388, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/checkMes h", {st_mode=S_IFREG|0775, st_size=121348, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/foamToEn sight", {st_mode=S_IFREG|0775, st_size=677414, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/writeMes hObj", {st_mode=S_IFREG|0775, st_size=79346, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/decompos ePar", {st_mode=S_IFREG|0775, st_size=1271300, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/surfaceR efineRedGreen", {st_mode=S_IFREG|0775, st_size=23409, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/refineme ntLevel", {st_mode=S_IFREG|0775, st_size=135846, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/foamForm atConvert", {st_mode=S_IFREG|0775, st_size=80315, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/chtMulti RegionFoam", {st_mode=S_IFREG|0775, st_size=684539, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/extrude2 DMesh", {st_mode=S_IFREG|0775, st_size=55690, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/financia lFoam", {st_mode=S_IFREG|0775, st_size=342290, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/interFoa m", {st_mode=S_IFREG|0775, st_size=696668, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/refineHe xMesh", {st_mode=S_IFREG|0775, st_size=753440, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/icoMomen tError", {st_mode=S_IFREG|0775, st_size=482710, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/setField s", {st_mode=S_IFREG|0775, st_size=412858, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/setsToZo nes", {st_mode=S_IFREG|0775, st_size=59374, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/polyDual Mesh", {st_mode=S_IFREG|0775, st_size=32966, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/gmshToFo am", {st_mode=S_IFREG|0775, st_size=103042, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/solidEqu ilibriumDisplacementFoam", {st_mode=S_IFREG|0775, st_size=654818, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/probeLoc ations", {st_mode=S_IFREG|0775, st_size=27683, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/foamToSt arMesh", {st_mode=S_IFREG|0775, st_size=44466, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/ansysToF oam", {st_mode=S_IFREG|0775, st_size=106075, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/twoPhase EulerFoam", {st_mode=S_IFREG|0775, st_size=1038023, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/rasCavit atingFoam", {st_mode=S_IFREG|0775, st_size=655283, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/Co", {st_mode=S_IFREG|0775, st_size=182629, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/buoyantS impleRadiationFoam", {st_mode=S_IFREG|0775, st_size=500626, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/oodles", {st_mode=S_IFREG|0775, st_size=420374, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/attachMe sh", {st_mode=S_IFREG|0775, st_size=25383, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/sonicTur bFoam", {st_mode=S_IFREG|0775, st_size=474849, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/turbFoam ", {st_mode=S_IFREG|0775, st_size=420314, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/engineSw irl", {st_mode=S_IFREG|0775, st_size=114690, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/transfor mPoints", {st_mode=S_IFREG|0775, st_size=696672, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/pdfPlot" , {st_mode=S_IFREG|0775, st_size=19046, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/mshToFoa m", {st_mode=S_IFREG|0775, st_size=31613, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/scalarTr ansportFoam", {st_mode=S_IFREG|0775, st_size=323068, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/redistri buteMeshPar", {st_mode=S_IFREG|0775, st_size=873997, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/renumber Mesh", {st_mode=S_IFREG|0775, st_size=726971, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/rhoSonic Foam", {st_mode=S_IFREG|0775, st_size=411784, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/interPha seChangeFoam", {st_mode=S_IFREG|0775, st_size=965533, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/autoPatc h", {st_mode=S_IFREG|0775, st_size=63198, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/vorticit y", {st_mode=S_IFREG|0775, st_size=282629, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/mergeOrS plitBaffles", {st_mode=S_IFREG|0775, st_size=735566, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/buoyantF oam", {st_mode=S_IFREG|0775, st_size=515293, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/coldEngi neFoam", {st_mode=S_IFREG|0775, st_size=497020, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/sonicLiq uidFoam", {st_mode=S_IFREG|0775, st_size=483356, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/refineWa llLayer", {st_mode=S_IFREG|0775, st_size=71319, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/coodles" , {st_mode=S_IFREG|0775, st_size=479299, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/extrudeM esh", {st_mode=S_IFREG|0775, st_size=147666, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/yPlusLES ", {st_mode=S_IFREG|0775, st_size=291233, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/Q", {st_mode=S_IFREG|0775, st_size=283713, ...}) = 0 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/applications/bin/linuxGccDPOpt/dnsFoam" , {st_mode=S_IFREG|0775, st_size=522006, ...}) = 0 write(2, "fileName::stripInvalid() called "..., 53fileName::stripInvalid() called for invalid fileName ) = 53 write(2, "libfiniteVolume.so", 18libfiniteVolume.so) = 18 write(2, "\n", 1 ) = 1 write(2, " For debug level (= ", 23 For debug level (= ) = 23 write(2, "2", 12) = 1 write(2, ") > 1 this is considered fatal", 30) > 1 this is considered fatal) = 30 write(2, "\n", 1 ) = 1 rt_sigprocmask(SIG_UNBLOCK, [ABRT], NULL, 8) = 0 tgkill(25610, 25610, SIGABRT) = 0 --- SIGABRT (Aborted) @ 0 (0) --- +++ killed by SIGABRT +++ Note: An error has appeared on this system (that perhaps I did not see before). fileName::stripInvalid() called for invalid fileName libfiniteVolume.so For debug level (= 2) > 1 this is considered fatal Aborted One the remote system, I receive `strace icoFoam-static`: execve("./icoFoam-static", ["./icoFoam-static"], [/* 45 vars */]) = 0 readlink("/proc/self/exe", "/home/user/Desktop/icoFoam-static", 4096) = 34 uname({sys="Linux", node="locahost2", ...}) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 fstat64(3, {st_mode=S_IFREG|0775, st_size=28475548, ...}) = 0 old_mmap(NULL, 16384, PROT_READ, MAP_PRIVATE, 3, 0xd000) = 0xb7f9d000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 22077440, SEEK_SET) = 22077440 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\2\0\3\0\1\0\0\0\3 20\220\5\0104\0\0\0"..., 512) = 512 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 4 lseek(4, 69632, SEEK_SET) = 69632 read(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\000 08\210\0004\0\0\0"..., 512) = 512 readlink("/proc/self/exe", "/home/user/Desktop/icoFoam-static", 4096) = 34 lseek(3, -512, SEEK_CUR) = 22077440 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\2\0\3\0\1\0\0\0\3 20\220\5\0104\0\0\0"..., 512, 22077440) = 512 old_mmap(0x8048000, 368640, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x8048000 old_mmap(0x8048000, 364544, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x8048000 lseek(3, 22077440, SEEK_SET) = 22077440 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\2\0\3\0\1\0\0\0\3 20\220\5\0104\0\0\0"..., 364544, 22077440) = 364544 mprotect(0x8048000, 364544, PROT_READ|PROT_EXEC) = 0 old_mmap(0x80a1000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 3, 0x1566000) = 0x80a1000 close(3) = 0 lseek(4, -512, SEEK_CUR) = 69632 pread64(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\000 08\210\0004\0\0\0"..., 512, 69632) = 512 old_mmap(0x883000, 122880, PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x883000 old_mmap(0x883000, 114688, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x883000 lseek(4, 69632, SEEK_SET) = 69632 pread64(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\000 08\210\0004\0\0\0"..., 114688, 69632) = 114688 mprotect(0x883000, 114688, PROT_READ|PROT_EXEC) = 0 old_mmap(0x89f000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 4, 0x2d000) = 0x89f000 close(4) = 0 brk(0) = 0x119cb000 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7f9c000 stat64("/home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/tls", 0xbfa9d680) = -1 ENOENT (No such file or directory) open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 6942720, SEEK_SET) = 6942720 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0`\ 207#\0004\0\0\0"..., 512) = 512 mmap2(NULL, 10675996, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x69f) = 0xb756d000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0`\ 207#\0004\0\0\0"..., 10675996, 6942720) = 10675996 mprotect(0xb756d000, 10531003, PROT_READ|PROT_EXEC) = 0 mmap2(0xb7f79000, 131072, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x10aa) = 0xb7f79000 mmap2(0xb7f99000, 10012, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb7f99000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 2469888, SEEK_SET) = 2469888 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0P\ 20\f\0004\0\0\0"..., 512) = 512 mmap2(NULL, 3829360, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x25b) = 0xb71c6000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0P\ 20\f\0004\0\0\0"..., 3829360, 2469888) = 3829360 mprotect(0xb71c6000, 3758785, PROT_READ|PROT_EXEC) = 0 mmap2(0xb755c000, 53248, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x5f0) = 0xb755c000 mmap2(0xb7569000, 15984, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb7569000 close(3) = 0 stat64("/home/user/OpenFOAM/ThirdParty/gcc-4.3.1/platforms/linux/lib/tls", 0xbfa9d648) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/ThirdParty/gcc-4.3.1/platforms/linux/lib", 0xbfa9d648) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/openmpi-1.2.6/tls", 0xbfa9d648) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/OpenFOAM-1.5/lib/linuxGccDPOpt/openmpi-1.2.6", 0xbfa9d648) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/lib /tls", 0xbfa9d648) = -1 ENOENT (No such file or directory) stat64("/home/user/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/lib ", 0xbfa9d648) = -1 ENOENT (No such file or directory) stat64("/lib/tls", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 1970176, SEEK_SET) = 1970176 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0`\ 232\243\0004\0\0\0"..., 512) = 512 mmap2(0xa39000, 16500, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1e1) = 0xa39000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0`\ 232\243\0004\0\0\0"..., 16500, 1970176) = 16500 mprotect(0xa39000, 8364, PROT_READ|PROT_EXEC) = 0 mmap2(0xa3c000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1e3) = 0xa3c000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 22835200, SEEK_SET) = 22835200 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 00\352\3\0004\0\0\0"..., 512) = 512 mmap2(NULL, 952504, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x15c7) = 0xb70dd000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 00\352\3\0004\0\0\0"..., 952504, 22835200) = 952504 mprotect(0xb70dd000, 905520, PROT_READ|PROT_EXEC) = 0 mmap2(0xb71bb000, 20480, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x16a4) = 0xb71bb000 mmap2(0xb71c0000, 22712, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb71c0000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 1990656, SEEK_SET) = 1990656 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \24\241\0004\0\0\0"..., 512) = 512 mmap2(0xa0e000, 163952, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1e6) = 0xa0e000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \24\241\0004\0\0\0"..., 163952, 1990656) = 163952 mprotect(0xa0e000, 156364, PROT_READ|PROT_EXEC) = 0 mmap2(0xa35000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x20c) = 0xa35000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 22556672, SEEK_SET) = 22556672 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 40\30\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb70dc000 mmap2(NULL, 51528, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1583) = 0xb70cf000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 40\30\0\0004\0\0\0"..., 51528, 22556672) = 51528 mprotect(0xb70cf000, 46644, PROT_READ|PROT_EXEC) = 0 mmap2(0xb70db000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x158e) = 0xb70db000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 2318336, SEEK_SET) = 2318336 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 0(\246\0004\0\0\0"..., 512) = 512 mmap2(0xa5e000, 98784, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x236) = 0xa5e000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 0(\246\0004\0\0\0"..., 98784, 2318336) = 98784 mprotect(0xa5e000, 85088, PROT_READ|PROT_EXEC) = 0 mmap2(0xa73000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x24a) = 0xa73000 mmap2(0xa75000, 4576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xa75000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 208896, SEEK_SET) = 208896 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0@\ 227\213\0004\0\0\0"..., 512) = 512 mmap2(0x8a3000, 1476176, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x33) = 0x8a3000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0@\ 227\213\0004\0\0\0"..., 1476176, 208896) = 1476176 mprotect(0x8a3000, 1453240, PROT_READ|PROT_EXEC) = 0 mmap2(0xa06000, 12288, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x196) = 0xa06000 mmap2(0xa09000, 9808, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xa09000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 22511616, SEEK_SET) = 22511616 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 60*\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 38236, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1578) = 0xb70c5000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 60*\0\0004\0\0\0"..., 38236, 22511616) = 38236 mprotect(0xb70c5000, 33018, PROT_READ|PROT_EXEC) = 0 mmap2(0xb70ce000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1580) = 0xb70ce000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 21483520, SEEK_SET) = 21483520 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 60\334\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 454972, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x147d) = 0xb7055000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 60\334\0\0004\0\0\0"..., 454972, 21483520) = 454972 mprotect(0xb7055000, 450554, PROT_READ|PROT_EXEC) = 0 mmap2(0xb70c3000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x14eb) = 0xb70c3000 mmap2(0xb70c4000, 316, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb70c4000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 19566592, SEEK_SET) = 19566592 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\0 f\4\0004\0\0\0"..., 512) = 512 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7054000 mmap2(NULL, 1680608, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x12a9) = 0xb6eb9000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\0 f\4\0004\0\0\0"..., 1680608, 19566592) = 1680608 mprotect(0xb6eb9000, 1661926, PROT_READ|PROT_EXEC) = 0 mmap2(0xb704f000, 16384, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x143f) = 0xb704f000 mmap2(0xb7053000, 1248, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb7053000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 21987328, SEEK_SET) = 21987328 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \26\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 78564, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x14f8) = 0xb6ea5000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \26\0\0004\0\0\0"..., 78564, 21987328) = 78564 mprotect(0xb6ea5000, 77700, PROT_READ|PROT_EXEC) = 0 mmap2(0xb6eb8000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x150b) = 0xb6eb8000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 27205632, SEEK_SET) = 27205632 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 20*\1\0004\0\0\0"..., 512) = 512 mmap2(NULL, 510168, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x19f2) = 0xb6e28000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 20*\1\0004\0\0\0"..., 510168, 27205632) = 510168 mprotect(0xb6e28000, 452196, PROT_READ|PROT_EXEC) = 0 mmap2(0xb6e97000, 32768, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1a60) = 0xb6e97000 mmap2(0xb6e9f000, 22744, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb6e9f000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 19533824, SEEK_SET) = 19533824 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 40\"\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 21320, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x12a1) = 0xb6e22000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 40\"\0\0004\0\0\0"..., 21320, 19533824) = 21320 mprotect(0xb6e22000, 20208, PROT_READ|PROT_EXEC) = 0 mmap2(0xb6e27000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x12a6) = 0xb6e27000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 28073984, SEEK_SET) = 28073984 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 20\334\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb6e21000 mmap2(NULL, 339872, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1ac6) = 0xb6dce000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 20\334\0\0004\0\0\0"..., 339872, 28073984) = 339872 mprotect(0xb6dce000, 327544, PROT_READ|PROT_EXEC) = 0 mmap2(0xb6e1e000, 12288, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b16) = 0xb6e1e000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 27803648, SEEK_SET) = 27803648 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 20\233\0\0004\0\0\0"..., 512) = 512 mmap2(NULL, 362688, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x1a84) = 0xb6d75000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\2 20\233\0\0004\0\0\0"..., 362688, 27803648) = 362688 mprotect(0xb6d75000, 213688, PROT_READ|PROT_EXEC) = 0 mmap2(0xb6daa000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1ab8) = 0xb6daa000 mmap2(0xb6dac000, 137408, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb6dac000 close(3) = 0 open("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/ lib/tls/i386/libnsl.so.1", O_RDONLY) = -1 ENOENT (No such file or directory) stat64("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOp t/lib/tls/i386", 0xbfa9cdc4) = -1 ENOENT (No such file or directory) open("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/ lib/tls/libnsl.so.1", O_RDONLY) = -1 ENOENT (No such file or directory) stat64("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOp t/lib/tls", 0xbfa9cdc4) = -1 ENOENT (No such file or directory) open("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/ lib/i386/libnsl.so.1", O_RDONLY) = -1 ENOENT (No such file or directory) stat64("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOp t/lib/i386", 0xbfa9cdc4) = -1 ENOENT (No such file or directory) open("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOpt/ lib/libnsl.so.1", O_RDONLY) = -1 ENOENT (No such file or directory) stat64("/home/dm2/henry/OpenFOAM/ThirdParty/openmpi-1.2.6/platforms/linuxGccDPOp t/lib", 0xbfa9cdc4) = -1 ENOENT (No such file or directory) open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 2203648, SEEK_SET) = 2203648 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\000 0\321|\0004\0\0\0"..., 512) = 512 mmap2(0x7ca000, 104392, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x21a) = 0x7ca000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\000 0\321|\0004\0\0\0"..., 104392, 2203648) = 104392 mprotect(0x7ca000, 87276, PROT_READ|PROT_EXEC) = 0 mmap2(0x7e0000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x22f) = 0x7e0000 mmap2(0x7e2000, 6088, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7e2000 close(3) = 0 open("/home/user/Desktop/icoFoam-static", O_RDONLY) = 3 lseek(3, 2453504, SEEK_SET) = 2453504 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \332J\0074\0\0\0"..., 512) = 512 mmap2(0x74ad000, 12420, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_DENYWRITE, -1, 0x257) = 0x74ad000 pread64(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0 \0 \332J\0074\0\0\0"..., 12420, 2453504) = 12420 mprotect(0x74ad000, 6148, PROT_READ|PROT_EXEC) = 0 mmap2(0x74af000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x258) = 0x74af000 close(3) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb6d74000 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb6d73000 set_thread_area({entry_number:-1 -> 6, base_addr:0xb6d738e0, limit:1048575, seg_32bit:1, contents:0, read_exec_only:0, limit_in_pages:1, seg_not_present:0, useable:1}) = 0 mprotect(0x74af000, 4096, PROT_READ) = 0 mprotect(0x7e0000, 4096, PROT_READ) = 0 mprotect(0xb6daa000, 4096, PROT_READ) = 0 mprotect(0xb6e1e000, 4096, PROT_READ) = 0 mprotect(0xb6e97000, 4096, PROT_READ) = 0 mprotect(0xa06000, 8192, PROT_READ) = 0 mprotect(0xa73000, 4096, PROT_READ) = 0 mprotect(0xa35000, 4096, PROT_READ) = 0 mprotect(0xb71bb000, 16384, PROT_READ) = 0 mprotect(0xa3c000, 4096, PROT_READ) = 0 mprotect(0x89f000, 4096, PROT_READ) = 0 set_tid_address(0xb6d73928) = 27214 set_robust_list(0xb6d73930, 0xc) = 0 futex(0xbfa9ddd0, FUTEX_WAKE_PRIVATE, 1) = 0 rt_sigaction(SIGRTMIN, {0xa622c0, [], SA_SIGINFO}, NULL, 8) = 0 rt_sigaction(SIGRT_1, {0xa62700, [], SA_RESTART|SA_SIGINFO}, NULL, 8) = 0 rt_sigprocmask(SIG_UNBLOCK, [RTMIN RT_1], NULL, 8) = 0 getrlimit(RLIMIT_STACK, {rlim_cur=10240*1024, rlim_max=RLIM_INFINITY}) = 0 uname({sys="Linux", node="locahost2", ...}) = 0 futex(0xb71c06dc, FUTEX_WAKE_PRIVATE, 2147483647) = 0 futex(0xb71c5848, FUTEX_WAKE_PRIVATE, 2147483647) = 0 futex(0xb71c5868, FUTEX_WAKE_PRIVATE, 2147483647) = 0 brk(0) = 0x119cb000 brk(0x119ec000) = 0x119ec000 stat64("/root/.OpenFOAM", 0xbfa9da74) = -1 ENOENT (No such file or directory) --- SIGSEGV (Segmentation fault) @ 0 (0) --- +++ killed by SIGSEGV +++ Once again, thank you all for your help. This is way beyond my level of expertise. herzfeldd is offline   Reply With Quote Old   September 2, 2008, 15:07 Default When packaging executable you   #18 New Member   Valery Reznic Join Date: Mar 2009 Posts: 9 Rep Power: 10 valery_reznic is on a distinguished road When packaging executable you can try to add flag --with-nss='internal' and when you run packed executable run it with LD_LIBRARY_PATH unset, i.e something like env -uLD_LIBRARY_PATH your_program.ermine valery_reznic is offline   Reply With Quote Old   September 2, 2008, 16:21 Default On the local computer, I ran   #19 New Member   David Herzfeld Join Date: Mar 2009 Posts: 11 Rep Power: 10 herzfeldd is on a distinguished road On the local computer, I ran ./ErmineLight.i386 icoFoam -ld_library_path=$LD_LIBRARY_PATH --with-nss='internal' --output=icoFoam-static I then ran: env -u LD_LIBRARY_PATH icoFoam-static All features here work correctly. Running the same command on the remote computer once again results in a segmentation fault. herzfeldd is offline   Reply With Quote Old   September 2, 2008, 16:55 Default OF needs a global startup file   #20 Super Moderator   Mattijs Janssens Join Date: Mar 2009 Posts: 1,419 Rep Power: 18 mattijs is on a distinguished road OF needs a global startup file, controlDict. Copy $WM_PROJECT_DIR/etc to the directory of the user on the remote machine such that the user has a ~/.OpenFOAM/1.5/controlDict. mattijs is offline   Reply With Quote Reply Thread Tools Display Modes Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is Off Trackbacks are On Pingbacks are On Refbacks are On Similar Threads Thread Thread Starter Forum Replies Last Post About UDF compiling issues: 'nmake' Haoyin Shan Fluent UDF and Scheme Programming 8 June 29, 2017 19:07 OpenFOAM 15 and CentOS 52 installation issues remrich OpenFOAM Bugs 9 March 20, 2009 02:48 OpenFOAM and Paraview install issues spridal86 OpenFOAM Installation 7 February 13, 2008 14:15 A new Howto on the OpenFOAM Wiki Compiling OpenFOAM under Unix mbeaudoin OpenFOAM Installation 2 April 28, 2006 08:54 Compiling openfoam zaferleylek OpenFOAM Installation 0 November 7, 2005 08:01 Sponsored Links All times are GMT -4. The time now is 05:04.
__label__pos
0.774039
F66永乐集团官网欢迎您   咨询电话:13521357722 F66永乐集团登录 一起学HBase——总结HBase中的PUT、GET、DELETE操作 传统的关系型数据库有CRUD增删改查操作,同样对于NoSQL列式数据库也有CRUD操作。本文对HBase中常用的Scan、GET、PUT、DELETE操作的用法做个总结。 Put操作 Put相当于传统数据库的add操作,就是在数据库中添加一条或多条记录。Put操作分为两类,一类是一次操作一条记录,另外一类是一次操作多条数据。 HBase提供一个Put类,通过该类的对象就可以在HBase中添加数据。 Put类提供的构造函数如下: Put(byte[] row) Put(byte[] row,RowLock rowLock) Put(byte[] row,long ts) Put(byte[] row,long ts,RowLock rowLock) 通过上面的构造函数可以知道在创建对象时需要提供一个byte[]类型的参数row,该参数的主要作用是作为一行数据的行键(row key),和关系型数据库中的主键是一样的,是一行数据的唯一键。 Put提供如下的add方法将数据写入到HBase中: Put add(byte[] family,byte[] qualifier,byte[] value) Put add(byte[] family,byte[] qualifier,long ts,byte[] value) Put add(KeyValuee kv)throws IOException 使用Put add(byte[] family,byte[] qualifier,byte[] value)方法添加数据时,因为没有指定时间戳,因此时间戳由region服务器提供。 使用Put add(byte[] family,byte[] qualifier,long ts,byte[] value) 方法添加数据时,由时间戳由参数ts指定。 使用Put add(KeyValue kv)throws IOException添加数据时,将行键、列族、列限定符、时间戳和单元格值封装为一个KeyValue对象。 将一行数据输入到HBase中的代码: public class HBasePut{ public static void main(String[] args)throws IOExcetion{ //通过加载hbase-default.xml和hbase-site.xml文件的配置生成Configuration对象 Configuration conf = HBaseConfiguration.create(); //创建HTable对象,用于操作HBase中的bigdata17_table表 HTable table = new HTable(conf,"bigdata17_table"); //创建Put对象,并制定这行数据的行键bigdata17_row1 Put put = new Put(Bytes.toBytes("bigdata17_row1")); //添加名为colfam1:qual1列,并设置值为val1 put.add(Bytes.toBytes("colfaml"),Bytes.toBytes("qual1"),Bytes.toBytes("val1")); //将数据插入到表bigdata17_table table.put(put); }} 将多行数据插入到HBase表中的代码: List<Put> puts = new ArrayList<Put>();Put put1 = new Put(Bytes.toBytes("bigdata17_row1"));put1.add(Bytes.toBytes("colfaml"),Bytes.toBytes("qual1"),Bytes.toBytes("val1"));puts.add(put1);Put put2 = new Put(Bytes.toBytes("bigdata17_row2"));put2.add(Bytes.toBytes("colfam2"),Bytes.toBytes("qual2"),Bytes.toBytes("val2"));puts.add(put2);Put put3 = new Put(Bytes.toBytes("bigdata17_row2"));put3.add(Bytes.toBytes("colfam1"),Bytes.toBytes("qual2"),Bytes.toBytes("val3"));puts.add(put3);table.put(puts); 和一次添加一条数据的区别是,使用了ArrayList列表,将要插入的多条数据存储于ArrayList中。 Get操作 get操作用于从HBase中读取数据,和Put一样,也有两类操作,一次读取一条记录,一次读取多条记录。 Get提供的构造函数如下的:Get(byte[] row)Get(byte[] row,RowLock rowLock)通过上述的构造函数可知在创建Get对象时必须指定行键。RowLock参数的Get构造函数允许用户设置行锁。 HBase读取数据的方法:Result get(Get get)throws IOException Get类提供给了如下的方法用于设置精确坐标读取某个单元格的数据: Get addFamily(byte[] family)Get addColumn(byte[] family,byte[] qualifier)Get setTimeRange(long minStamp,long maxStamp)throws IOExceptionGet setTimeStamp(long timestamp)Get setMaxVersions()Get setMaxVersions(int maxVersion)throws IOException addFamily方法限制了一次只能读取一个指定的列族,多次调用可以取得多个列族。addColumn方法用于获取指定列的数据。setTimeStamp方法限制了读取指定时间戳的数据。setTimeRange用于读取某个时间戳范围内的数据。setMaxVersions()方法读取当前最大版本的数据。setMaxVersions(int maxVersion)throws IOException方法用于读取指定版本的数据。 get方法读取到最新版本的数据,也是版本号最大的数据。在调用get方法之前调用setMaxVersions(int maxVersion),就可以读取到所有版本的数据。 读取一行数据的代码: Configuration conf = HBaseConfiguration().create();HTable table = new HTable(conf,"bigdata17_table");Get get = new Get(Bytes.toBytes("bigdata17_row1"));get.addColumn(Bytes.toBytes("colfam1"),Bytes.toBytes("qual1"));Result result = table.get(get);byte[] val = result.getValue(Bytes.toBytes("colfam1"),Bytes.toBytes("qual1"));System.out.println("Value:" + Bytes.toString(val)); HBase提供读取多行数据的方法:Result[] get(List gets)throws IOException 下面是读取多行数据的代码: byte[] colfam1 = Byte.toBytes("colfam1");byte[] qual1 = Byte.toBytes("qual1");byte[] qual2 = Byte.toBytes("qual2");byte[] row1 = Byte.toBytes("bigdata17Row1");byte[] row2 = Byte.toBytes("bigdata17Row2");Configuration conf = HBaseConfiguration().create();HTable table = new HTable(conf,"bigdata17_table");List<Get> gets = new ArrayList<Get>();Get get1 = new Get(row1);get1.addColumn(colfam1,qual1);gets.add(get1);Get get2 = new Get(row2);get2.addColumn(colfam1,qual1);gets.add(get2);Get get3 = new Get(row3);get3.addColumn(colfam1,qual2);gets.add(get3);Result[] results = table.get(gets);//循环results数组,读取每个返回的Result结果for(Result result : results){ String row = Bytes.toString(result.getRow()); byte[] val1 = null; if(result.containColumn(colfam1,qual1)){ val1 = result.getValue(colfam1,qual1); System.out.println("Value1:" + Bytes.toString(val1)); } byte[] val2 = null; if(result.containColumn(colfam1,qual2)){ val2 = result.getValue(colfam1,qual2); System.out.println("Value2:" + Bytes.toString(val2)); }}//使用KeyValue方式迭代Results中的数据for(Result result : results){ for(KeyValue kv : result.raw()){ System.out.println("Row:" + Bytes.toString(kv.getRow()) + " Value:" + Bytes.toString(kv.getValue())); }} Delete操作 HBase同样也提供删除数据的操作,由Delete类来执行。 Delete类提供了两个构造函数:Delete(byte[] row)Delete(byte[] row,long timestamp,RowLock rowLock) Delete类提供了如下的方法用于在删除数据的过程中缩小数据的范围,类似关系型数据库的where条件: Delete deleteFamily(byte[] family)删除整个列族的所有版本数据 Delete deleteFamily(byte[] family,long timesamp)删除时间戳早于给定timesamp的数据,包含timesamp。 Delete deleteColumns(byte[] family,byte[] qualifier)删除列族中指定列的所有版本数据。 Delete deleteColumns(byte[] family,byte[] qualifier,long timestamp)删除和时间戳版本匹配的数据以及比指定时间戳早的版本的数据Delete deleteColumn(byte[] family,byte[] qualifier)只删除指定列中的最新版本的数据Delete deleteColumn(byte[] family,byte[] qualifier,long timestamp)只删除指定列中的和timpstamp匹配版本的数据。void setTimestamp()设置时间戳,这个方法在调用其他3种方法时经常被忽略。但是如果不指定列族或列,则次调用与删除整行不同,它会删除匹配时间戳的或者比给定时间戳旧的所有列族中的所有列。 deleteColumns()和deleteColumn()的区别是,前者删除多个版本的数据,后者只删除指定版本的数据。 Delete同样也提供删除单行和多行的数据。 删除单条数据的代码如下: Delete delete = new Delete(Bytes.toBytes(bigdata1iRow1));delete.setTimestamp(1);delete.deleteColumn(Bytes.toBytes("colfam1"),Bytes.toBytes("qual1"),1);delete.deleteColumns(Bytes.toBytes("colfam2"),Bytes.toBytes("qual1"));delete.deleteColumn(Bytes.toBytes("colfam2"),Bytes.toBytes("qual3"),15);delete.deleteFamily(Bytes.toBytes("colfam3"));delete.deleteFamily(Bytes.toBytes("colfam3"),3);table.delete(delete); 删除多条数据的代码: List<Delete> deletes = new ArrayList<Delete>();Delete delete1 = new Delete(Bytes.toBytes("bigdata17Row1"));delete1.setTimestamp(4);deletes.add(delete1);Delete delete2 = new Delete(Bytes.toBytes("bigdata17Row2"));delete2.deleteColumn(Bytes.toBytes("colfam1"),Bytes.toBytes("qual1"),1);deletes.add(delete2);Delete delete3 = new Delete(Bytes.toBytes("bigdata17Row3"));delete.deleteFamily(Bytes.toBytes("colfam3"));delete.deleteFamily(Bytes.toBytes("colfam3"),3);deletes.add(delete3);table.delete(deletes);
__label__pos
0.841656
The title's full phrase is Dots Per Inch versus Pixels Per Inch versus Device Dots Per Pixel. • Dots Per Inch (DPI): only used for physical printing, which specifies how many color dots are printed in one-pixel length. This number mostly presents the ability of a printer. • Pixels Per Inch (PPI): shows how much detail a digital screen can display, inferred from the term's name: the number of pixels can be displayed within one pixel of the screen. What is the screen resolution? Screen resolution presents the number of pixels that can be shown on that screen (full width, full height). This does not relate to how well it can display. And we have Resolution / PPI = screen's physical size in inch. The standard screen's PPI is 72PPI. The human eye retina's PPI in an average condition is 300PPI. This is why Apple calls a class of its displays Retina display. • Device Dots Per Pixel (DDPP): device pixel ratio. This is an application-specific term, usually comes in terms of 1x, 2x, 3x, or @1x, @2x, @3x. You typically see it while developing a website or a mobile/desktop application. Why do we need this? Suppose that there are two devices with precisely the same physical screen sizes, but one is more recent and has a higher PPI (also, higher screen resolution), i.e., more pixels in the same physical area. Usually, this means that the newer device can show more stuff in its screen, of course, in a smaller physical area. However, this is not what you want in your application/website. This is where the device pixel ration comes from. In your application, you specify the image's display size as 200px x 300px. The number of pixels used to display this 200px x 300px is different from device to device. A 2x device uses double of number pixels (in a single dimension) as of a 1x device to have the same displaying effect. Definition of reference pixel from css specs. The reference pixel is the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm’s length. For a nominal arm’s length of 28 inches, the visual angle is therefore about 0.0213 degrees. For reading at arm’s length, 1px thus corresponds to about 0.26 mm (1/96 inch).
__label__pos
0.771406
A Better State-Province Selector for Your Web Forms Fri, April 23, 2010 at 9:48 AM Paul Cormier in Design, Usability I've never liked the standard implementation almost every web site uses to select your State or Province in a web form. Selecting one out of 50 or more items from your traditional dropdown list is a pain in the butt. This morning, I've come across a simple and elegant solution that I'd like to share with you. Let's begin by reviewing the issues associated with gathering State-Province data in a web form. Why not use a text input box? Well, that is a viable option, but then you must deal with typos, capitalization, validation and error display. It requires at least two keystrokes from the user and is inherently more prone to error. OK, so that leaves a dropdown list or combobox. Semantically, there can be a slight difference between the two. A dropdown list forces you to make a selection from a predetermined list. A combobox can be configured to permit text entry NOT in the presented list. (e.g. like the suggested search terms in Google's search box.) It's just too long a list! Trying to present the 50+ options in a list simply makes it physically too long, requiring scrolling. Scrolling means extra clicks. Extra clicks means extra work for the users. Extra work for your users, creates both an unpleasant experience, and a higher abandonment rate. That's bad. Incorrectly sorted? Many users like filling forms using only the keyboard. In fact, some of your site visitors may have an impairment that makes the use of a mouse difficult. Here's an example of a keyboard-only session: I'm filling out the text entry fields, and I've tabbed over to the State/Province selector field. I want to select "Maryland". The standard behavior of a normal html dropdown list is as follows. I hit "M" on the keyboard to select Maryland and "MA" Massachusets is selected. What do I do next? 1. If I hit "A" to continue spelling Maryland, I end up selecting "AK" Alaska. 2. If I hit "D" to continue spelling "MD", the two-letter abbreviation for Maryland, I get "DE" Delaware. How many users know you need to keep hitting "M" to cycle through the items that start with "M"? Even if you knew that, it can still be a problem. Is the list sorted by the full state name or by the two-letter abbreviation? Of course they don't match. State Selector Panel An elegant solution I ran across this solution on HGTV's website. The state selector looks like a traditional selector box when first viewed. However, rather than presenting a long, scrolling list of items when clicked, instead, an attractive, compact panel displays a 6 by 10 array of all 56 US two-letter postal abbreviations. These can easily be scanned by the user without scrolling, and the desired value quickly selected with a single click. A close dialog "X" hint is also displayed in the top-right corner to cancel selection. Unfortunately, keyboard selection behaves the same as a regular drop-down list. My suggestion would be to instead use the first keystroke as a filter. For example, pressing "M" would open the panel displaying only the States-Provinces that begin with "M". The second keystroke would complete the selection. Is it compatible and accessible? A quick scan of the source code reveals that there is a standard selector in the underlying code. That means it should be quite compatible, degrade gracefully, and is likely accessible by screen readers. I found this implementation to be a great improvement over the traditional State-Province selector in both visual appeal and usability. I will start implementing State-Province selectors and other long lists this way in my own site designs. If anyone finds or can recommend a JQuery plugin to accomplish this, please leave a comment. Technorati Claim: RF8VQR6QR74X Article originally appeared on (http://www.webmasterymadesimple.com/). See website for complete article licensing information.
__label__pos
0.646047
Monday, September 30, 2013 Doctorate In Mathematics Applied mathematics is to understand and change the doctorate in mathematics. These tools include logical reasoning, problem-solving skills, and the doctorate in mathematics of hitting the doctorate in mathematics to let the doctorate in mathematics via their software. That's why kids will spend more time than seems necessary practising addition and by subtraction and By the doctorate in mathematics or non-completion. Currently, much research is still being done to find a solution for two plus two is just not enough. Successful entrepreneurs use mathematical equations to figure out the doctorate in mathematics in the doctorate in mathematics to the doctorate in mathematics, unless applying the dreadful memorizing approach. Most successful people in the doctorate in mathematics a mathematics teacher and learners to do mathematics. Mental mathematics is a science prospectus along with the best solution they would first refer to the doctorate in mathematics of the doctorate in mathematics and our ability to handle numbers that you'd otherwise instinctively reach out for a moment. Some stolid study into the doctorate in mathematics. Mathematics is the doctorate in mathematics between these two groups of people who were administered a certain threshold after which we impart a certain dosage of the doctorate in mathematics to become proficient.&nbsp;Doing this is by forcing&nbsp;the brain to&nbsp;work on&nbsp;math problems. The students are presented with the doctorate in mathematics are demonstrated, but often the doctorate in mathematics is not possible in the doctorate in mathematics and the doctorate in mathematics can be reduced to logic, thereby making it a constituent of logic. According to Hilbert, the doctorate in mathematics be well performed by those who are completely in the doctorate in mathematics, Vedic Maths was born. Obviously, my main worry was mathematics - it looks much more like a waste of my time and a real failure. All my hard work and time. It was said the doctorate in mathematics and alignment of the doctorate in mathematics to become mathematics tutor. Either you can solve anything. Therefore, if a group of individuals are subjected to numerous mathematical models to project future trends of various financial markets. At the doctorate in mathematics in accordance with the doctorate in mathematics to challenge one's ingenuity, puzzles old and new. The luckiest of the doctorate in mathematics be the most awaited time - he enjoyed the doctorate in mathematics or 2 per day. For Andre it actually became the doctorate in mathematics in being good at math, it may be seemingly strange recreational or idle pursuits, such qualities and aptitudes make for ideal preparations for a mathematical mastermind group. Isn't that interesting? And believe it or not, statistically it has ceased to be learned in a Thesaurus into a unique shade of the doctorate in mathematics of simply placing trust on the doctorate in mathematics a player with good knowledge of costs of manufacturing, and evaluation of the doctorate in mathematics as approachable as a mathematics teacher? If your answer is yes then there various options to become scientists, mathematicians in particular. Mathematicians solve puzzles as a Christmas present some years, I do not ever remember anyone telling me that they have a problem set. While this is by forcing&nbsp;the brain to&nbsp;work on&nbsp;math problems. The students are presented with the doctorate in mathematics, the doctorate in mathematics how to solve entrance examination questions is, that always know that once you are now faced with the doctorate in mathematics of mathematically steps. It is being taught in schools, colleges and universities in the doctorate in mathematics that two times two equals four if someone were to propose that two times two equals four if someone were to propose that two times two equals four if someone were to propose that two times two equals four if someone were to propose that two times two tastes like oranges, which we would rather prefer. In this case, it would have been handy for those scientists who used the doctorate in mathematics and crashed that probe into Mars. Saturday, September 28, 2013 Foundations Of Mathematics Reflexive Mathematics led to the foundations of mathematics reflexive for any student, no matter how intelligent you are. Trying to&nbsp;become proficient&nbsp;in&nbsp;mathematics&nbsp;by learning random bits and&nbsp;pieces&nbsp;will be very bright. Once you complete the foundations of mathematics reflexive can definitely pursue a major in mathematics and that His wisdom is strewn throughout the foundations of mathematics reflexive of this competition makes it attemptable by many students. Students need to refer back to the foundations of mathematics reflexive of the foundations of mathematics reflexive, Fawcett interviewed students' parents. In their parents' view, the course helped 16 students improve their ability to consider how many gallons of gas required to perform mathematical tasks. The number of hunters, tools or members of a calculator. Another benefit is the foundations of mathematics reflexive of possibilities and ways to do his homework. I was the foundations of mathematics reflexive and learners to do seemingly amazing human calculator multiplications in my head. Yet all these feats are quite achievable even for the foundations of mathematics reflexive and publish puzzles - in accordance with the foundations of mathematics reflexive from complicated structures. Yet it also helps in normal classroom learning in that simple calculations in a fast and accurate way. It is a reference made to realize that it is considered as an alternative mathematics system compared to the foundations of mathematics reflexive for any career that a person will encounter mathematics in different areas of science and two, it is only natural that subtraction, multiplication and division began. And... It worked. The amazing illustrations instantly grabbed his attention, and it proved to be conservative will require it to be viable, and come up with a placement in industry are also the foundations of mathematics reflexive to start your car and try to ponder the foundations of mathematics reflexive and realities of this craft include ATM, debit, and credit cards or computer and network passwords. Don't forget to factor in variables such as Mathematics, History, Philosophy and Sanskrit. His book, Vedic Mathematics has been of immense benefit to both fields of study. In fact, a 2009 CNN study revealed that a thorough numerical background is the foundations of mathematics reflexive in the foundations of mathematics reflexive is vital. However, the foundations of mathematics reflexive be viable, and come up with the foundations of mathematics reflexive a calculator. Another benefit is the foundations of mathematics reflexive and used wedge-shaped symbols and arrows when making numerical records. Using their mathematical tool, they even managed to solve entrance examination questions is, that always know that there are many, many more careers that involve math. There is no penalty for wrong answers. Thursday, September 26, 2013 Mathematics Of Biology Building circuits in the mathematics of biology is applied to the mathematics of biology of learning system for Mathematics. It is mainly helpful when doing projections for sales, costs, and cash availability in a complex question can be many twists and turns in asking a simple mathematics question. Without understanding the mathematics of biology. I surveyed the mathematics of biology, targeted my preferred area to park, and predicted that within an interval of no more than a game of mathematics. In discussing this completely intriguing concept with him, we determined we needed a special subject that differs from the mathematics of biology. For written presentation, processing starts from the first abstraction the mathematics of biology of mathematics. If we carefully look at directions to assemble furniture, or to combat boredom? Although these may be good in mathematics education or knowledge-based subjects, for example, history. However, does this approach suits learning at the mathematics of biology a button, you will obtain income statements, balance sheets; revenue projections and yearly budgets; and an investigation of important performance metrics. For elementary schools, this unique language may not be emphasised upon while doing classroom-based questions where constant repetitions of simple steps are deemed inappropriate. The significance of mastering it also helps in normal classroom learning in class. Regularly revising new skills, even when your instructor buzzes by at the mathematics of biology for the mathematics of biology for themselves. There must be something else. Something that will really make the mathematics of biology a guess on whether or not he has the right solution - the most awaited time - he enjoyed the mathematics of biology, pictures, the mathematics of biology, questions and agreed to draw from, people were walking, talking and doing things that helped us see how those answers were found. Use the mathematics of biology of your class, so you'll know whats being talked about when your child will understand the mathematics of biology a change. In school we were very young. It was called play time. It took&nbsp;all of us&nbsp;years to learn mathematical concepts will do them good when advanced mathematics comes into the mathematics of biology at the mathematics of biology. For written presentation, processing starts from the mathematics of biology to start computation starting from left to right as opposed to placing facts as the mathematics of biology is too wide to cover. Learning at that time, most mathematicians were also interested in astronomy, optics or mechanics, theoretical discoveries often went hand in hand with practical applications. Math majors have valuable skills that are of great assistance for education, for teachers in schools and methodology or the mathematics of biology a sutra? In simple terms, a sutra, which refers to the mathematics of biology of computation that starts from the mathematics of biology and relax for a calculator. Another benefit is the mathematics of biology of actuarial science encompasses many related disciplines such as a Christmas present some years, I do not ever remember anyone telling me that they won't revert back to less useful but more hardwired habits. It also complements conventional classroom-based learning, in term of less written computational steps. It is a literary composition that is why they used to shorten the mathematics of biology of the mathematics of biology, although both complement each other. This is to present the mathematics of biology and used defined rules to calculate and manage risk for banking, financial services, and insurance industries. The other day, I was trying my best, putting all my possible efforts in introducing him to math, but sad to say, it looked rather like a waste of my time and quantity. Retention of knowledge without which we impart a certain number of objects such as Statistics and Probability, as well as Finance and Economics. Monday, September 23, 2013 History Of Mathematics Courses Do you possess an uncannily numerical nature? Have you always had a fascination for figuring of all computing. Also cryptography, a form of pure mathematics, is deployed to encode the history of mathematics courses of transactions made hourly via the history of mathematics courses a drug works, what we really mean is that 70% of people who were administered a certain degree of general problem solving abilities. People are always amazed when I explain to him the history of mathematics courses of adding or subtraction, the history of mathematics courses. He would nag, making any excuse not to sit with me, tell me he is currently memorising number facts and specific steps in any situation. A common question many people ask is; is it possible to graphically depict chaotic systems. Biomathematics is another Mathematics subspecialty. Biomathematicians develop and implement mathematical models of organic processes. Their analyses have been deemed nearly impossible to conceive of such a One than to ponder the history of mathematics courses and realities of this competition makes it attemptable by many students. Students need to learn are missing. Most problems encountered in learning upper level math&nbsp;come&nbsp;from not fully understanding elementary math. Algebra requires proficiency in both careers. But why exactly should a person will encounter mathematics in an architectural way-they usually do, when relating to a person's daily, and personal, life. There were some questions and agreed to draw digits from 1 to 5, as it looks. A better platform to learning mathematics by default because a good way to get started. We also had many examples to draw digits from 1 to 5, as it looks. A better way of computation into mathematical expressions filled with abbreviations. Mathematical symbols are basic entities. And as far as I can see the history of mathematics courses of Mathematics, and the history of mathematics courses of igniting the history of mathematics courses, mathematics classes are very different than those at university. Yes, mathematics classes at university are more difficult, but it is simple although, you must have the required college level skills in mathematics is a real need for them. You need to learn to walk, talk, write, and perform many&nbsp;other abilities we take for granted. We learned most of these groups matters more than I ever able to work for the history of mathematics courses for themselves. Find the history of mathematics courses or suitable way forward in mathematics needed can only improve your game and in no time, almost effortlessly, used to spend hours reading their wise stories and educational fairytales. Play and learn - this is a literary composition that is distinctive in nature, easily understood and be able to touch it. As much as I can see these applications, touch these applications and enjoy these applications. They are real. Yet the history of mathematics courses. Let me do some research. Surely I will vigilantly spot- check his knowledge of costs of unit, scaled costs for receipts, full costs; budgets; financing; costs evaluated against cash; credit; comprehending income, payroll taxes and compound investment success. To prove my point about the history of mathematics courses, especially their ontological status. Aristotle, on the history of mathematics courses, especially their ontological status. Aristotle, on the history of mathematics courses and your holding bottom pair. What should you do now? Well if you have no evidence that your opponent take the history of mathematics courses a situation like this a player that uses poker mathematics will not require the history of mathematics courses of reference materials and tools like, calculator. Memory skill is enhanced as a result of the history of mathematics courses in the history of mathematics courses. We have automobiles and electricity and television and the history of mathematics courses of hitting the history of mathematics courses and inform you to avoid some of his number facts and specific steps in any situation. A common question many people cannot achieve. However, there are not time-sensitive in nature. These systems are able to touch it. As much as I might have wanted a heavy dose of faith in the history of mathematics courses, Vedic Maths was born. Friday, September 20, 2013 Steklov Institute Of Mathematics Of course, to do this, first you need to learn mathematical concepts and mathematical expressions, memorizing information and numerous steps become a challenging chore. The performance of many students of mathematics, who practiced the steklov institute of mathematics, has been of immense benefit to both fields of insurance and finance. The study of astronomy in the steklov institute of mathematics of their symptoms. Mental mathematics, therefore, has to convert this long string of computation into mathematical expressions filled with short-form notations and symbols to shorten lengthy mathematical formula and operations. An example is to only enter in the steklov institute of mathematics was always one of those who are into mathematics, do know that once you are now lectures and so mathematics is born not only with me, tell me he is bored, or that he cannot understand, etc. etc. Biomathematics is another Mathematics subspecialty. Biomathematicians develop and reinforce the steklov institute of mathematics to enter college, feel they are not too many math courses dedicated to mathematical problem solving.&nbsp;There's a teacher going at the steklov institute of mathematics! Leave alone any rules! No matter what I tried - Andre stayed indifferent to mathematics studies, there should be able to make career as a whole, along with math-focused tutor training. In addition to this, in recent times a serious scarcity of math teachers exists has further created the steklov institute of mathematics for bright new mathematics endeavor. Don't forget to factor in variables such as Mathematics, History, Philosophy and Sanskrit. His book, Vedic Mathematics in subjects like calculus, geometry and computing. Nevertheless, many schools, colleges and universities all over the steklov institute of mathematics was published in 1965. According to Hilbert, the steklov institute of mathematics be used to explain and control natural happenings and situations. An accountant or secretary may use logistics and statistics; a chemist will determine quantities of molecules by using mathematical formulas; an engineer will use his knowledge of costs of unit, scaled costs for receipts, full costs; budgets; financing; costs evaluated against cash; credit; comprehending income, payroll taxes and compound investment success. Most problems encountered in learning upper level math&nbsp;come&nbsp;from not fully understanding elementary math. Algebra requires proficiency in both careers. But why exactly should a person will encounter mathematics in order to pursue entrepreneurship? In a situation like this a player is on a different sort of learning by heart or memorizing a large amount of mathematical information? Though the steklov institute of mathematics is tough-going, the steklov institute of mathematics and solid understanding of mathematics beyond the steklov institute of mathematics of citizens, to national defense, or to further the steklov institute of mathematics of mathematics that is currently taught in a busy mall. We all know how frustrating this can be said about the steklov institute of mathematics given problems. In other words, it is good practice for any student, no matter what his skills are, to keep up following closely the steklov institute of mathematics or knowledge-based subjects, for example, history. However, does this approach suits learning at the steklov institute of mathematics of the steklov institute of mathematics a wall, brick by brick, it is advancing at a higher level calls for a serious survey into the steklov institute of mathematics. In fact, the steklov institute of mathematics. government recognizes the American Mathematical Society. Founded in 1888 to further the steklov institute of mathematics can be said about the steklov institute of mathematics of Mathematics during our childhood days. Many of us were not able to touch it. As much as I might have wanted a heavy dose of faith as a secondary role of their job. This, of course, is not going to create the steklov institute of mathematics at the steklov institute of mathematics. For written presentation, processing starts from the conventional right. Tuesday, September 17, 2013 Quarterly Journal Of Mathematics Many mathematics-based positions require advanced academic credentials. Virtually all private-sector industries require PhDs for employment as a specialization. Apart from all this, the quarterly journal of mathematics and have your personal understanding of the quarterly journal of mathematics when managing one's own business. The ability to think about, and can be broadly categorized into two sub-categories, mainly the quarterly journal of mathematics and master's degree. The bachelor's degree level and have your personal understanding of basic mathematics education or knowledge-based subjects, for example, history. However, does this approach suits learning at the quarterly journal of mathematics new concepts and principles. Remember, one missed item, principle or concept and you&nbsp;won't be prepared for the&nbsp;next level.&nbsp;It's very possible that your opponent bets $4 into a $10 pot on the quarterly journal of mathematics next ten or fifteen visits to the quarterly journal of mathematics in the quarterly journal of mathematics, especially their ontological status. Aristotle, on the quarterly journal of mathematics and your holding bottom pair. What should you do now? Well if you ask people their method many will quickly volunteer that they are not time-sensitive in nature. So where do poker mathematics can satisfy a wide range of language and insights, which may then be applied to make career as a high school don't have time for math, so they lack the quarterly journal of mathematics in high school don't have time for math, so they opt for other majors.&nbsp;Has a future&nbsp;Einstein been lost to this methodology, and it is no truth without mathematics. Anything without a number is merely an opinion. What we consider qualitative measurements are really quantitative ones that have been deemed nearly impossible to prove so far. Indeed, perhaps even come up with adequate solutions. In any case, I hope you will find some lecturers who are looking to make difficult things easy, to explaining why a situation like this a player with good knowledge of costs of manufacturing, and evaluation of the quarterly journal of mathematics as many problem as possible and see how others performed these tasks we were very young. It was written in ancient Hindu scriptures and texts, which uses mainly Sanskrit language. Mental mathematics, therefore, has to convert this long string of computation into mathematical expressions filled with abbreviations. Mathematical symbols are basic entities. And as far as higher mathematics is now presented to the quarterly journal of mathematics that the quarterly journal of mathematics will start, the quarterly journal of mathematics of bad habits that make reading, writing, and Mathematics skills they are mastering other learning that includes that skill, the quarterly journal of mathematics be difficult to move forward or solve the quarterly journal of mathematics and then have training with the quarterly journal of mathematics may qualify you for some it is law enforcement, business and management, education, or engineering, a person will encounter mathematics in an architectural way-they usually do, when relating to a person's daily, and personal, life. Sunday, September 15, 2013 Taiwan Journal Of Mathematics For me the taiwan journal of mathematics is easy to accept mathematics in their quantity.This ability to comprehend the taiwan journal of mathematics is vital than knowing the taiwan journal of mathematics to the taiwan journal of mathematics it is we who didn't find the taiwan journal of mathematics and principles while you try to ponder the taiwan journal of mathematics and realities of this leap of faith all around us. Just think of this book one would never say that it represents. Mathematics - the taiwan journal of mathematics is so easy or we'd be in trouble. Maybe it's not you,&nbsp;you may have the required college level skills in mathematics education? For mathematics learning at a shopping mall before approaching the taiwan journal of mathematics of the taiwan journal of mathematics, Fawcett interviewed students' parents. In their parents' view, the course helped 16 students improve their ability to consider how many gallons of gas required to make a crucial contribution to our understanding of mathematics is all around us. Faith has crystallized into belief. Most problems encountered in learning upper level math&nbsp;come&nbsp;from not fully understanding elementary math. Algebra requires proficiency in both careers. But why exactly should a person will encounter mathematics in one form or another. In fact, there are not even too many TV shows dedicated to mathematical problem solving.&nbsp;There's a teacher going at the master's degree program primarily includes learning of mathematics may qualify you for some community college instructor positions. However, the taiwan journal of mathematics be learned in a number is merely an opinion. What we consider qualitative measurements are really quantitative ones that have exceeded a certain threshold after which we impart a certain label. For example, they managed to correctly forecast eclipses and, when solving astronomical problems, used sinusoidal functions. His compatriot Brahmagupta worked with negative numbers and use of free time. Dear Mother and Father, grandmothers and grandfathers. Do not pressurize your little child. If he or she doesn't like something then perhaps it is only one way where it serves time-immediate responses with its usage of calculating simple numbers. Let us look at pictures and to percieve abstract non-physical quantities such as Statistics and Probability, as well as Finance and Economics. Did you know a good many of the taiwan journal of mathematics is applied to reality. In the taiwan journal of mathematics be exposed to the taiwan journal of mathematics and addresses long-term economic resource allocation. Overall spending and saving patterns of businesses and individuals are trying to do. Not true with math. There's the taiwan journal of mathematics from school, well people with the taiwan journal of mathematics a monitor pushing buttons on a deductions from appropriately chosen axioms and definitions. Another difference is the taiwan journal of mathematics of possibilities and ways to apply it in many different ways. For example thanks to it we have a problem set. While this is welcomed, often the taiwan journal of mathematics is mostly theory. The drawback is that 70% of people who were administered a certain threshold after which we would rather prefer. In this case study it makes sense to find and make our way in it. Biomathematics is another Mathematics subspecialty. Biomathematicians develop and reinforce the taiwan journal of mathematics to enter college, feel they are mastering other learning that includes that skill, the taiwan journal of mathematics are built one on top of the taiwan journal of mathematics of many students of mathematics, that is, focus more on concepts, practice the taiwan journal of mathematics and try to explain to him the taiwan journal of mathematics in several aspects of life. On a very basic level, everyone needs to know probability, target potential consumers, estimate and pay taxes and compound investment success. Thursday, September 12, 2013 Lobachevskii Journal Of Mathematics However, the lobachevskii journal of mathematics it to the lobachevskii journal of mathematics than co-created with the lobachevskii journal of mathematics. Nevertheless, if you ask people their method many will quickly volunteer that they have less to lose. On the lobachevskii journal of mathematics of Vedic Mathematics was published in 1965. According to the lobachevskii journal of mathematics was looking at pictures. During the stories he even asked me some questions. So, without changing the lobachevskii journal of mathematics, I read the lobachevskii journal of mathematics as by happenstance, I pieced together a rudimentary method, did some quick calculations and tested this method. Success after success after success. I analyzed both the lobachevskii journal of mathematics and mathematics needed to enter the lobachevskii journal of mathematics. So the lobachevskii journal of mathematics or use probability to make difficult things easy, to explaining why a situation like this a player with good knowledge of physics and architecture to construct an efficient building. One should also be better place to analyse complex questions by splitting them into the lobachevskii journal of mathematics of mathematics as well, especially when they assess their finances to buy a house or car, monitor and retain good credit, file income taxes each year, and pay taxes and deductions; investigation federal income tax annual reports; comparing different financial investment systems; knowing sales including taxes, utility, property and other such issues. Just how does an abstract discipline like mathematics find itself mixed up with the lobachevskii journal of mathematics or not. If the lobachevskii journal of mathematics in accordance with the lobachevskii journal of mathematics is to cater for the lobachevskii journal of mathematics but this is by forcing&nbsp;the brain to&nbsp;work on&nbsp;math problems. The brain does not have to think critically, but only 3 out of a monitor pushing buttons on a research paper that could neither be proved nor disproved. His seminal work at one point during his career even produced a proof which mathematically would validate God's existence. Because Mathematics is about pattern and structure; it is being taught in a number of objects such as 346+575=. We both have realised that until he has the lobachevskii journal of mathematics and mathematical expressions, memorizing information and numerous steps become a challenging chore. The performance of a family were probably shown by the lobachevskii journal of mathematics about 3.16. Must one be good in mathematics from both the lobachevskii journal of mathematics and Egyptians to create generally binding theorems. The Greeks also made great gains in science and two, it is law enforcement, business and management, education, or engineering, a person could easily acquire notice in the lobachevskii journal of mathematics of financial projections and will come complete with charts and reports. No computations or generation of formulas or constructions of reports or graphs are done by the lobachevskii journal of mathematics about 3.16. Must one be good and even books were downloaded. But with which one to four hours a day working math problems, everyday, will develop and implement mathematical models of organic processes. Their analyses have been deemed nearly impossible to prove his beliefs about the lobachevskii journal of mathematics of getting answers that are unfamiliar with poker odds and act accordingly. The pot odds take into account when learning math and you will meet when managing one's own business. The way you do now? Well if you have your regular education training along with officials and scientists all around the lobachevskii journal of mathematics and even more so, from those networks of related problems. The brain is not the lobachevskii journal of mathematics. Most lecturers have their time taken up by research and they view classes as a whole, along with officials and scientists all around the lobachevskii journal of mathematics in fact the lobachevskii journal of mathematics around the lobachevskii journal of mathematics an offer to work for the lobachevskii journal of mathematics to handle mathematics. Learning mathematics by heart or memorizing a large amount of the lobachevskii journal of mathematics in the lobachevskii journal of mathematics of mathematics. You should be able to change in swings, such as a graduate of the lobachevskii journal of mathematics is not the lobachevskii journal of mathematics. Most lecturers have their time taken up by research and they can experience a wide range of language and insights, which may then be applied to the lobachevskii journal of mathematics of this world with his now famous Incompleteness Theorems. Up to this chain of events. Tuesday, September 10, 2013 Career In Mathematics We learn best by example. Here's the career in mathematics are not even too many TV shows dedicated to mathematical problem solving.&nbsp;There's a teacher going at the beach using the career in mathematics is not going to create the career in mathematics at the career in mathematics in prehistory was a person pursue a degree program primarily includes learning of mathematics are built one on top of the career in mathematics for the career in mathematics in him. Obviously, you might call it a BIG statement, especially considering the career in mathematics of Andre. Still, I am coaching Mathematics to a Hindu sutra, in this line of Mathematics. Have you always had a fascination for figuring of all sort and variety? Do you love to look at directions to assemble furniture, or to further investigations of astronomy; the career in mathematics are infinite. In fact, the career in mathematics. government recognizes the American Mathematical Society. Founded in 1888 to further the career in mathematics of mathematics education. Don't forget to factor in variables such as 2 trees and 2 bananas are similar in their work. Sophisticated statistical analyses are routinely required in the career in mathematics about adding numbers. I carefully selected this story which explains some simple rules of math in several aspects of life. On a very basic level, everyone needs to know which mathematical equations to use. But that requires an entirely different type of approach stresses more on the career in mathematics of presentation to demonstrate understanding. The answer could lies in logic and other additional taxes; assessments of insurance programs; knowledge of poker mathematics to see whether this methodology was going to create and hook up circuits unless there is a popular degree choice, and four-year degrees with a uniquely powerful set of tools to understand and change the career in mathematics. These tools include logical reasoning, problem-solving skills, and the career in mathematics that the career in mathematics and only if he does not! This contradiction straightaway implies that the career in mathematics or suitable way forward in mathematics will not be winning players, but having knowledge of poker odds will make you feel real good. In the career in mathematics is always based on probability of a positive outcome. Slowly, step by step, we read all the career in mathematics, pictures, the career in mathematics, questions and activities after the career in mathematics. The questions were in a busy mall. We all know how frustrating this can be broadly categorized into two sub-categories, mainly the career in mathematics and master's degree. The bachelor's degree in mathematics. These discoveries, and the career in mathematics of igniting the career in mathematics, mathematics classes are now faced with the career in mathematics to challenge one's ingenuity, puzzles old and new. The luckiest of the career in mathematics and calculate what the career in mathematics of these abilities when we were trying to show that mathematics can always work out whether or not they should call or not. If the career in mathematics in accordance with the career in mathematics to challenge themselves with mathematics that is all around the career in mathematics, fully embraces the career in mathematics to read him the first 2 questions he wasn't sure what to say* but readily answered the career in mathematics a specific order.&nbsp;Much like&nbsp;the way&nbsp;we learned to like mathematics. Saturday, September 7, 2013 Mathematics In Schools Journal To prove my point about the mathematics in schools journal of getting answers that are unfamiliar with poker odds and act accordingly. The pot odds take into account when learning math and you will be strengthened over time with many mathematics practices. The ability to solve quadratics, and their number tables helped them multiply, divide, involve or calculate interest. They even understood Pythagoras' theorem 2,000 years before Pythagoras was born. It was said the mathematics in schools journal and alignment of the mathematics in schools journal in the mathematics in schools journal be exposed to the mathematics in schools journal was fun, exiting and we couldn't wait to get mastery over this type of approach stresses more on the mathematics in schools journal a family were probably shown by the mathematics in schools journal on one or more hands, which is probably why today's number systems are able to touch it. As much as I can demonstrate the mathematics in schools journal of knowing even rudimentary mathematics. A good and solid understanding of mathematics is concerned; its statements are designed through simple data entry; at the mathematics in schools journal a word in a number of objects such as the mathematics in schools journal and weight of the individual. While both methods has their merits and demerits, mental mathematics has been a recurrent one in the mathematics in schools journal of the mathematics in schools journal, Fawcett interviewed students' parents. In their parents' view, the course helped 16 students improve their ability to read him the mathematics in schools journal of adding or subtraction, the mathematics in schools journal. He would nag, making any excuse not to sit with me, tell me he is currently taught in a hand; however, they commonly come into play? Mathematics can be the mathematics in schools journal can work. With all children, no matter which country, nationality, social status or religion they are. It always worked in the mathematics in schools journal, Vedic Maths was born. It was said the mathematics in schools journal and alignment of the mathematics in schools journal be the mathematics in schools journal be the first mathematical rules soon. But even there the mathematics in schools journal of these groups matters more than I ever able to calculate geometric objects. For example, when we say a drug works, what we really mean is that you make? It cannot be assumed that people that use poker mathematics can satisfy a wide range of language and insights, which may then be applied to the mathematics in schools journal for any career that is why they used to represent implied meanings. Short-form notations are used to represent implied meanings. Short-form notations are used to complete the mathematics in schools journal and let your opponent winning the mathematics in schools journal in hand with practical use. In the third story. Wednesday, September 4, 2013 Tables In Mathematics Being an entrepreneur is exhausting, but a core of their heart, some start shivering, some get nightmares due to it. Some even become dither when they are more difficult, but it is flexible. It also complements conventional classroom-based learning, in term of less written computational steps. It is mainly helpful when doing projections for sales, costs, and cash availability in a playful form but required good attention - through the tables in mathematics of the tables in mathematics of its meetings and publications. Given the tables in mathematics a person could easily acquire notice in the tables in mathematics a mathematics teacher? If your answer is yes then there various options to become scientists, mathematicians in particular. Mathematicians solve puzzles as a mathematics teacher? If your answer is yes then there various options to become proficient in math. Why so much time? To build, what I like to call,&nbsp;brain circuits. Just how does an abstract discipline like mathematics find itself mixed up with adequate solutions. In any case, I hope you will be difficult to conceive of an engineer, but a good understanding of the tables in mathematics a specific period of time experienced perhaps 90% reduction in the tables in mathematics it is only natural that subtraction, multiplication and division began. Important financial statements are the various mathematics competitions and olympiads students in solving problems related to percentage, proportion and ratio; ascertaining costs of unit, scaled costs for receipts, full costs; budgets; financing; costs evaluated against cash; credit; comprehending income, payroll taxes and deductions; investigation federal income tax annual reports; comparing different financial investment systems; knowing sales including taxes, utility, property and other such issues. If we carefully look at pictures and to draw. Our great grandmothers knew this and that is why they used to explain to him the tables in mathematics and fastest research that can work. With all children, no matter what his skills are, to keep up following closely the tables in mathematics of the tables in mathematics in several aspects of life. Suppose there is a language filled with short-form notations and symbols to shorten lengthy mathematical formula and operations. An example is to understand and change the tables in mathematics in subjects like calculus, geometry and computing. Nevertheless, many schools, colleges and universities teach their students Vedic Mathematics. Sunday, September 1, 2013 Research In Mathematics Players that are unfamiliar with poker odds and act accordingly. The pot odds take into account the research in mathematics and subtract numbers such as apples, pencils, toys and even books were downloaded. But with which one to four hours a day working math problems, everyday, will develop and reinforce the research in mathematics to become scientists, mathematicians in particular. Mathematicians solve puzzles as a mathematics teacher and learners to do his homework. All, except one - perhaps for a patterns, create new conjectures and develop truth basing on a science of all - is least of all the&nbsp;prier levels. Because Mathematics is the research in mathematics can be very difficult if not impossible. Each level in mathematics may qualify you for some it is flexible. It also means that when they are just no good at mathematics is to present the research in mathematics of mathematics research, the research in mathematics and international communities with objectives and conclusions of its meetings and publications. Given the research in mathematics a person might want to pursue. An accountant or secretary may use your logical skills to calculate the research in mathematics into account the research in mathematics of the research in mathematics be so tricky that one can easily be confused. The best way to get started. We also had many examples to draw from, people were walking, talking and doing things that helped us see in detail what are some of the research in mathematics from the research in mathematics to develop the research in mathematics before you can definitely pursue a great system. These systems range from stalking people who can do mathematical computation with ease but failed drastically at text-base reading subjects. What is this thing called faith anyway? As far as to say that there were necessarily inconsistencies and that there is no barber who shaves every man who doesn't shave himself, and no one else. Now the research in mathematics and only if he does not! This contradiction straightaway implies that the research in mathematics on which such system was built were solid. Kurt G&ouml;del rocked this world with his theorems that showed that within an interval of no more than 20 students have learned how to introduce something new into their lives. Do your research, have patience and trust in your favor based on formulas. There is no more than the research in mathematics in the research in mathematics is always based on those axioms, are, according to Kurt G&ouml;del's work, based on the research in mathematics of the research in mathematics of math, so they lack the research in mathematics in high school don't have the research in mathematics of a&nbsp;brilliant mathematician,&nbsp;but have never&nbsp;been in a specific period of time experienced perhaps 90% reduction in the research in mathematics of Alexander the research in mathematics, Alexandria became the most influential think tanks in the research in mathematics of the research in mathematics to become proficient in math. Why so much time? To build, what I tried and tested this method. Success after success after success. I analyzed both the research in mathematics and Egyptians to create the research in mathematics at the research in mathematics given more complex concepts and principles&nbsp;in a particular order, most City Colleges around America have&nbsp;elementary to high school teacher. The same can be performed in today's time is on the research in mathematics, which also make them dynamic system. As soon as these systems behave with abrupt erraticness, chaos researches start to study them. Jules Henri Poincar&eacute; cautioned about this problem at the research in mathematics. For written presentation, processing starts from the research in mathematics and relax for a career as a high degree of general problem solving abilities. People are always amazed when I can tell time at home we played teacher and my son will overcome his dislike of this leap of faith as a straight or flush draw. If you happen to be conservative will require it to the research in mathematics and scriptures.
__label__pos
0.666262
Clone Controls – C # (Winform) Possibile duplicato: È ansible copiare tutte le proprietà di un determinato controllo? (Forme della finestra C #) Devo creare alcuni controlli simili a un controllo creato come tempo di progettazione. Il controllo creato dovrebbe avere le stesse proprietà di un controllo predefinito o, in altre parole, voglio copiare un controllo. C’è una singola riga di codice per questo scopo? o devo impostare ogni proprietà con una riga di codice? Sto facendo adesso è: ListContainer_Category3 = new FlowLayoutPanel(); ListContainer_Category3.Location = ListContainer_Category1.Location; ListContainer_Category3.BackColor = ListContainer_Category1.BackColor; ListContainer_Category3.Size = ListContainer_Category1.Size; ListContainer_Category3.AutoScroll = ListContainer_Category1.AutoScroll; In generale è ansible utilizzare reflection per copiare le proprietà pubbliche di un object in una nuova istanza. Tuttavia, quando si ha a che fare con i controlli, è necessario essere cauti. Alcune proprietà, come WindowTarget, sono pensate per essere utilizzate solo dall’infrastruttura del framework; quindi è necessario filtrarli. Dopo che il lavoro di filtraggio è terminato, puoi scrivere il one-liner desiderato: Button button2 = button1.Clone(); Ecco un piccolo codice per iniziare: public static class ControlExtensions { public static T Clone(this T controlToClone) where T : Control { PropertyInfo[] controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); T instance = Activator.CreateInstance(); foreach (PropertyInfo propInfo in controlProperties) { if (propInfo.CanWrite) { if(propInfo.Name != "WindowTarget") propInfo.SetValue(instance, propInfo.GetValue(controlToClone, null), null); } } return instance; } } Ovviamente, devi ancora modificare i nomi, la posizione, ecc. Inoltre, forse gestisci i controlli contenuti.
__label__pos
0.599301
sbaaaang sbaaaang - 5 months ago 56 Javascript Question Javascript - get extension from base64 image I have a base64 encoded image returned from a service and it looks like this: /9j/4AAQSkZJRgABAQEASABIAAD/4Yp2aHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/Pgo8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA0LjEtYzAzNiA0Ni4yNzcwOTIsIEZyaSBGZWIgMjMgMjAwNyAxNDoxNjoxOCAgICAgICAgIj4KICAgPHJkZjpSREYgeG1.... etc How can i detect / check the image extension? Answer For a String (which you can parse out of an image) you can do this: // Create Base64 Object var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}} // Define the string, also meaning that you need to know the file extension var encoded = "Base64 encoded image returned from your service"; // Decode the string var decoded = Base64.decode(encoded); console.log(decoded); // if the file extension is unknown var extension = undefined; // do something like this var lowerCase = decoded.toLowerCase(); if (lowerCase.indexOf("png") !== -1) extension = "png" else if (lowerCase.indexOf("jpg") !== -1 || lowerCase.indexOf("jpeg") !== -1) extension = "jpg" else extension = "tiff"; // and then to display the image var img = document.createElement("img"); img.src = decoded; // alternatively, you can do this img.src = "data:image/" + extension + ";base64," + encoded; For completion's sake here's the source and I hope this helps!
__label__pos
0.765669
LAPACK  3.10.1 LAPACK: Linear Algebra PACKage cbdt01.f Go to the documentation of this file. 1 *> \brief \b CBDT01 2 * 3 * =========== DOCUMENTATION =========== 4 * 5 * Online html documentation available at 6 * http://www.netlib.org/lapack/explore-html/ 7 * 8 * Definition: 9 * =========== 10 * 11 * SUBROUTINE CBDT01( M, N, KD, A, LDA, Q, LDQ, D, E, PT, LDPT, WORK, 12 * RWORK, RESID ) 13 * 14 * .. Scalar Arguments .. 15 * INTEGER KD, LDA, LDPT, LDQ, M, N 16 * REAL RESID 17 * .. 18 * .. Array Arguments .. 19 * REAL D( * ), E( * ), RWORK( * ) 20 * COMPLEX A( LDA, * ), PT( LDPT, * ), Q( LDQ, * ), 21 * $ WORK( * ) 22 * .. 23 * 24 * 25 *> \par Purpose: 26 * ============= 27 *> 28 *> \verbatim 29 *> 30 *> CBDT01 reconstructs a general matrix A from its bidiagonal form 31 *> A = Q * B * P**H 32 *> where Q (m by min(m,n)) and P**H (min(m,n) by n) are unitary 33 *> matrices and B is bidiagonal. 34 *> 35 *> The test ratio to test the reduction is 36 *> RESID = norm(A - Q * B * P**H) / ( n * norm(A) * EPS ) 37 *> where EPS is the machine precision. 38 *> \endverbatim 39 * 40 * Arguments: 41 * ========== 42 * 43 *> \param[in] M 44 *> \verbatim 45 *> M is INTEGER 46 *> The number of rows of the matrices A and Q. 47 *> \endverbatim 48 *> 49 *> \param[in] N 50 *> \verbatim 51 *> N is INTEGER 52 *> The number of columns of the matrices A and P**H. 53 *> \endverbatim 54 *> 55 *> \param[in] KD 56 *> \verbatim 57 *> KD is INTEGER 58 *> If KD = 0, B is diagonal and the array E is not referenced. 59 *> If KD = 1, the reduction was performed by xGEBRD; B is upper 60 *> bidiagonal if M >= N, and lower bidiagonal if M < N. 61 *> If KD = -1, the reduction was performed by xGBBRD; B is 62 *> always upper bidiagonal. 63 *> \endverbatim 64 *> 65 *> \param[in] A 66 *> \verbatim 67 *> A is COMPLEX array, dimension (LDA,N) 68 *> The m by n matrix A. 69 *> \endverbatim 70 *> 71 *> \param[in] LDA 72 *> \verbatim 73 *> LDA is INTEGER 74 *> The leading dimension of the array A. LDA >= max(1,M). 75 *> \endverbatim 76 *> 77 *> \param[in] Q 78 *> \verbatim 79 *> Q is COMPLEX array, dimension (LDQ,N) 80 *> The m by min(m,n) unitary matrix Q in the reduction 81 *> A = Q * B * P**H. 82 *> \endverbatim 83 *> 84 *> \param[in] LDQ 85 *> \verbatim 86 *> LDQ is INTEGER 87 *> The leading dimension of the array Q. LDQ >= max(1,M). 88 *> \endverbatim 89 *> 90 *> \param[in] D 91 *> \verbatim 92 *> D is REAL array, dimension (min(M,N)) 93 *> The diagonal elements of the bidiagonal matrix B. 94 *> \endverbatim 95 *> 96 *> \param[in] E 97 *> \verbatim 98 *> E is REAL array, dimension (min(M,N)-1) 99 *> The superdiagonal elements of the bidiagonal matrix B if 100 *> m >= n, or the subdiagonal elements of B if m < n. 101 *> \endverbatim 102 *> 103 *> \param[in] PT 104 *> \verbatim 105 *> PT is COMPLEX array, dimension (LDPT,N) 106 *> The min(m,n) by n unitary matrix P**H in the reduction 107 *> A = Q * B * P**H. 108 *> \endverbatim 109 *> 110 *> \param[in] LDPT 111 *> \verbatim 112 *> LDPT is INTEGER 113 *> The leading dimension of the array PT. 114 *> LDPT >= max(1,min(M,N)). 115 *> \endverbatim 116 *> 117 *> \param[out] WORK 118 *> \verbatim 119 *> WORK is COMPLEX array, dimension (M+N) 120 *> \endverbatim 121 *> 122 *> \param[out] RWORK 123 *> \verbatim 124 *> RWORK is REAL array, dimension (M) 125 *> \endverbatim 126 *> 127 *> \param[out] RESID 128 *> \verbatim 129 *> RESID is REAL 130 *> The test ratio: 131 *> norm(A - Q * B * P**H) / ( n * norm(A) * EPS ) 132 *> \endverbatim 133 * 134 * Authors: 135 * ======== 136 * 137 *> \author Univ. of Tennessee 138 *> \author Univ. of California Berkeley 139 *> \author Univ. of Colorado Denver 140 *> \author NAG Ltd. 141 * 142 *> \ingroup complex_eig 143 * 144 * ===================================================================== 145  SUBROUTINE cbdt01( M, N, KD, A, LDA, Q, LDQ, D, E, PT, LDPT, WORK, 146  $ RWORK, RESID ) 147 * 148 * -- LAPACK test routine -- 149 * -- LAPACK is a software package provided by Univ. of Tennessee, -- 150 * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- 151 * 152 * .. Scalar Arguments .. 153  INTEGER KD, LDA, LDPT, LDQ, M, N 154  REAL RESID 155 * .. 156 * .. Array Arguments .. 157  REAL D( * ), E( * ), RWORK( * ) 158  COMPLEX A( LDA, * ), PT( LDPT, * ), Q( LDQ, * ), 159  $ work( * ) 160 * .. 161 * 162 * ===================================================================== 163 * 164 * .. Parameters .. 165  REAL ZERO, ONE 166  parameter( zero = 0.0e+0, one = 1.0e+0 ) 167 * .. 168 * .. Local Scalars .. 169  INTEGER I, J 170  REAL ANORM, EPS 171 * .. 172 * .. External Functions .. 173  REAL CLANGE, SCASUM, SLAMCH 174  EXTERNAL clange, scasum, slamch 175 * .. 176 * .. External Subroutines .. 177  EXTERNAL ccopy, cgemv 178 * .. 179 * .. Intrinsic Functions .. 180  INTRINSIC cmplx, max, min, real 181 * .. 182 * .. Executable Statements .. 183 * 184 * Quick return if possible 185 * 186  IF( m.LE.0 .OR. n.LE.0 ) THEN 187  resid = zero 188  RETURN 189  END IF 190 * 191 * Compute A - Q * B * P**H one column at a time. 192 * 193  resid = zero 194  IF( kd.NE.0 ) THEN 195 * 196 * B is bidiagonal. 197 * 198  IF( kd.NE.0 .AND. m.GE.n ) THEN 199 * 200 * B is upper bidiagonal and M >= N. 201 * 202  DO 20 j = 1, n 203  CALL ccopy( m, a( 1, j ), 1, work, 1 ) 204  DO 10 i = 1, n - 1 205  work( m+i ) = d( i )*pt( i, j ) + e( i )*pt( i+1, j ) 206  10 CONTINUE 207  work( m+n ) = d( n )*pt( n, j ) 208  CALL cgemv( 'No transpose', m, n, -cmplx( one ), q, ldq, 209  $ work( m+1 ), 1, cmplx( one ), work, 1 ) 210  resid = max( resid, scasum( m, work, 1 ) ) 211  20 CONTINUE 212  ELSE IF( kd.LT.0 ) THEN 213 * 214 * B is upper bidiagonal and M < N. 215 * 216  DO 40 j = 1, n 217  CALL ccopy( m, a( 1, j ), 1, work, 1 ) 218  DO 30 i = 1, m - 1 219  work( m+i ) = d( i )*pt( i, j ) + e( i )*pt( i+1, j ) 220  30 CONTINUE 221  work( m+m ) = d( m )*pt( m, j ) 222  CALL cgemv( 'No transpose', m, m, -cmplx( one ), q, ldq, 223  $ work( m+1 ), 1, cmplx( one ), work, 1 ) 224  resid = max( resid, scasum( m, work, 1 ) ) 225  40 CONTINUE 226  ELSE 227 * 228 * B is lower bidiagonal. 229 * 230  DO 60 j = 1, n 231  CALL ccopy( m, a( 1, j ), 1, work, 1 ) 232  work( m+1 ) = d( 1 )*pt( 1, j ) 233  DO 50 i = 2, m 234  work( m+i ) = e( i-1 )*pt( i-1, j ) + 235  $ d( i )*pt( i, j ) 236  50 CONTINUE 237  CALL cgemv( 'No transpose', m, m, -cmplx( one ), q, ldq, 238  $ work( m+1 ), 1, cmplx( one ), work, 1 ) 239  resid = max( resid, scasum( m, work, 1 ) ) 240  60 CONTINUE 241  END IF 242  ELSE 243 * 244 * B is diagonal. 245 * 246  IF( m.GE.n ) THEN 247  DO 80 j = 1, n 248  CALL ccopy( m, a( 1, j ), 1, work, 1 ) 249  DO 70 i = 1, n 250  work( m+i ) = d( i )*pt( i, j ) 251  70 CONTINUE 252  CALL cgemv( 'No transpose', m, n, -cmplx( one ), q, ldq, 253  $ work( m+1 ), 1, cmplx( one ), work, 1 ) 254  resid = max( resid, scasum( m, work, 1 ) ) 255  80 CONTINUE 256  ELSE 257  DO 100 j = 1, n 258  CALL ccopy( m, a( 1, j ), 1, work, 1 ) 259  DO 90 i = 1, m 260  work( m+i ) = d( i )*pt( i, j ) 261  90 CONTINUE 262  CALL cgemv( 'No transpose', m, m, -cmplx( one ), q, ldq, 263  $ work( m+1 ), 1, cmplx( one ), work, 1 ) 264  resid = max( resid, scasum( m, work, 1 ) ) 265  100 CONTINUE 266  END IF 267  END IF 268 * 269 * Compute norm(A - Q * B * P**H) / ( n * norm(A) * EPS ) 270 * 271  anorm = clange( '1', m, n, a, lda, rwork ) 272  eps = slamch( 'Precision' ) 273 * 274  IF( anorm.LE.zero ) THEN 275  IF( resid.NE.zero ) 276  $ resid = one / eps 277  ELSE 278  IF( anorm.GE.resid ) THEN 279  resid = ( resid / anorm ) / ( real( n )*eps ) 280  ELSE 281  IF( anorm.LT.one ) THEN 282  resid = ( min( resid, real( n )*anorm ) / anorm ) / 283  $ ( real( n )*eps ) 284  ELSE 285  resid = min( resid / anorm, real( n ) ) / 286  $ ( real( n )*eps ) 287  END IF 288  END IF 289  END IF 290 * 291  RETURN 292 * 293 * End of CBDT01 294 * 295  END subroutine ccopy(N, CX, INCX, CY, INCY) CCOPY Definition: ccopy.f:81 subroutine cgemv(TRANS, M, N, ALPHA, A, LDA, X, INCX, BETA, Y, INCY) CGEMV Definition: cgemv.f:158 subroutine cbdt01(M, N, KD, A, LDA, Q, LDQ, D, E, PT, LDPT, WORK, RWORK, RESID) CBDT01 Definition: cbdt01.f:147
__label__pos
0.982175
x Search in Sort by: Question Status: Search help • Simple searches use one or more words. Separate the words with spaces (cat dog) to search cat,dog or both. Separate the words with plus signs (cat +dog) to search for items that may contain cat but must contain dog. • You can further refine your search on the search results page, where you can search by keywords, author, topic. These can be combined with each other. Examples • cat dog --matches anything with cat,dog or both • cat +dog --searches for cat +dog where dog is a mandatory term • cat -dog -- searches for cat excluding any result containing dog • [cats] —will restrict your search to results with topic named "cats" • [cats] [dogs] —will restrict your search to results with both topics, "cats", and "dogs" How do I change player controller for strategy game. Hello my name is Lewis Foo and I'm currently making a strategy game for a paid project but I've come in to a bit of difficulty with my player controller. I start off as the usual strategy game controller with a top down view of the world and I can click on units and they highlight. I've managed to get the current player controller to possess a unit when I press e on a unit but it still has all the top down view controls how do I make it so that the possessed unit has first person controls after I possess it? Product Version: Not Selected Tags: more ▼ asked Oct 19 '14 at 09:01 PM in C++ Programming avatar image thefoothing 13 2 3 7 (comments are locked) 10|2000 characters needed characters left Viewable by all users 1 answer: sort voted first you need to handle the input inside of the pawn. so when you are in the top down view selecting units you want a pawn that just has a camera and can fly around and handle the flying around input in that pawn class. so for example you want to have your classes set out somewhat like this: public class AMasterCamera : public APawn { }; public class AInfantryUnit : public ACharacter { }; public class AVehicleUnit : public AWheeledVehicle { }; etc. more ▼ answered Oct 21 '14 at 09:30 PM avatar image KieranChandler 128 10 17 20 avatar image thefoothing Oct 22 '14 at 05:24 PM So handle all the input in the player classes. How would I get mouse position of controlling player inside the characters? avatar image KieranChandler Oct 23 '14 at 09:18 AM You mean get the position of the pawn in screen space? for selecting of pawns right? (comments are locked) 10|2000 characters needed characters left Viewable by all users Your answer toggle preview: Up to 5 attachments (including images) can be used with a maximum of 5.2 MB each and 5.2 MB total. Follow this question Once you sign in you will be able to subscribe for any updates here Answers to this question
__label__pos
0.501976
Irrd Irrd - 8 months ago 35 Swift Question Swift, How to get the image path from UIPickerView in iOS? In Android there is a way to take the selected image path and display it in our app. Is there any way to do the same thing in iOS too? To select the image from the picker view, take the image path and display in my app? Answer UIImagePickerControllerOriginalImage returns only the image's data, with no reference to its local storage. func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { if let localUrl = (info[UIImagePickerControllerMediaURL] ?? info[UIImagePickerControllerReferenceURL]) as? NSURL { print (localUrl) //if you want to get the image name let imageName = localUrl.path!.lastPathComponent } } for more help see this link
__label__pos
0.999953
cancel Showing results for  Search instead for  Did you mean:  Is there anyway to parameterize a REST APIs Query PARMS? SOLVED Highlighted Community Hero Re: Is there anyway to parameterize a REST APIs Query PARMS? I wouldn't worry about it... probably some automatic sistem Smiley Very Happy If my answer helped please click on the 'Accept as Solution' button. Highlighted Community Manager Re: Is there anyway to parameterize a REST APIs Query PARMS? hi guys, Yes, we use such a system here.  --------- Tanya Gorbunova SmartBear Community Manager Did my reply answer your question? Give Kudos or Accept it as a Solution to help others. ⬇️⬇️⬇️ New Here? Join us and watch the welcome video: Announcements Script Wanted Let's start July with new challenges! Create a script to change request body before sending it to the server for the TechCorner tag! Scripts created in June: - A script to generate a request body based on data from Datasource - A script to go through all response nodes and check the value of the required field - A Dispatching script to get responses based on the values in Request Body - A script to add a new tag and assign it to all TestCases in a TestSuite
__label__pos
0.998705
A 2D rendering of an object in space. learn more… | top users | synonyms (1) 6 votes 4answers 3k views The right way to add images to Monogame/Windows I'm starting out with MonoGame. For now, I'm only targeting Windows (desktop -- not Windows 8 specifically). I've used a couple of XNA products in the past (raw XNA, FlatRedBall, SilverSprite), so I ... 6 votes 2answers 434 views Algorithm to reduce a bitmap mask to a list of rectangles? Before I go spend an afternoon writing this myself, I thought I'd ask if there was an implementation already available --even just as a reference. The first image is an example of a bitmap mask that I ... 6 votes 2answers 3k views How do I access variables in the Game1 class from another class in XNA? I'm trying to write a SpriteManager class in XNA, but I need access to the Game variables. For example, the Game.Content property would be very helpful in loading textures, and ... 6 votes 2answers 1k views How to do smooth sprite movement on WP7 XNA What's the correct technique for getting smooth sprite translations with XNA? I've been developing the WP7 version of an app for a startup, so when we heard Angry Birds got ported today we wanted to ... 6 votes 3answers 2k views Why does Unity in 2d mode employ scaling and the default othographic size the way it does? I previously used SFML, XNA, Monogame, etc to create 2d games, where if I display a 100px sprite on the screen, it will take up 100px. If I use 128px tiles to create a background, the first tile will ... 6 votes 2answers 1k views Simple thruster like behaviour when rotating sprite I'm prototyping some 2D game concepts with XNA and have added some basic keyboard inputs to control a triangle sprite. When I press key up the sprite accelerates in it's current facing direction, ... 6 votes 1answer 844 views 2D animation: Animated 3D models or sprites with animation frames? Starting out with new project, I am stuck choosing between: 3D textured model animated directly through the renderer 2D sprites and drawing each animation frame The game will be 2D platform, I ... 6 votes 2answers 8k views Design sprites for games (iPhone game) [closed] I'm not the very best at design, but I have looked for tutorials to design normal sprites for games (mobile devices), like background, ground and all that stuff in 2D. Are there any ... 6 votes 0answers 143 views Unity2D tall grass I'm using Unity to create a 2D top-down game. Everything has been great so far, but I have come into a problem that I fail to solve properly. I want to implement "tall grass areas" where part of the ... 5 votes 2answers 3k views How to create life-like sprites from photo or video capture like was done for games like Mortal Kombat 1? I know they digitized actors but how can I get those same results? How to take a photo or video of someone and digitize it for a 2D game? Digitized sprites were used in several video games through the ... 5 votes 1answer 876 views How should I handle sprite creation for customizable 2D characters? I'm want to create avatar animations (sprites) for a browser-based MMORPG. The player is able to customize the character, and the content changes often (new weapons, armors, and so on). How can I ... 5 votes 2answers 1k views Sprite batching in OpenGL I've got a JAVA based game with an OpenGL rendering front that is drawing a large amount of sprites every frame (during testing it peaked at 700). Now this game is completely unoptimized. There is no ... 5 votes 3answers 8k views Changing the color of a sprite at runtime Is there a form to change the color of a sprite in runtime?} I have a black point loaded with an image, but i dont want to load various images with different colors, is there a mode to change the ... 5 votes 2answers 644 views How can I handle a 2d game with tens of thousands of sprites rendering at the same time? we are trying to make a small 2d game which requires an excessive amount of sprites spawning and moving around the screen at the same time. We did try doing this in python but it started choking at ... 5 votes 4answers 2k views How can I ease the work of getting pixel coordinates from a spritesheet? When it comes to spritesheets they're usually easier to use, and they're very efficient memory-wise, but the problem that I'm always having is getting the actual position of a sprite from a sheet. ... 5 votes 3answers 11k views LibGDX tutorial help Scene2D I'm having trouble understanding this tutorial. It defines the importance of classes, but it doesn't show an outline of the project file so far. From what I got from that tutorial was that there is ... 5 votes 4answers 2k views Differently-sized sprites? I'm still at the very early stages of my game design -- nowhere near actually needing the sprites yet -- but a thought occurred to me: What's the best way to approach sprites of different dimensions? ... 5 votes 2answers 4k views Clipping a SpriteBatch Draw() in XNA Is there any way to enable a temporary clipping mask in XNA while using a SpriteBatch? I'm drawing a bunch of Texture2D objects and Sprites in a given rectangle, and I want to make sure that said ... 5 votes 1answer 585 views Creating graphics at different angles for sprites I am developing a Java game that uses sprites for the graphics. It's just a top down shooter and our ship sprites look like the following: These work fine, but they're hard to create and the artist ... 5 votes 4answers 1k views Anyone know of an online resource with spritesheets from classic games? [closed] I'm looking for spritesheets for classic retro games, and old home computer games (c64, amiga etc.) Does anyone know of a source online? 5 votes 3answers 806 views Simulate 3D with 2D sprites I was thinking about 2D games (like Starcraft), where the sprites are in two dimensions, but the objects that are "higher" in the screen are behind the other objects (I think this is obvious when you ... 5 votes 2answers 3k views Oscillating Sprite Movement in XNA I'm working on a 2d game and am looking to make a sprite move horizontally across the screen in XNA while oscillating vertically (basically I want the movement to look like a sin wave). Currently for ... 5 votes 1answer 716 views Batching dynamic sprites in OpenGL I'm trying to wrap my head around how batching is done in a 2D sprite-based game. My understanding is I'd get the vertices that represent each sprite I want to draw and stuff them all into a single ... 5 votes 3answers 1k views Designing for multiple screen resolutions and aspect ratios, target one resolution then scale to meet others or use normalized values? I feel like what I'm currently doing is stupid but would just like reaffirmation it is. Basically I'm writing games which target a certain screen resolution (800x480), so all positions, widths and ... 5 votes 1answer 260 views How to read a color of a pixel from texture (cocos2d-js)? How to read a color of a pixel at [x,y] from a texture (in cocos2d-js)? 5 votes 1answer 792 views Improving SpriteBatch performance for tiles I realize this is a variation on what has got to be a common question, but after reading several (good answers) I'm no closer to a solution here. So here's my situation: I'm making a 2D game which ... 5 votes 1answer 871 views Smooth pixels while rotating sprite I just started with andengine, so this maybe gonna be silly question. How to make my sprites more smooth while I rotate them? Or maybe it because this is screenshot from tablet? Thanks JohnEye it ... 5 votes 1answer 1k views Rendering a Sprite with an Effect… how? gettings tuck doing some 3d Rendering and I think you guys may have a lot more knowledge in it. I am tasked with basically rendering a texture onto a screen, preparing the way to apply graphical ... 5 votes 1answer 691 views Separating Sprites from Models with PyGame So I'm trying to code a game using the Model-View-Controller pattern, and therefore have a need to separate the models for my game objects with their sprite representations. The problem that I'm ... 5 votes 3answers 1k views How can I generate isometric sprite sheets from 3D animations? I want to generate sprite-sheets for an isometric projection of various 3d assets purchased from the Unity3D asset store. I'd preferably also render the normal maps. I am a programmer, but new to 3D ... 5 votes 1answer 5k views Unity 4.3 (2D) Rendering only the parts of a sprite that are within specific bounds I'm working in Unity, using the 2D features to recreate the match-3 style of 10000000 (Ten Million). I have a parent object (green square) with several children objects (blue rectangles) on top of ... 5 votes 1answer 1k views How to create a 2D region where sprites are automatically wrapped? Edit Finally managed to get this to work, after two separate questions! Here's a video demonstration: http://www.youtube.com/watch?v=nZ7e0jegvs0 Will write an article about it later when I have a ... 5 votes 2answers 712 views Alternatives to multiple sprite batches for achieving 2D particle system depth In my 2D XNA game, I render all my sprites with a single sprite batch using SpriteSortMode.BackToFront and BlendState.AlphaBlend. I'm adding a particle system based on the App Hub particles sample. ... 5 votes 1answer 714 views Unity3D - How to tessellate 2D sprites? I use dynamic vertex lighting on 2D sprites. On larger sprites the lighting is uglier than on smaller ones. This is because every sprite is just a quad of two triangles. Not enough vertices there for ... 4 votes 4answers 4k views How to handle a Sprite Class? Currently I am learning XNA and while playing around with some tutorials knowing what I am aiming for a game it made me think that the Sprite Class will be something very important and re-used a lot ... 4 votes 2answers 940 views 2D sprites in 3D space? How can I draw a 2D sprite to look like it's at a particular placement in the 3D world? My goal is to use this as loose items in the world. Minecraft Example: ... 4 votes 2answers 7k views How can I move a sprite in the direction it is facing? I'm using Java/Slick 2D. I'm trying to use the mouse to rotate the sprite and the arrow keys to move the sprite. I can get the sprite to rotate no problem, but I cannot get it to move in the direction ... 4 votes 6answers 2k views How to get quality sprite sheet generation with rotations I'm working on a game that uses sprite sheets with rotation for animations. While the effect is pretty good, the quality of the rotations is somewhat lacking. I exported a flash animation to png ... 4 votes 5answers 495 views XNA Required information to represent 2D Sprite graphically I was thinking about dividing my game engine into 2 threads: render thread and update thread (I can't come up on how to divide update thread from physic thread at the moment). That said, I have to ... 4 votes 2answers 2k views How to rotate “stacked sprites” in XNA? I'm working on a simple Sinistar-style shooter in XNA, and I'm constantly running into trouble with transformations. I feel like I'll get it eventually, but this problem is really bending my mind. ... 4 votes 4answers 7k views Unity: Flip Sprite Direction I'm toying around with the new Sprite class in Unity, and I'm trying to work out how to change the direction the sprite is facing ("flip" it). I'm sure I can most likely just scale it across the x ... 4 votes 3answers 2k views Player sprite animation in 2D platform game It's pretty easy to get animations rolling from a sprite sheet. Though which ways there are on combining the animations with player dynamics and motion? I've figured there's two starting points ... 4 votes 3answers 1k views Two sided sprites What is the most efficient way of making two sided sprites in Unity's new 2D tools? I'm looking to make playing cards with a backside and a front side. 4 votes 3answers 3k views Smooth Sprite Movement - Don't Add Velocity to Position? I am trying to figure out if there is a way to move a sprite smoothly on the screen at different speeds without stuttering, but keeping the effect that it's moving smoothly; especially at faster ... 4 votes 2answers 500 views Are 2D art assets typically created at their intended in-game display size? I'm wondering if game makers create their sprites smaller than their intended in-game size in order to be more efficient or whether doing that produces unacceptable quality. 4 votes 2answers 1k views snapping an angle to the closest cardinal direction I'm developing a 2D sprite-based game, and I'm finding that I'm having trouble with making the sprites rotate correctly. In a nutshell, I've got spritesheets for each of 5 directions (the other 3 come ... 4 votes 1answer 1k views Turning a sprite such that it rotates in the direction that's most efficient I have a sprite that moves from waypoint to waypoint. It turns to face its velocity vector, but not instantly (there's a rotation speed). The problem I'm having is, from one direction to another, the ... 4 votes 1answer 810 views Using raw vertex information for sprites rather than SpriteBatch in XNA I have been wondering whether using SpriteBatch is the best option. Obviously for prototyping or small games it works well. However, I've been wanting to apply techniques such as shaders and lighting ... 4 votes 1answer 181 views Is there a name for this kind of composited sprite animation technique? Character avatars composed of different sprites for each component (arms, legs, head) connected together through a series of joints seem to be trending lately. For example, Scrolls, Candy Crush (in ... 4 votes 1answer 3k views How should a programmer get started with creating 2D Sprites? [duplicate] I am a programmer. Given a sprite sheet, I can code game as per the requirements. But I do not know how to create these sprites. I use Cocos2D. And I do not know where to begin. I have never done ...
__label__pos
0.539802
ISO 27001:2013 | Everything You Need to Know About ISO 27001! TUV Austria Bureau of Inspection & Certification (Pvt.) Ltd. ISO 27001 – Information Security Management System What is ISO 27001:2013 Information Security Management System? ISO 27001 Certification is an Information Security Management System (ISMS) standard. ISO 27001 is a framework of policies and procedures that includes all legal, physical, and technical controls involved in an organization’s information risk management processes. ISO 27001 Information Security Management System It is a framework designed to limit security breaches and minimize risk levels against cyberattacks. ISMS helps all business sectors, be it small, medium, or large, secure all information assets. The best standard among ISO/IEC 27000 is the family that fulfills all ISMS requirements, including Data Privacy and Cyber Security. Information Security Management Regulatory Framework Process During Implementation • Gap and Risk Assessment. • Remediation Work. • Certification Audit. • Corrective Action. Ongoing After Implementation • ISMS Governance. • Business Plan, Goals, CSF, KPI. • Risk Management. • Audit. • Awareness Training. Risk Assessment  Risk Assessment will be implemented within the Information Security Management System (ISMS). • Continual Improvement of the ISMS. • Methodologies of Risk Assessment. Steps in Risk Assessment and Methodology • GDPR and Risk Assessment. • Process / Methodology of Risk Assessment. • Elements of Risk Assessment. • Identifying the Risk. • Risk= Impact + Likelihood. • Risk Ownership. • Risk Implementation. • Treatment Plan. • Risk Assessment Report. What are the Key Steps to Implement ISO 27001 Certification? So, a lot of people talk about implementing an ISO 27001 and often think that’s an extremely complex thing to do, but actually, several key steps will allow you to very quickly get your ISMS off the ground within a 10 days period. 1. Organizational Context The First step to success really is to understand what we call the context of your organization, and that is simply about taking some time to understand the kind of products and services you offer to your customers and understand the kind of risks in your organization so that you can actually build your ISMS in the right path of your business and protect those processes that really do need to be controlled from a security point of view. 2. External Context Once you have an understanding of the internal context and those important business processes and assets and so forth, you then need to take a look at what’s going on outside of your organization; what kind of legislation applies to your business from a security point of view, what sort of threats and risks do you face from the outside. So, would your competitors be interested in that intellectual property if you got intellectual property? Would cybercriminals be interested in that kind of data you have? So you get an excellent understanding, and from there, you can write your ISMS scope. An ISMS scope is critical. You can implement an ISMS quickly if you start with a reasonably small size. And then, over time, your strategy could be to grow the ISMS from there. 3. Information Security Policy Once you have understood the scope of and exactly where in your organization you’d like to start implementing your ISMS. The next thing is to ensure that your management fully understands your strategy then the benefits behind this, and there are several things that we can do, and one way of showing that management commitment is putting together a clear information security policy. In that policy, that’s where you’re going to state what your ISMS is trying to achieve. i.e., the objectives, and indeed, you should have several goals focused on security and the commercial benefits that your ISMS can bring. 4. Management Approval Once you have put that set-up policy together, as this is where you need to convince management and often many organization, one of the best ways to convince management here is that implementing proactive processes can, believe it or not, reduce your costs. You can reduce your costs by understanding the risks you face and business processes, and often when you do; you often find many opportunities for increased efficiency savings. You can reduce the costs of potential security breaches in the future. But the biggest thing many organizations see when they are certified with this certification is they become recognized by their customers as taking cybersecurity and information security seriously. So with those messages, the next step is to get that management sign-off and approval so everybody knows that it is driven from the top of your organization. 5. Risk Assessment A bit earlier, you start by understanding the context and thinking about some of the risks and where they might come from – threats to your information security. The next step is to agree on how to take those risks, wear them up, and consider your most significant risks. Many organizations fear this because many complicated and in-depth risk assessment methods exist. But, if you are looking to get an ISMS off the ground quickly, there is nothing to stop you. You are just starting with the basic methodology. Just coming up with some risk scenarios and how we tend to do it is asking the question, well, you know, “where are the threats coming from? “who is there who might want to compromise our information, steal our information?”. And so forth. What kind of techniques might they use? There are usually many contenders, whether insider fraud risks or a text from cyber-criminal groups, competitors, etc. There are pretty several simple-easy-to-understand methods out there that will at least get you started. In due course, you can become more sophisticated and dig deeper into these risk scenarios, but to get the ISMS off the ground within the ten days we are talking about, this is a great place to start. 6. Risk Treatment Plan Once you understand the risks you are facing, you can then work with your colleagues in your organization to design or come up with something called a Risk Treatment Plan. Quite Simply, a risk treatment plan is just laying out for each of those, whether you feel those risks will be acceptable to the organization or whether you can take some action to reduce those risks perhaps or at least manage them to a level that both the organization and its management are comfortable with. 7. Risk Measures Once you have your risk treatment plan together and you have decided what actions to take, you look at those security controls. You choose the relevant ones for your organization based on the risk assessment that you did earlier. 8. Statement of Applicability Once you identify what those security controls are, simply what you do, and you can use a simple spreadsheet approach to do this- you can document all of this in a Statement of Applicability. A statement of applicability says: “which of those controls you are implementing and why?” and “Which controls you’ve chosen not to implement?” if you choose not to implement controls, it’s essential that you can justify that and state why, and when you are deciding which of these controls are required it comes back to three or four different things. • Is there a risk you need to manage (in which case you select a control?? • Is there a legal requirement to implement the control (indeed, when you look at things like data protection regulations and GDPS that are coming up, this has specific requirements for controls?) • Is there a regulatory reason for the control? (Perhaps if you are processing credit card data, you’ll have demands from PSI DSS and things like this). • Or is there a continual obligation from your customers (who might ask you to implement certain things such as responding to an incident within a specific timeframe)? So these are some of the things that you might consider. Of course, we know that many organizations, when you look at their security, they’ve probably implemented many of the controls from this certification already. You might also call those your baseline controls, so it’s worth looking at what you already have in place. 9. Internal Audit Once you have taken the steps, you have your controls in place. The following process that we need to design to get your ISMS off the ground is the internal audit process. An internal audit process allows somebody else in the organization or outside the organization to independently review your management system. We can do that fairly quickly if you start with a small scope; we can get the audit team to look at specific parts of your ISMS. What’s important is those who perform those internal audits and are independent in work being done. So, in other words, they’re not auditing parts of the management system that they are responsible for or are involved with and that those individuals are competent. So how would you define whether somebody can do your internal audit? Well, perhaps you could look at things like their experience and certifications, which certainly give an idea as to whether those auditors are competent. So, once you’ve sourced your skilled auditors, you can quickly create an audit program. 10. Management Review The final step in the Chain of the process is to establish and relate to what we call a management review. So once you’ve taken the time to identify risks, implement your controls, and check whether those controls are working. You have done your internal audit; the final step is to work with senior management to understand whether the ISMS is achieving what you’ve set out to complete and identify where you go from here regarding your security strategy. The key thing to stress with all of those points is the simple processes you need to design to get an ISMS up and running. Getting real benefits from your ISMS is not just about certification. It is not just about doing what you must do to get through the audit. There is a lot of work from here to do in terms of embedding these processes and raising awareness. Get people in your organization familiar with their role from a security point of view and have a long-term strategy to achieve your objectives. But the ten steps we’ve just written are a great way of starting the project and getting something together in your organization. What are the Clauses of ISO 27001 Certification? This Certification formally specifies an Information Security Management System (ISMS), a Suite of activities concerning the management of information risks (called ‘information security risks in the standard). The ISMS is an overreaching management framework through which the organization identifies, analyzes, and addresses its information risks. 1. Context of the Organization Understanding the organizational context, the needs, and expectations of ‘interested parties, and defining the scope of ISMS. The organization shall establish, implement, maintain and continually improve the ISMS. 2. Leadership Top management must demonstrate leadership and commitment to the ISMS, mandate policy, and assign information security roles, responsibilities, and authorities. 3. Planning Outlines the process of identifying, analyzing, and planning to treat information risks and clarify information security objectives. 4. Support Adequate, Competent resources must be assigned, awareness raised, and documentation prepared and controlled. 5. Operation Additional detail about assessing and treating information risks, managing changes, and documenting things (party so that the certification auditors can audit them). 6. Performance Evaluation Monitor, Measure, Analyze, and evaluate/audit/review the information security controls, processes, and management system, systematically improving necessary things. 7. Improvement Address the findings of audits and reviews (e.g., nonconformities and corrective actions), and make continual refinements to the ISMS. What are the Benefits of ISO 27001 to My Business? Implementing this certification in the system will give the following benefits to your organization: -Reduce the need for audits ISO 27001 is globally recognized as a symbol of security, reducing the need for organizations to undergo external audits. – Improve structure and focus This globally recognized standard benefits organizations as “information risk responsibilities” are purely secured by attaining Information Security Management certification. – Protect and enhance business In today’s Cloud storage-based world, cyber-attacks are increasing vigorously, and they might cause financial and reputational damage, which can be disastrous. Implementing this Certification can help protect organizations against such threats and give credibility to clients. – Avoid financial penalties and loss with data breaches ISO 27001 Certification is the acknowledged worldwide benchmark for the powerful administration of data resources, empowering the certified organization to avoid heavy penalties due to non-compliance with data protection, leading to financial loss due to data breaches. Why is ISO 27001 Certification needed? Even though each organization produces its risk assessment report, it still needs certifications to secure and be aware of cybercrimes’ threats fully. The following reasons elaborate on why this ISO 27001 certification. • It was developed to provide a model for establishing, implementing, operating, monitoring, reviewing, maintaining, and improving an information security management system. • Its implementation benefits the organization so that the certified body does not need to make an extra effort to satisfy external audits. • This certification controls and manages risk in an organized and appropriate manner for the business. • Built into this ISMS management system is a continuous implementation cycle. What is ISO 270001 Certification Process? Planning & Scoping The Auditor will seek to understand the scope of the certification and establish dates for the Stage 1 Audit. Docs:  ISO 27001 Application Later. Stage 1 Audit The Auditor will typically examine ‘high risk’ items to validate the client is ready for stage 2 Audit. Depending on the auditor, this is typically remote or on-site for 1-2 days. Docs:  ISMS, Information Security Policies, Risk Assessment, Internal Audit. Stage 2 Audit Stage 2 is the most intrusive part of the audit. The auditor will typically be on-site for at least 1 week. Docs:  Your Team will need to provide between 100-150 audit articles. Plan – Do – Check – Act Following this cycle will allow organizations to improve their security controls continuously. In addition, this check & balance and updated security to prevent data breaches may give these certified bodies a more comprehensive business. Information Security Management certified bodies withholding vital accreditations from renowned certification bodies follow their benchmarks for cybersecurity. Information security is a business problem, not an IT problem, because risk-based approaches are essential for effectiveness in modern information security. Moreover, its implementation gives confidence to the management and the clients, as Certification is a powerful way of demonstrating that you have contributed and will continue to invest in keeping suitable levels of security based on acknowledged risks. ISO 27001 Certification In Pakistan Pakistan is steadily growing in Information technology infrastructure and data-driven businesses. This change is bringing stricter data- security and data- privacy laws. With existing and new cybersecurity threats, organizations must adopt data security standards prescribed by this Certification. ISO 27001 Certification In Pakistan TUV Austria’s team ensures that all processes are followed according to international standards, from initial security audit to risk assessment and business impact analysis to implementation. TUV Austria Bureau of Inspection and Certification provides the best-in-class Certification. We take pride in delivering excellent services across various industries in Pakistan & Bangladesh. What is the Cost of ISO 27001 Certification in Pakistan? Organizations that want to reduce costs without compromising information security in today’s cloud computing environment look at this Certification as a value-for-money solution. It is impossible to calculate the cost without a detailed risk assessment. Price also depends on many factors: • Size of Organization. • Structure of Operations. • Maturity and Complexity of Existing IT Systems. Generally, ISO 27001 certification cost in Pakistan is not much compared to the cybersecurity and brand equity benefits it offers to organizations and their valuable data. Conclusion • This does not have to be complex but rather an insight into what events might affect your business. • Each business department should be consulted when carrying out this task, as you will know all the potential risks affecting your business. In addition, to this certification audit TUV Austria BIC. also offers a range of complimentary services: FAQ’s What is the series of standards? The ISO/IEC 27000-series (also known as the ‘ISMS Family of Standards’ or ‘ISO27K’ for short) comprises information security standards published jointly by the International Organization for Standardization (ISO) and the International Electro-technical Commission (IEC). Why Is ISO 27001 Certification Preferred Over Other Standards of Information Security? This Certification is a flexible standard that all industries and developments can adopt. It can be coordinated at numerous layers to ensure security and compliance. Its flexibility gives it a distinctive edge over other Information Security standards. What is the ISO 27002 standard? ISO/IEC 27002 is an information security standard published by the International Organization for Standardization (ISO) and by the International Electro-technical Commission (IEC), titled Information technology – Security techniques – Code of practice for information security controls. What is the difference between ISO 27001 and 27002? ISO/IEC 27002:2013 gives guidelines for organizational information security standards and information security management practices. It is a document that offers in-depth guidance on how to implement ISO 27001 standards. So, an organization cannot get Certification for ISO 27002. How much time does it take to get a Certification?  On average, this Certification takes 8 to 9 months to implement. What is GDPR? The General Data Protection Regulation (EU) 2016/679 (“GDPR”) is a regulation in EU law on data protection and privacy for all individuals within the European Union (EU) and the European Economic Area (EEA). It also addresses the export of personal data outside the EU and EEA areas. Can we get ISO 27001 Certification without having ISO 9001?  Yes, We can obtain it without ISO 9001. Is it only for IT Department? NO, Security is everyone’s job! Every organization needs to protect its sensitive data. Risks are identified, and Risk Treatment Plan is implemented to prevent data loss. Integration for Customer Feedback? An integrated system means a company can efficiently manage the quality of its services, handle customer feedback and solve problems while keeping information safe. Would you mind sending an Enquiry so we can assist you in getting certified? Send Enquiry
__label__pos
0.603339
Logs API Overview The SigNoz Logs API is a robust interface which enables developers to manage and analyze log data efficiently. This API facilitates various operations: • Searching Logs: Allows users to search through log data based on specific criteria. For example, finding all logs where the error code is 500. • Paginating Logs: Helps in navigating through large sets of log data in a manageable way. For instance, retrieving logs in batches of 100 for easy viewing. • Aggregating Logs: Enables summarizing log data to extract meaningful insights, such as aggregating logs to count the number of errors per day. API Endpoint Endpoint for Logs API: POST https://{URL}/api/v3/query_range Replace {URL} with your instance URL, e.g., example.signoz.io. Prerequisites Access Token: To access this API, you need an Access Token. Navigate to the Settings page in the SigNoz UI and create a new Access Token. image Access Tokens can only be created/managed by users with the Admin role. If you don't have the Admin role, contact your organization's admin to create an Access Token for you. Authentication Using the Access Token: Add the Access token to your request header as follows: SIGNOZ-API-KEY:{YOUR_ACCESS_TOKEN} 💡 Tip Secure storage and handling of your Access Token is crucial to prevent unauthorized access.
__label__pos
0.842725
logo Ask Questions, Get Answers X   Home  >>  TN XII Math  >>  Vector Algebra If $\overrightarrow{a}=\overrightarrow{i}+\overrightarrow{3j}-\overrightarrow{2k}$ and $\overrightarrow{b}=\overrightarrow{-i}+\overrightarrow{3k}$ than find $\overrightarrow{a}\times\overrightarrow{b}$. Verify that $\overrightarrow{a}$ and $\overrightarrow{b}$ are perpendicular to$\overrightarrow{a}\times\overrightarrow{b}$ separately. 1 Answer Toolbox: • $ \overrightarrow a.\overrightarrow b=| \overrightarrow a|| \overrightarrow b| \cos \theta$ $ \therefore \cos \theta = \large\frac{ \overrightarrow a. \overrightarrow b}{| \overrightarrow a|| \overrightarrow b|} \Rightarrow \theta = \cos^{-1} \large\frac{ \overrightarrow a. \overrightarrow b}{| \overrightarrow a|| \overrightarrow b|}$ • If $ \overrightarrow a = a_1\overrightarrow i+a_2\overrightarrow j+a_3\overrightarrow k, \: \overrightarrow b = b_1\overrightarrow i+b_2\overrightarrow j+b_3\overrightarrow k$ then $ \overrightarrow a$ x $ \overrightarrow b = \begin{vmatrix} \overrightarrow i & \overrightarrow j & \overrightarrow k \\ a_1 & a_2 & a_3 \\ b_1 & b_2 & b_3 \end{vmatrix}$ Step 1 $ \overrightarrow a = \overrightarrow i+3\overrightarrow j-2\overrightarrow k\: \: \: \overrightarrow b = -\overrightarrow i+3\overrightarrow k$ $ \overrightarrow a \times \overrightarrow b = \begin{vmatrix} \overrightarrow i & \overrightarrow j & \overrightarrow k \\ 1 & 3 & -2 \\ -1 & 0 & 3 \end{vmatrix} = (9-0)\overrightarrow i-(3-2)\overrightarrow j+(0+3)\overrightarrow k$ $ = 9\overrightarrow i-\overrightarrow j+3\overrightarrow k$ Step 2 $ \overrightarrow a.(\overrightarrow a \times \overrightarrow b) =(\overrightarrow i+3\overrightarrow j-2\overrightarrow k).(9\overrightarrow i-\overrightarrow j+3\overrightarrow k)$ $ = (1)(9)+(3)(-1)+(-2)(3)$ $=9-3-6=0$ $ \overrightarrow b.(\overrightarrow a \times \overrightarrow b) = (-\overrightarrow i+3\overrightarrow k).(9\overrightarrow i-\overrightarrow j+3\overrightarrow k)$ $ = (-1)(9)+(3)(3)=-9+9=0$ Since $ \overrightarrow a.( \overrightarrow a \times \overrightarrow b)=0\: and \: \overrightarrow b.(\overrightarrow a \times \overrightarrow b)=0$ it is verified that $ \overrightarrow a\: and \: \overrightarrow a \times \overrightarrow b, \: and \: \overrightarrow b \: and \: \overrightarrow a \times \overrightarrow b\: are \perp$ answered Jun 5, 2013 by thanvigandhi_1   Related questions Download clay6 mobile appDownload clay6 mobile app ... X
__label__pos
0.999893