source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0003829542.txt" ]
Q: How to make a cross domain AJAX POST call from a Sharepoint Webpart? I need to call a (HTTP) REST API as as POST call - basically, it allows me to post a message to a forum/community. Since, there is currently no way of authenticating over the API, I need to depend on browser cookies. ie, have the user logged in to the community and then use the API calls. This means, server proxies are ruled out. And because its a POST call, JSONP is also ruled out, even if it were supported by the API's server. So this POST call needs to be 100% javascript. This JS will end up being part of a Webpart in Sharepoint so I don't really want to complicate it with iframes. Well? A: The only way to do a cross-domain POST is to script a form: <iframe name="iframe"></iframe> <form id="foo" target="iframe" method="POST" action="http://..."> <input type="hidden" name="parameter 1" value="bar"/> ... </form> <script type="text/javascript"> ... document.getElementById('foo').submit(); </script> You won't be able to read the response in the iframe due to the Same Origin Policy, but the POST will be made. Any forum that knows what it's doing will reject this request. Otherwise, anyone who visited a third-party site could be made to automatically post to the forum against their will. This is known as cross-site request forgery (XSRF) and is a perennial web security problem. Most forum administrators would consider the above code hostile. Secure forums use an ‘anti-XSRF’ per-action token to prevent the above, essentially requiring that postings be made from the form on the site itself and not from a third-party site. Since you can't read the document included cross-domain, you can't pinch the token so can't authorise a post.
[ "stackoverflow", "0008521885.txt" ]
Q: Break down a row into multiple rows using bitfield column in MySQL I have a bitfield called warnings stored as an int. I would like to get a list of warnings for each person lets say we have a table NAME, WARNINGS alex, 0 mike, 5 sarah, 2 where each bit of the integer corresponds to a warning # (bit position). This is currently done in perl with a for loop for(my $i=0; $i < $warning_size;$i++ ){ if( (1 << $i ) & $warning != 0){ print "$name\t" . $i+1 ."\n"; } } Is there any way that I can have this handled by a mysql query. For the above example, I would like the following output: name, warning ------------- mike 1 mike 3 sarah 2 I am trying to get this down to one select statement, Thanks A: Try this one - CREATE TABLE warn_bits( b INT(11) NOT NULL ); INSERT INTO warn_bits VALUES (1), (2), (3), (4), (5), (6), (7), (8); SELECT w.name, wb.b FROM warnings w JOIN warn_bits wb ON ((w.WARNINGS >> wb.b - 1) & 1) > 0 ORDER BY w.name, wb.b; +-------+---+ | name | b | +-------+---+ | mike | 1 | | mike | 3 | | sarah | 2 | +-------+---+ You may extend warn_bits table to support INT or BIGINT numbers. Edit2 SELECT w.name, wb.b FROM warnings w JOIN ( SELECT 1 b UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 ) wb ON ((w.WARNINGS >> wb.b - 1) & 1) > 0 ORDER BY w.name, wb.b;
[ "stackoverflow", "0029294691.txt" ]
Q: ASP.NET MVC Htmlhelper htmlAttributes doesnt work When I user this targ on a page like: @Html.TextBoxFor(model => model.JobName, new { @class = "form-control" }) It can work, But when I use like this: @Html.TextBoxFor(model => model.JobName, new { @data-provide="typeahead", }) then it can't work, because this attribute: data-provide, it have a symbol which is '-', how I can solve this problem? A: You need to use the underscore character (the helper will translate this correctly and generate data-provide="typeahead") @Html.TextBoxFor(model => model.JobName, new { data_provide="typeahead", })
[ "stackoverflow", "0058988483.txt" ]
Q: Gremlin Python: Count vertices and its children in one query I am trying to get the count of all vertices with a particular label and all its children in one query like so: g.V().hasLabel('folder').has('folder_name', 'root').as_('a', 'b').select('a', 'b').by(__.count()).by(__.in_('items_belongs_to_folder').count()).toList() This should ideally return [{a: 200, b: 400}], but I am instead getting a list like so: [{a: 1, b: 0},{a: 1, b: 0},{a: 1, b: 0},{a: 1, b: 0},{a: 1, b: 0},{a: 1, b: 0},{a: 1, b: 0},....{a: 1, b: 0}] How exactly can I achieve the desired result? gremlinpython: 3.4.4 (latest) Python 3.7 graph database: AWS Neptune A: You can try: g.V().hasLabel('folder').has('folder_name', 'root').fold() .project('a', 'b') .by(count(local)) .by(unfold().in_('items_belongs_to_folder').count())
[ "stackoverflow", "0053622892.txt" ]
Q: Display items over image I have the following code on codepen page. (included for code-running purposes - doesn't work in the snippet) The goal is be able display the <div class="item__boxes"> element at the bottom of the <div class="item">. Question How would I display the <div class="item__boxes"> element at the bottom of the <div class="item">? Goal: As the height of the <div class="item__text"> increases due to content inside of it, there should always be some padding/margin between the text and the <div class="item__boxes">. <div class="item__boxes"> should always display at the bottom of the <div class="item"> element regardless of breakpoint. Current Issue Desired output Code .item { position: relative; } .item__wrapper { max-width: 50%; position: relative; } .item__img img { width: 100% !important; } .item__text { position: absolute; background: rgba(238, 238, 238, 0.5); padding: 64px; top: 0; right: 0; bottom: 0; left: 0; z-index: 5; display: flex; flex-direction: column; justify-content: center; } .item__boxes { background-color: #ccc; display: flex; position: absolute; bottom: 0; } .col-padding { padding: 16px; } .col-m-12 { width: 100%; } @media (min-width: 1024px) { .col-t-6 { width: 50%; } } <div class="item__wrapper"> <div class="item"> <div class="item__img"> <picture> <source media="(min-width: 1300px)" srcset="https://placeimg.com/1000/480/nature"> <source media="(min-width: 1024px)" srcset="https://placeimg.com/960/480/nature"> <img src="https://placeimg.com/640/480/nature" alt="Flowers" style="width:auto;"> </picture> </div> <div class="item__text"> <h3>Some title</h3> <p>Efficiently communicate sticky quality vectors after compelling growth strategies. Compellingly scale future-proof content rather than enterprise users. Uniquely build scalable applications vis-a-vis performance based functionalities. Monotonectally procrastinate. Compellingly scale future-proof content rather than enterprise users. Uniquely build scalable applications vis-a-vis performance based functionalities. Monotonectally procrastinate.</p> </div> </div> <div class="item__boxes"> <div class="col-m-12 col-t-6 col-padding"> <div>Some Title</div> <div>Enthusiastically incubate diverse initiatives without multifunctional strategic theme areas.</div> </div> <div class="col-m-12 col-t-6 col-padding"> <div>Globally Title</div> <div>Globally impact integrated infomediaries via seamless mindshare. </div> </div> <div class="col-m-12 col-t-6 col-padding"> <div>Distinctively Title</div> <div>Distinctively strategize long-term high-impact ideas whereas client-centered leadership skills.</div> </div> </div> </div> A: I played about with your code. In order for there to be always some padding no matter how wide, you'll have to use relative positioning on the text and absolutely position the image. As-is the padding-bottom will vary depending on how wide it is, I recommend you include the image as a background-image and set the size of the background-image to cover in the css, this way there will be no gap, no matter how wide/narrow/tall/short your screen is. I tried out the given code at 80% width, and set the padding to 33% (I didn't put the background image code in) At 50%, your initial width, there was no bottom padding required. The snippet code won't run because of the css structure but I'm including it anyway for future reference. Here is a codepen link, and a second one Hope this helps .item { position: relative; &__wrapper { max-width: 50%; position: relative; min-height: 100vh; } &__img { img { top: 0px; position: absolute; width: 100%!important; } } &__text { top: 0px; position: relative; min-height: 100vh; background: rgba(238, 238, 238, 0.5); padding-right: 50px; padding-left: 50px; padding-top: 30px; //padding-bottom:33vh at 80%; z-index: 0; display: flex; flex-direction: column; align-items: top; justify-content: center; } &__boxes { background-color: #ccc; display: flex; position: relative; bottom: 0px; } } .col { &-padding { padding: 16px 16px 5px 16px; } &-m-12 { width: 100%; } } @media (min-width: 1024px) { .col { &-t-6 { width: 50%; } } } <div class="item__wrapper"> <div class="item"> <div class="item__img"> <picture> <source media="(min-width: 1300px)" srcset="https://placeimg.com/1000/480/nature"> <source media="(min-width: 1024px)" srcset="https://placeimg.com/960/480/nature"> <img src="https://placeimg.com/640/480/nature" alt="Flowers" style="width:auto;"> </picture> </div> <div class="item__text"> <h3>Some title</h3> <p>Efficiently communicate sticky quality vectors after compelling growth strategies. Compellingly scale future-proof content rather than enterprise users. Uniquely build scalable applications vis-a-vis performance based functionalities. Monotonectally procrastinate. Compellingly scale future-proof content rather than enterprise users. Uniquely build scalable applications vis-a-vis performance based functionalities. Monotonectally procrastinate.</p> </div> </div> <div class="item__boxes"> <div class="col-m-12 col-t-6 col-padding"> <div>Some Title</div> <div>Enthusiastically incubate diverse initiatives without multifunctional strategic theme areas.</div> </div> <div class="col-m-12 col-t-6 col-padding"> <div>Globally Title</div> <div>Globally impact integrated infomediaries via seamless mindshare. </div> </div> <div class="col-m-12 col-t-6 col-padding"> <div>Distinctively Title</div> <div>Distinctively strategize long-term high-impact ideas whereas client-centered leadership skills.</div> </div> </div> </div>
[ "stackoverflow", "0041356509.txt" ]
Q: com.microsoft.sqlserver.jdbc.sqlserverexception:the column name count(pr) is not valid I am using sql server and when i write this sql select statement it runs well when i use it in netbean it show error com.microsoft.sqlserver.jdbc.sqlserverexception:the column name count(pr) is not valid i write code below can any one help me try{ String sql="SELECT count(status) from Sub_Data"; pst=conn.prepareStatement(sql); rs=pst.executeQuery(); if(rs.next()){ String count4=rs.getString("count(status)"); totall111.setText(count4); } catch(Exception e){ JOptionPane.showMessageDialog(null, e ); } A: either change it to SELECT count(status) as c from Sub_Data ... rs.getInt ("c"); or just use the columnIndex rs.getInt (1); Edit count would return an Int not a String
[ "stackoverflow", "0025088367.txt" ]
Q: How to use Core Data's ManagedObjectModel inside a framework? I'm trying to migrate a specific part of one of my apps into a framework so that I can use it in my app itself and in one of those fancy new iOS 8 widgets. This part is the one that handles all my data in Core Data. It's pretty straight forward to move everything over and to access it. I'm just having trouble accessing my momd file in there. When creating the NSManagedObjectModel I still try to load the momd as illustrated in Apple's code templates: NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"MyApp" withExtension:@"momd"]; __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; Unfortunately, modelURL stays nil and thus MyApp crashes when accessing the Core Data stack with this error: 2014-08-01 22:39:56.885 MyApp[81375:7417914] Cannot create an NSPersistentStoreCoordinator with a nil model 2014-08-01 22:39:56.903 MyApp[81375:7417914] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Cannot create an NSPersistentStoreCoordinator with a nil model' So, what's the right way to do this when working inside a framework with Core Data? A: I'm a bit late for flohei's issue, but hopefully this helps anybody else who wanders by. It is possible to get this to work without having to perform script-fu to copy resources around! By default Apple's Core Data template gives you something like this: lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource("MyCuteCoreDataModel", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() That would load your Core Data resources out of the main bundle. The key thing here is: if the Core Data model is loaded in a framework, the .momd file is in that framework's bundle. So instead we just do this: lazy var managedObjectModel: NSManagedObjectModel = { let sexyFrameworkBundleIdentifier = "com.heybaby.xxx" let customKitBundle = NSBundle(identifier: sexyFrameworkBundleIdentifier)! let modelURL = customKitBundle.URLForResource("MyCuteCoreDataModel", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() That should get you up and running. Credit: https://www.andrewcbancroft.com/2015/08/25/sharing-a-core-data-model-with-a-swift-framework/ A: You need to drag the xcdatamodeld file and drop it in the Build Phases | Compile Sources for the targets that use the framework. Then when the target runs its [NSBundle mainBundle] will contain the model (momd file). A: @Ric Santos was almost there. I think you just need to make it an "mom" extension rather than "momd", then it will run. lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle(forClass: self.dynamicType.self).URLForResource(self.dataModelName, withExtension: "mom")! return NSManagedObjectModel(contentsOfURL: modelURL)! }()
[ "stackoverflow", "0017113901.txt" ]
Q: How can I derive a class that has a constructor that takes some arguments? How can I derive a class that has a constructor that takes some arguments? //The construction in base class: BaseClass::BaseClass(int inArgument) : m_args (inArgument) // where m_args is a public/protected member of the base class { } //The construction of derived class: DerivedClass::DerivedClass(int inArgument) : m_args (inArgument) // where m_args is a public/protected member of the derived class { } after compiling I get: Error 1 error C2512: 'BaseClass' : no appropriate default constructor available I am a beginner c++ programmer... A: Just forward the argument to the constructor of the base class: DerivedClass::DerivedClass(int inArgument) : BaseClass(inArgument) // ^^^^^^^^^^^^^^^^^^^^^^^ { }
[ "stats.stackexchange", "0000108901.txt" ]
Q: Difference between Factorization machines and Matrix Factorization? I came across the term Factorization Machines in recommender systems. I know what Matrix Factorization is for recommender systems but never heard of Factorization Machines. So what's the difference? A: Matrix factorization is a method to, well, factorize matrices. It does one job of decomposing a matrix into two matrices such that their product closely matches the original matrix. But Factorization Machines are quite general in nature compared to Matrix Factorization. The problem formulation itself is very different. It is formulated as a linear model, with interactions between features as additional parameters. This feature interaction is done in their latent space representation instead of their plain format. So along with the feature interactions like in Matrix Factorization, it also takes the linear weights of different features. So compared to Matrix Factorization, here are key differences: In recommended systems, where Matrix Factorization is generally used, we cannot use side-features. Ex for a movie recommendation system, we cannot use the movie genres, its language etc in Matrix Factorization. The factorization itself has to learn these from the existing interactions. But we can pass this info in Factorization Machines Factorization Machines can also be used for other prediction tasks such as Regression and Binary Classification. This is usually not the case with Matrix Factorization The paper shared in previous answer is the original paper that talks about FMs. It has great illustrative example too as to what FM exactly is. A: Matrix factorization is a different factorization model. From the article about FM: There are many different factorization models like matrix factorization, parallel factor analysis or specialized models like SVD++, PITF or FPMC. The drawback of these models is that they are not applicable for general prediction tasks, but work only with special input data. Furthermore their model equations and optimization algorithms are derived individually for each task. We show that FMs can mimic these models just by specifying the input data (i.e. the feature vectors). This makes FMs easily applicable even for users without expert knowledge in factorization models. From libfm.org: "Factorization machines (FM) are a generic approach that allows to mimic most factorization models by feature engineering. This way, factorization machines combine the generality of feature engineering with the superiority of factorization models in estimating interactions between categorical variables of large domain." A: Just some extension to Dileep's answer. If the only features involved are two categorical variables (e.g. users and items) then FM is equivalent to the matrix factorization model. But FM can be easily applied to more than two and real valued features.
[ "stackoverflow", "0011178785.txt" ]
Q: Cannot figure out the error in simple PHP/MySQL "Q&A" DB I'm creating a simple questions DB, here are some details to start: 1st off, I am not using PDO - it's an old webapp, and this question is not about upgrading to PDO. The DB CREATE TABLE IF NOT EXISTS `questions` ( `id` int(11) unsigned NOT NULL auto_increment, `question` varchar(255) NOT NULL, `userID` int(11) unsigned NOT NULL, `active` tinyint(1) NOT NULL default '1', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; Already inside the DB: INSERT INTO `apl_questions` (`id`, `question`, `userID`, `active`) VALUES (1, 'Do you have a dog?', 1, 1), (2, 'Have you ever been arrested?', 1, 1), (3, 'Pick yes or no...', 1, 1); The PHP $questionsResult = mysql_query("select * from questions where userID = 1 AND active = 1"); // Get all activated questions if(mysql_num_rows($questionsResult) > 0){ $questions = mysql_fetch_assoc($questionsResult); var_dump($questions); } The RESULT (of the PHP) array(4) { ["id"]=> string(1) "1" ["question"]=> string(18) "Do you have a dog?" ["userID"]=> string(1) "1" ["active"]=> string(1) "1" } As you can see, this is only grabbing the first row - when it should be grabbing all rows since the userID and "active" column of all 3 rows are 1. Anyone see anything here that could be causing this problem? If I put the query into PHP MyAdmin, the query works correctly - so I have to assume at this point that it's the PHP... This is blowing my mind! Thanks. A: It seems mysql_fetch_assoc is row fetching, opposite to bulk fetching, which means it will fetch row per row inside a given array. You have to loop over, for example in the php page: while ($row = mysql_fetch_assoc($result)) { echo $row["userid"]; echo $row["fullname"]; echo $row["userstatus"]; } rgds.
[ "stackoverflow", "0045565610.txt" ]
Q: Get Firebase storage Object on a database-triggered cloud function I want to generate a thumb image when a record is added to the database. On the Firebase website they have some examples but they are all based on a storage trigger instead of a database trigger: Image database object: image: { name: abc123, raw: download url abc123 } - firebase thumb generator example (storage triggered): exports.generateThumbnail = functions.storage.object().onChange(event => { const object = event.data; // The Storage object. const fileBucket = object.bucket; // The Storage bucket that contains the file. const filePath = object.name; // File path in the bucket. const contentType = object.contentType; // File content type. const resourceState = object.resourceState; // The resourceState is 'exists' or 'not_exists' (for file/folder deletions). const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1. // Exit if this is triggered on a file that is not an image. if (!contentType.startsWith('image/')) { console.log('This is not an image.'); return; } // Get the file name. const fileName = path.basename(filePath); // Exit if the image is already a thumbnail. if (fileName.startsWith('thumb_')) { console.log('Already a Thumbnail.'); return; } // Exit if this is a move or deletion event. if (resourceState === 'not_exists') { console.log('This is a deletion event.'); return; } // Exit if file exists but is not new and is only being triggered // because of a metadata change. if (resourceState === 'exists' && metageneration > 1) { console.log('This is a metadata change event.'); return; } // Download file from bucket. const bucket = gcs.bucket(fileBucket); const metadata = { contentType: contentType }; // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail. const thumbFileName = `thumb_${fileName}`; const thumbFilePath = path.join(path.dirname(filePath), thumbFileName); // Create write stream for uploading thumbnail const thumbnailUploadStream = bucket.file(thumbFilePath).createWriteStream({metadata}); // Create Sharp pipeline for resizing the image and use pipe to read from bucket read stream const pipeline = sharp(); pipeline .resize(THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT) .max() .pipe(thumbnailUploadStream); bucket.file(filePath).createReadStream().pipe(pipeline); const streamAsPromise = new Promise((resolve, reject) => thumbnailUploadStream.on('finish', resolve).on('error', reject)); return streamAsPromise.then(() => { console.log('Thumbnail created successfully'); }); }); - How I want it to work (database triggered): The database trigger event does not have a storage object. How can I access the storage object? When a thumbnail is created successfully I want to add the donwloadUrl of the thumb image to the database exports.generateThumbnail = functions.database.ref('/data/{dataID}/childData/{childDataID}/image/name').onCreate(event => { const object = event.data; // This Storage object does not work when using a database trigger so how do I access the same storage object, I have the image name? //thumb generator code... return streamAsPromise.then(() => { console.log('Thumbnail created successfully'); //add thumb image download url back to the database }); }); - image: { name: abc123, raw: download url abc123 thumb: download url thumb_abc123 //added after thumb is created } A: This is how I got it to work. Add cloud storage to your project. If you want to retrieve the image signed url like I do, add projectId and keyFilename to you cloud storage reference const gcs = require('@google-cloud/storage')({ projectId: 'name-1234', keyFilename: './keyfile.json' }); generateThumbnail function exports.generateThumbnail = functions.database.ref('/data/${dataID}/childData/${childDataID/image/name').onCreate(image => { const dataID = image.params.dataID const childDataID = image.params.childDataID const fileName = image.data.val() //get your project storage bucket id const storageBucket = functions.config().firebase.storageBucket //path to image const imagePath = `${dataID}/${childDataID}` //open bucket const bucket = gcs.bucket(storageBucket) //location of the image in the bucket const object = bucket.file(imagePath) const fileBucket = object.bucket; // The Storage bucket that contains the file. const filePath = object.name; // File path in the bucket. const metadata = { contentType: 'image/jpeg' }; // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail. const thumbFileName = `thumb_${fileName}`; const thumbFilePath = path.join(path.dirname(filePath), thumbFileName); // Create write stream for uploading thumbnail const thumbnailUploadStream = bucket.file(thumbFilePath).createWriteStream({metadata}); // Create Sharp pipeline for resizing the image and use pipe to read from bucket read stream const pipeline = sharp(); pipeline .resize(400, 400) .max() .pipe(thumbnailUploadStream); bucket.file(filePath).createReadStream().pipe(pipeline); const streamAsPromise = new Promise((resolve, reject) => thumbnailUploadStream.on('finish', resolve).on('error', reject)); return streamAsPromise.then(() => { console.log('Thumbnail created successfully'); var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! const yyyy = today.getFullYear() + 5; // add a few years if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } today = mm + '-' + dd + '-' + yyyy; bucket.file(filePath).getSignedUrl({ action: 'read', expires: today }, function(err, url) { if (err) { console.error(err); return; } //add thumb image url to message (in database) return admin.database().ref(`/${dataID}/childData/${childDataID}`).child('image').update({ thumb: url }) }); }); })
[ "stackoverflow", "0053398303.txt" ]
Q: recursive formula which gives number of permutations? Is there any recursive formula which gives number of permutations each of which can be reduced to ordered permutation by certain number of flips for n pancakes by using pancake sort algorithm? A: I do not have a proof, but would be willing to bet a large sum of money that there is not such, unless you restrict the number of flips to be small. There is no trouble recursively counting how many ways of performing the flipping operations there are. The challenge is in figuring out how many other ways there are to arrive at the same order with a different sequence of flips. In fact per https://en.wikipedia.org/wiki/Pancake_sorting#The_pancake_problems, finding the shortest sequence of flips to arrive at a particular order is NP-hard. Which means that if you have more than a few flips, the appropriate expressions to identify when there was another will have a combinatorial explosion. If you want permutations that can be undone by the selection sort algorithm in n steps, there is a way to calculate it recursively in a way that is suited to dynamic programming. Let f(n, m, on_top) be the number of permutations that can be solved in n steps, with m being the largest one out of place, and on_top is a variable that says whether the largest one out of place is on top of the stack. As a special case we'll say that f(0, 0, True) = 1 representing the sorted stack requiring no sorting. Now our recursive rules are as follows: Base case: f(0, 0, True) = 1 Second base case: if 0 < n then f(n, 0, False) = f(n, 0, True) = 0 Third base case: if 0 < m then f(0, m, True) = f(0, m, False) = 0 Case where we will put the largest on top: f(n, m, False) = (m-2) * f(n-1, m, True). The reason why it is this is that the mth pancake must be in the top m-1 locations because it is out of place and nothing larger is displaced. But it can't be on top because then the last argument would be True and it is not. So that gives m-2 possible flips we would have to do. Case where we will put the largest in its place: f(n, m, True) = sum over i < m of (f(n-1, i, False) + f(n-1, i, True)). Which is just that we flip to put the largest in its place, and then come up with the next largest out of place. This is enough to allow us to write a recursive function that will calculate the answer. Unfortunately calculating that function naively will involve a lot of repeated calls. However if we memoize this function by saving the value you get for a set of parameters and returning it again the next time, then you'll short-circuit most of the calculation and evaluating this will only take a polynomial amount of work.
[ "wordpress.stackexchange", "0000326229.txt" ]
Q: delete_published_posts does not work I made a plugin with a custom post type calls "product". For some reasons, the administrator cannot move to trash post inside the list table. I know the capability to do that is delete_published_posts. I checked all capabilities for the administrator on the right page like this : $user = wp_get_current_user(); pretty_var_dump( $user->allcaps ); array ( 'switch_themes' => true, 'edit_themes' => true, 'activate_plugins' => true, 'edit_plugins' => true, 'edit_users' => true, 'edit_files' => true, 'manage_options' => true, 'moderate_comments' => true, 'manage_categories' => true, 'manage_links' => true, 'upload_files' => true, 'import' => true, 'unfiltered_html' => true, 'edit_posts' => true, 'edit_others_posts' => true, 'edit_published_posts' => true, 'publish_posts' => true, 'edit_pages' => true, 'read' => true, 'level_10' => true, 'level_9' => true, 'level_8' => true, 'level_7' => true, 'level_6' => true, 'level_5' => true, 'level_4' => true, 'level_3' => true, 'level_2' => true, 'level_1' => true, 'level_0' => true, 'edit_others_pages' => true, 'edit_published_pages' => true, 'publish_pages' => true, 'delete_pages' => true, 'delete_others_pages' => true, 'delete_published_pages' => true, 'delete_posts' => true, 'delete_others_posts' => true, 'delete_published_posts' => true, 'delete_private_posts' => true, 'edit_private_posts' => true, 'read_private_posts' => true, 'delete_private_pages' => true, 'edit_private_pages' => true, 'read_private_pages' => true, 'delete_users' => true, 'create_users' => true, 'unfiltered_upload' => true, 'edit_dashboard' => true, 'update_plugins' => true, 'delete_plugins' => true, 'install_plugins' => true, 'update_themes' => true, 'install_themes' => true, 'update_core' => true, 'list_users' => true, 'remove_users' => true, 'promote_users' => true, 'edit_theme_options' => true, 'delete_themes' => true, 'export' => true, 'edit_product' => true, 'read_product' => true, 'delete_product' => true, 'edit_products' => true, 'edit_others_products' => true, 'publish_products' => true, 'read_private_products' => true, 'create_products' => true, 'edit_post' => true, 'delete_private_products' => true, 'delete_published_products' => true, //<-- ?! 'delete_others_products' => true, 'edit_private_products' => true, 'edit_published_products' => true, 'administrator' => true, ) So, I don´t know why it does not work. Someone has got an idea ? A: What I need to see was the posts were draft, I had to add the capabilty delete_posts.
[ "stackoverflow", "0053746198.txt" ]
Q: NiFi - Control de order merging two dataflows with EnforceOrder and MergeContent processor I am trying to use the EnforceOrder processor to do a Merge in a determinate order. To do so, this is my flow: In the updateAttribute, I am generating an attribute to set order I want in the merge. On the one of the left, I am setting the value '1' and on the other, I am setting the value of '2'. And then the configuration of the EnforceOrder is the nextone: The problem is that only arrives the flow of the process.order = 1 and is not taking out the number 2. What am I doing wrong? Cheers A: Use EnforceOrder processor to control the order of flowfiles reaching to MergeContent processor. using UpdateAttribute processor add the sequence number to the flowfile. Example: Consider 2 flowfiles, Flowfile-2(this content will need to showup first) will have lower sequence number compared to flowfile1 then feed the success connection to MergeContent processor, By using enforceorder processor we are making sure flowfile2 will be going to Mergecontent processor before flowfile1. Please refer to this and use the enforce-order template to get familiar with the enforce order processor. UPDATE: I think the issue is with the EnforceOrder configs, Group Identifier is configured as ${filename} so if you have two different filenames then processor doesn't wait for both of them. To fix this Keep common attribute in UpdateAttribute processors like group_name as gn then use same attribute name in Group Identifier property value as ${group_name} Connect Skipped and Wait connections to EnforceOrder processor it self. UpdateAttributeConfigs: EnforceOrderConfigs: Please use this template as reference and upload it to your NiFi instance check out how the flow has been running.
[ "stackoverflow", "0032297014.txt" ]
Q: iPad margin have an empty space in left and right I wrote a universal application and I am using size classes and auto layout . Everything seems good in iPhone but when I run it on iPad there are free spaces on the left and right margins, I don't know why they appear!!! A: Check the details of your constraints. If you use "Margin" in First Item, select that. After that, uncheck "Relative to Margin".
[ "stackoverflow", "0021167118.txt" ]
Q: PHP support in Glassfish 4 I have read in some blog comment that newer versions of glassfish has inbuilt PHP support, is this true? I am using Glassfish 4 and trying to make wordpress work on it. For this I am trying to use quercus from http://quercus.caucho.com/ but things does seems to work right. I have submitted a question for the same Exception: WELD-000071 Managed bean class com.caucho.jms.MemoryQueue must be @Dependent while installing Quercus on Glassfish If glassfish 4 has inbuilt PHP support then I do not need to use quercus. If its true, please guide me how to set up a PHP website in glassfish A: GlassFish 4 does not have built-in PHP support, nor are there plans to add PHP support in the future.
[ "math.stackexchange", "0003061025.txt" ]
Q: Can You Have 2 Numerical, Identical Values To Represent the nth Percentile? For an assignment, I am required to find the value of a piece of data in the 70th percentile using mean and standard deviation. Here is my organized data in ascending order: 0, 1, -4, 0, -3, 0, -4, -2, 0, 1, -1, 2, 0, -4, 5, -2, 0, 3, -3, 0. The image link attached below called 'Percentiles With Normal Distribution' is the work I have done to find the value. (For some reason I can`t seem to upload the actual image here...) Percentiles with Normal Distribution Just in case you cannot access the image, I will explain what I did. I created the normal distribution graph and shaded approximately 70% of it, leaving a little part on the right side empty. I am finding b, where P(X > b) = p, where p = 0.7. I reversed this and it is now P(X > b) = 1 - p (where p = 0.7). This means to find the (1-p)Th percentile for X. Next, I found the corresponding percentile for Z by looking in the body of the Z-Score Table, and finding the probability that is closest to p = 0.7, to which I did this: (1-0.7) = 0.3 so the closest value to this is 0.3015, which falls under row = -0.5 and column = 0.02. This means the 70th percentile for Z is equal to -0.52. Lastly, I just changed the Z-Score value back into an x-value (original units). x = Mean + Z(Standard Deviation). I substiuted my mean value of -0.55, Z-Score value of -0.52, and standard deviation of 2.4 and solved for x. x = -2. Now, if you look at the organized data set I provided above, youd see that there are two -2s. This is confusing me because I`m not sure whether there can be two numerical values to represent the value of a certain percentile. A: Three points: If you look at your picture, you want $+0.52$ for the $70$th percentile of a standard normal distribution, but you used $-0.52$ which in fact corresponds to the $30$th percentile. Correcting this would have given you about $0.7$ rather than $-1.8$ There is no problem with a percentile corresponding to a value from the sample which happens multiple times. For example with the data 3, 5, 5, 5, 7 it is obvious that the $50$th percentile or median is $5$ I am not sure why you need to fit a normal distribution unless it is to fit the question's "using mean and standard deviation". As an alternative, sorting your $20$ data points to -4, -4, -4, -3, -3, -2, -2, -1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 5, you have $25\%$ of the values below $-2$ and $65\%$ of the values above $-2$ so you could say $-2$ is the $30$th percentile. Similarly you have $40\%$ of the values below $0$ and $25\%$ above $0$ so you could say $0$ is the $70$th percentile.
[ "stackoverflow", "0039959506.txt" ]
Q: CSS Animation changes the element position I have a hexagon inside a circle. See the initial scenario: https://jsfiddle.net/njzwfvpf/ Now I want to add an animation rotating the hexagon 360deg inside the circle This is the existing scenario with the css animation (fiddle here): .rotate { -webkit-animation: rotating 3s cubic-bezier(0, 0, 1, 1) infinite alternate; animation: rotating 3s cubic-bezier(0, 0, 1, 1) infinite alternate; -webkit-transform-origin: 50% 50%; transform-origin: 50% 50%; } @-webkit-keyframes rotating { 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } <svg width="350" height="350"> <svg width="350" height="350"> <circle cx="230.00591443779982" cy="155.55555555555554" r="45" style="stroke: rgb(158, 157, 158); stroke-width: 1; fill: none;"></circle> <circle cx="100" cy="155.55555555555554" r="45" style="stroke: rgb(158, 157, 158); stroke-width: 1; fill: none;"></circle> <circle cx="180.41237113402062" cy="155.55555555555554" r="50" style="stroke: rgb(158, 157, 158); stroke-width: 1; fill: none;"></circle> <circle cx="165.0943396226415" cy="120.27491408934708" r="45" style="stroke: rgb(158, 157, 158); stroke-width: 1; fill: none;"></circle> <circle cx="165.0943396226415" cy="200" r="45" style="stroke: rgb(158, 157, 158); stroke-width: 1; fill: none;"></circle> <svg viewBox="0 0 600 720" width="295" height="205"> <g transform="translate(239, 370)" class="rotate"> <path></path> <path d="M 175 0 L 326.55444566227675 87.50000000000001 L 326.55444566227675 262.5 L 175 350 L 23.445554337723223 262.5 L 23.44555433772325 87.49999999999999" style="opacity: 0.4; fill: black;"></path> </g> <svg viewBox="0 0 600 720" width="507.4" height="799.5"> <g transform="translate(105, 395)"> <path d="M 175 0 L 341.43489035165186 120.9220259843842 L 277.8624191511828 316.57797401561584 L 72.13758084881722 316.57797401561584 L 8.565109648348141 120.92202598438415" style="opacity: 0.4; fill: black;"></path> </g> </svg> </svg> </svg> </svg> The problem is that adding the animation the Hexagon changes its position, it is not inside the circle nanymore. What am I doing wrong ? How can I fix it? A: The issue you are facing is that you are applying a transform with CSS (rotate(360deg)) while you already have a transform on the same element in the SVG (translate(239, 370)). You can solve this with 2 approaches : apply all the transforms with CSS so you can control the animation with CSS apply the CSS animation on the child element (the hexagon) Here is an example of how you can solve it with the second approach : .rotate { -webkit-animation: rotating 3s cubic-bezier(0, 0, 1, 1) infinite alternate; animation: rotating 3s cubic-bezier(0, 0, 1, 1) infinite alternate; -webkit-transform-origin: 50% 50%; transform-origin: 50% 50%; } @-webkit-keyframes rotating { 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } <svg width="350" height="350"> <svg width="350" height="350"> <circle cx="230.00591443779982" cy="155.55555555555554" r="45" style="stroke: rgb(158, 157, 158); stroke-width: 1; fill: none;"></circle> <circle cx="100" cy="155.55555555555554" r="45" style="stroke: rgb(158, 157, 158); stroke-width: 1; fill: none;"></circle> <circle cx="180.41237113402062" cy="155.55555555555554" r="50" style="stroke: rgb(158, 157, 158); stroke-width: 1; fill: none;"></circle> <circle cx="165.0943396226415" cy="120.27491408934708" r="45" style="stroke: rgb(158, 157, 158); stroke-width: 1; fill: none;"></circle> <circle cx="165.0943396226415" cy="200" r="45" style="stroke: rgb(158, 157, 158); stroke-width: 1; fill: none;"></circle> <svg viewBox="0 0 600 720" width="295" height="205"> <g transform="translate(239, 370)"> <path></path> <path class="rotate" d="M 175 0 L 326.55444566227675 87.50000000000001 L 326.55444566227675 262.5 L 175 350 L 23.445554337723223 262.5 L 23.44555433772325 87.49999999999999" style="opacity: 0.4; fill: black;"></path> </g> <svg viewBox="0 0 600 720" width="507.4" height="799.5"> <g transform="translate(105, 395)"> <path d="M 175 0 L 341.43489035165186 120.9220259843842 L 277.8624191511828 316.57797401561584 L 72.13758084881722 316.57797401561584 L 8.565109648348141 120.92202598438415" style="opacity: 0.4; fill: black;"></path> </g> </svg> </svg> </svg> </svg>
[ "stackoverflow", "0020558873.txt" ]
Q: Lotus notes automation from browser I have been trying to automate Lotus Notes mail fillup from a browser interface. After refering to Richard Schwartz's answer, i came up with this piece of code using the Lotus.NotesSession class. function SendScriptMail() { var mToMail = document.getElementById('txtMailId').value var mSub = document.getElementById('txtSubject').value var mMsg = document.getElementById('txtContent').value var Password = "yyy" alert("1"); var MailFileServer = "xxx.com" var MailFile = "C:\Program Files\IBM\Lotus\Notes\mail\user.nsf" alert("2") var Session; var Maildb; var UI; var NewMail; var From = "[email protected]" try { alert("3") // Create the Activex object for NotesSession Session = new ActiveXObject("Lotus.NotesSession"); alert("4") if (Session == null) { throw ("NoSession"); } else { Session.Initialize(Password); // Get mail database Maildb = Session.GetDatabase(MailFileServer, MailFile); alert("5") if (Maildb == null) { throw ("NoMaildb"); } else { NewMail = MailDB.CreateDocument(); if (MailDoc == null) { throw ('NoMailDoc'); } else { // Populate the fields NewMail.AppendItemValue("Form", "Memo") NewMail.AppendItemValue("SendTo", mToMail) NewMail.AppendItemValue("From", From) NewMail.AppendItemValue("Subject", mSub) NewMail.AppendItemValue("Body", mMsg) NewMail.Save(True, False) NewMail.Send(False) } } } } catch (err) { // feel free to improve error handling... alert('Error while sending mail'); } } But now, alerts 1,2,3 are being trigerrd, and then the counter moves to the catch block. The lotus notes session is not being started. In a powershell script that I was previously looking at there was a code regsvr32 "$NotesInstallDir\nlsxbe.dll" /s that was used before the Session = new ActiveXObject("Lotus.NotesSession");. Is there something similar in javascript too, if so how do i invoke that dll. I think I've realised where I am going wrong. According to me, upto alert("5") things are good. But since Lotus.NotesSession doesn't have a CreateDocument() method, it is throwing the error. I am not sure how to create the document and populate the values though. A: Since you've chosen to use the Notes.NotesUIWorkspace class, you are working with the Notes client front-end. It's running, and your users see what's happening on the screen. Are you aware that there's a set of back-end classes (rooted in Lotus.NotesSession) instead of Notes.NotesSession and Notes.NotesUIWorkspace) that work directly with Notes database data, without causing the Notes client to grab focus and display everything that you're doing? Working with the front-end means that in some cases (depending on the version of Notes that you are working with) you're not going to be working directly with the field names that are standard in Notes messages as stored and as seen in the back-end. You're going to be working with names used as temporary inputs in the form that is used to view and edit the message. You can see these names by using Domino Designer to view the Memo form. Instead of using 'SendTo', try using: MailDoc.Fieldsettext('EnterSendTo', mToMail) Regarding the Body field, there's no temporary field involved, however you haven't really explained the difficulty you are having. Do you not know how to display the interface that you want in the browser? Do you not know how to combine different inputs into a single FieldSetText call? Or are you just dissatisfied with the fact that FieldSetText can't do any fancy formatting? In the latter case, to get more formatting capability you may want to switch to using the back-end classes, which give you access to the NotesRichTextItem class, which has more formatting capabilities.
[ "stackoverflow", "0055522059.txt" ]
Q: Prevent Visual Studio Code from changing the window layout when the last file in a pane is closed? In Visual Studio Code, if I change my window's layout to include more than one pane (such as two columns), if I close the last file open in that pane then the entire pane will close and change the window layout. This is quite annoying! I always want there to be two columns, or whichever window layout I've set up. Is there a way to change this behavior? A: You want to set this to false: "workbench.editor.closeEmptyGroups": false Then when the last editor of a group (or column as you say) is closed, that editor group will not close.
[ "stackoverflow", "0038731833.txt" ]
Q: javafx programmatically set arguments for virtual keyboard I have a desktop application that will be used on computers with no keyboard, input will be on a touch screen. I can get the virtual keyboard to show up on textfields fine when running from eclipse. I used these arguments -Dcom.sun.javafx.touch=true -Dcom.sun.javafx.isEmbedded=true -Dcom.sun.javafx.virtualKeyboard=none The following link shows me where to add the arguments. how to add command line parameters when running java code in Eclipse? When I make a runnable jar file the keyboard does not show up. I am looking for a way to set these arguments programmatically so that the runnable jar file will display the virtual keyboard on any computer. Any help will be greatly appreciated. A: The only working solution I could find came from here Gradle build for javafx application: Virtual Keyboard is not working due to missing System property Create a wrapper class and set the system properties before invoking the applications original main method. public class MainWrapper { public static void main(String[] args) throws Exception { // application - package name Class<?> app = Class.forName("application.Main"); Method main = app.getDeclaredMethod("main", String[].class); System.setProperty("com.sun.javafx.isEmbedded", "true"); System.setProperty("com.sun.javafx.touch", "true"); System.setProperty("com.sun.javafx.virtualKeyboard", "javafx"); Object[] arguments = new Object[]{args}; main.invoke(null, arguments); } } When making the runnable jar file just point to the MainWrapper class for the launch configuration.
[ "stackoverflow", "0060888283.txt" ]
Q: Generating n number of different files in python In my code I create a text file of random numbers. But I am wondering if it is possible to generate multiple files, each time with different ranges for the random numbers within a for loop. I have an idea for how to implement this, but I'm not sure how to call the file I make each time testn, with n being the current value of n. So I would have files: test1, test2 and so on. My implementation so far is: numberOfFiles = 5 #set this to the number of files you want to make for n in range(numberOfFiles): newFile = open('testn.txt', 'w') #if possible I want to create a file each time and call it testn, where n is the current value of n. x = [] for i in range(10): #number of lines in each file x.append(random.randint(0,60 + (n * 10)) for val in range(len(x)): newFile.write(str(x[val]) + "\n") newFile.close() A: newFile = open('test' + str(n) + '.txt', 'w') or in python3.6+: newfile = open(f'test{n}.txt','w')
[ "elementaryos.stackexchange", "0000001664.txt" ]
Q: How to change the first day of week on wingpanel calendar? I'd like to change the first day of week on the little calendar that shows up at the wingpanel. At the current state it shows Sunday as the first day of the week, but I'd like it to be Monday. How can I change this? Thank you! A: Use a locale from a culture where that is the norm. You can try to make that a sticky setting for your user in the system, by putting something like that in ~/.xsessionrc export LANG=en_US.UTF-8 export LANGUAGE=en_US.utf-8 export LC_TIME=en_GB.UTF-8 export LC_MEASUREMENT=en_GB.UTF-8 Which is basically "I want system messages in American, but time and measurement in UK English". Monday is the first day of the week in UK culture. Log out and back in for that to work. Or, you could try make that a system-wide change. Assuming your locale outputs LANG=en_US.UTF-8, find and change first_weekday 1 to first_weekday 2 in the US locale file (do a sudo nano /usr/share/i18n/locales/en_US). Then do a sudo locale-gen and reboot. The latter is not recommended in a server setting, but you should be fine on your own machine.
[ "stackoverflow", "0010325565.txt" ]
Q: Tokenize a source code Is there any library available that can tokenize source code written in different programming languages (java/C/C++)? (can possible identify part of it like starting and ending of a function, which are identifiers). I do not want to parse the source code, that can be overly complex. Moreover the source code may not be error free. Thanking in advance. A: You can tokenize source code using a lexical analyzer (or lexer, for short) like flex (under C) or JLex (under Java). The easiest way to get grammars to tokenize Java, C, and C++ may be to use (subject to licensing terms) the code from an open source compiler using your favorite lexer. Even if you find the licensing conditions too onerous, they should be educational to look through... However, you still won't be able to identify the beginning and end of a function without parsing.
[ "stackoverflow", "0031685812.txt" ]
Q: Why does the size of the contents of a tag change its position? I'm trying to figure out why my buttons aren't lining up, and I figured out it's because the size of their contents are different. Here's a fiddle: https://jsfiddle.net/ktjboox3/ button { width: 75px; height: 75px; } <button> hello </button> <button> hello <br /> hello </button> <button> hello <br /> hello <br /> hello </button> You can see that the buttons with more content have this strange top-margin-but-not-actually-margin going on. Why are they layed out lower? It appears to be a requirement that they all have a set width and height, but I need all my buttons to be the same size. And to be clear, even though I am certainly interested in getting my code to work, the actual answer I'm looking for isn't a code snippet where the buttons are all lined up, I want to understand this is happening in the first place. A: button { width: 75px; height: 75px; vertical-align: top;/* or middle/bottom/... whatever suits your needs best */ } <button>hello</button> <button>hello <br />hello</button> <button>hello <br />hello <br />hello</button> buttons are inline-block element and can be set on the same level from the base line with: vertical-align https://jsfiddle.net/ktjboox3/5/ A: If you look carefully you will notice that the baselines of all three buttons (the bottom of the last line) (Chrome might have got this wrong) are vertically aligned. This is the expected behavior since the initial value for vertical-align property is baseline. To align the top of all buttons, set the vertical align to top. button { width: 75px; height: 75px; vertical-align: top; } <button> hello </button> <button> hello<br> hello </button> <button> hello<br> hello<br> hello </button>
[ "stackoverflow", "0054112542.txt" ]
Q: How to use 2 gridview cell values column to build a hyper link I have a gridview. I need to build a hyperlink in one column with the value from a different one and its own value. So for example the URL would be something.com/column1value/column2value. I have the System and theregion hyperlinked via a TemplateField in there respective column. It is in column 2 that i want to build the url based on the value in column1 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SQL" Class='table table-hover' BorderStyle="None" BorderColor="White" GridLines="None" UseAccessibleHeader="False" ShowFooter="True" ShowHeaderWhenEmpty="True" EnableTheming="False"> <Columns> <asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" /> <asp:TemplateField HeaderText="System" SortExpression="System"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("System") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("System", "http://evemaps.dotlan.net/system/{0}/") %>' Target="_blank" Text='<%# Eval("System", "{0}") %>'></asp:HyperLink> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Region" SortExpression="Region"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Region") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("Region", "http://evemaps.dotlan.net/Map/{0}/") %>' Target="_blank" Text='<%# Eval("Region", "{0}") %>'></asp:HyperLink> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" /> <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> <asp:BoundField DataField="Owner" HeaderText="Owner" SortExpression="Owner" /> <asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" /> <asp:TemplateField HeaderText="EvE Time" SortExpression="EvE Time"> <EditItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("[EvE Time]") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="EvETimeLB" runat="server" Text='<%# Bind("[EvE Time]") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> <HeaderStyle Font-Bold="True" /> </asp:GridView> A: Using Eval is not restricted to the column you are using it in. You can use all the columns in an ItemTemplate. <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank" NavigateUrl='<%# string.Format("something.com/{0}/{1}", Eval("column1"), Eval("column2")) %>' Text='<%# string.Format("something.com/{0}/{1}", Eval("column1"), Eval("column2")) %>'> </asp:HyperLink>
[ "stackoverflow", "0049716031.txt" ]
Q: Javascript obje.key is undefined when assigned to object itself I was looking at a snippet from here var foo = {n: 1}; var bar = foo; foo.x = foo = {n: 2}; When I log foo.x it says undefined. Why's it so? I expected it to be {n: 2} A: The values are assigned from left to right so this is what happens: foo.x = {n: 2}; which results in foo being {n: 1, x: {n: 2}} then foo is being assigned a new value foo = {n: 2}; which overrides it to {n: 2}.
[ "stackoverflow", "0008937089.txt" ]
Q: Grouping listview Below is the code currently I am using for grouping in listview. I am able to group records, but when user clicks on the button(AddNewCluster) to create new group with set of records I am unable to concatenate with the old records. The listview gets updated with the new group and records. But I need to show the user both the old and newly added group and records. ListCollectionView collectionView; public Window1() { InitializeComponent(); var clusters = new[] { new Cluster { Name = "Front end" }, new Cluster { Name = "Middle end" }, new Cluster { Name = "Back end" }, }; collectionView = new ListCollectionView(new[] { new Server { Cluster = clusters[0], Name = "webshop1" }, new Server { Cluster = clusters[0], Name = "webshop2" }, new Server { Cluster = clusters[0], Name = "webshop3" }, new Server { Cluster = clusters[0], Name = "webshop4" }, new Server { Cluster = clusters[0], Name = "webshop5" }, new Server { Cluster = clusters[0], Name = "webshop6" }, new Server { Cluster = clusters[2], Name = "sql1" }, new Server { Cluster = clusters[2], Name = "sql2" }, }); var groupDescription = new PropertyGroupDescription("Cluster.Name"); // this foreach must at least add clusters that can't be // derived from items - i.e. groups with no items in them foreach (var cluster in clusters) groupDescription.GroupNames.Add(cluster.Name); collectionView.GroupDescriptions.Add(groupDescription); ServersList.ItemsSource = collectionView; Clusters = groupDescription.GroupNames; } readonly ObservableCollection<object> Clusters; And here is the AddNewCluster_Click method: void AddNewCluster_Click(object sender, RoutedEventArgs e) { Clusters.Add(NewClusterName.Text); var clusters = new[] { new Cluster { Name = NewClusterName.Text }, }; collectionView = new ListCollectionView(new[] { new Server { Name = "new server data" }, }); var groupDescription = new PropertyGroupDescription("Cluster.Name"); // this foreach must at least add clusters that can't be // derived from items - i.e. groups with no items in them foreach (var cluster in clusters) groupDescription.GroupNames.Add(cluster.Name); collectionView.GroupDescriptions.Add(groupDescription); ServersList.ItemsSource = collectionView; } A: It's a bit difficult to read the code, but as far as I can make out, you're creating a new collection view, with a completely new collection, instead of adding the new item to the old collection. You should add the new item to the old collection and call CollectionView.Refresh().
[ "stackoverflow", "0004366315.txt" ]
Q: jScrollPane strange behavior in Internet Explorer I'm trying to use jScrollPane with fallowing page: http://demo.2klika.net/home.php#!pages/prodavaonice.html Well, this works as expected in all major browsers except in Internet Explorer (I tried with IE7 and IE8). On first load (same goes for every page reload), IE will show list of locations, and when you click somewhere in that list, it will jump down to the last item in list. After that it will work normally (you can click on title, eg. Mesnica 1, Mesnica 2, etc..., and script will center google map on that marker). I tried everything that I can think of (eg. removing onClick handlers for various elements, tried to catch problematic function using developer tools in IE, googling around, but no luck). If someone can help with this, I will be very grateful. Thanks in advance. A: This has been addressed: jScrollpane 2 IE8 Problem - strange behavior when hit top/bottom https://github.com/vitch/jScrollPane/commit/b80165e3c5cb6d21f9569cacaffd55d33435d23c
[ "magento.stackexchange", "0000291331.txt" ]
Q: Varnish full_page cache can't clear I've recently set my site up with Varnish full_page cache, and I have one specific URL that seems to be "stuck" and I am not able to clear it from the cache. Last night I went into maintenance mode to do some updates, and this morning one URL is still showing the maintenance page, I guess because it got crawled while the site was down. All the other URLs I've tested are working but this specific one won't load. This is production so I don't want to do anything crazy, I just want to clear that one page's cache and nothing I've tried works. I have tried restarting Varnish at the command line but that does not work. Nor does clearing Magento cache on the front end. I can disable full_page cache at the command line, and then I can see that the page loads properly. Then I restarted Varnish, and turned full_page cache back on, and the page then responded once again with the "Maintenance" page. So Varnish is hard-caching the page response, but how do I purge it? Magento 2.3.2 and Varnish 6.0.3 A: I thought this URL was caching the maintenance page, but that wasn't the case. This specific page was actually crashing when varnish was enabled because of this Magento issue with too-long cache headers. My fix is described in my response to this issue: Magento 2.3.1 - Issue with catalog search when using php7.2-fpm
[ "stackoverflow", "0027084493.txt" ]
Q: copy nsobject custom class to array after edit it's properties I do have a problem editing my custom class objects, I do have a custom class of product, when i pass it through next view where i can fix it's quantity and save it to my appdelegate array, everything OK! But if I try to add the same product with another quantity to same array, first object get overwritten and i do get second object twice in my array with same property values, my code is to messy to past it here, so here an pseudo example of problem: view A: list of products class product: title quantity View B: product details set quantity let's say I choose product apple: in view B quantity set to 2 added to array if I select product apple again set quantity to 1 added to array as result I do get an array of 2 objects: -apple quantity 1 -apple quantity 1 any help appreciated, A: The scenario points out to a simple root cause: you are not making a copy of the object before editing it. The two objects in your NSMutableArray are actually the same object. It is hard to identify the problem without seeing the relevant code. However, you need to make sure that the products and quantities are not stored in the same object: @interface Product @property NSString *name; @property NSDecimal *price; @end @interface OrderEntry @property Product *product; @property int quantity; @end You should be adding OrderEntry objects to your NSMutableArray. Each time that you add a new entry a new OrderEntry object needs to be created, rather than modifying an existing one.
[ "stackoverflow", "0001758276.txt" ]
Q: How can I run a Python program over telnet? How can I run a Python program so it outputs its STDOUT and inputs its STDIN to/from a remote telnet client? All the program does is print out text then wait for raw_input(), repeatedly. I want a remote user to use it without needing shell access. It can be single threaded/single user. A: On a Unix system, you can use inetd for this. It will take care of opening the network connection for you, so your program will work as-is. A: Make the Python script into the shell for that user. (Or if that doesn't work, wrap it up in bash script or even a executable). (You might have to put it in /etc/shells (or equiv.)) A: If you don't need full telnet functionality, you can just use a socket. Check out the Socket Server module in the standard python library. It'll enable you to easily write a program that'll listen on a port for input/output. It won't support the proper telnet protocol negotiation, but you might not need that for what you're doing.
[ "stackoverflow", "0006789655.txt" ]
Q: glReadPixels() fails to fill ByteBuffer Well, I'm trying to take a screenshot for a window in OpenGL using LWJGL. Here's the code: ByteBuffer pixels = ByteBuffer.allocateDirect(800*600*4); pixels.order(ByteOrder.nativeOrder()); while(!Display.isCloseRequested()) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); render(); Display.update(); // "Screenshot" block if(Keyboard.isKeyDown(Keyboard.KEY_Q)) { pixels.clear(); glReadPixels(0, 0, 800, 600, GL_RGBA, GL_UNSIGNED_BYTE, pixels); pixels.flip(); // pixels.position() and pixels.limit() tells us that there is nothing in the buffer // ... } } And... I've already tried various versions of the code, like placing the "Screenshot" block before Display.update(). And using combinations of glReadBuffer(GL_BACK/GL_FRONT) and glDrawBuffer(GL_BACK/GL_FRONT) to no avail. I've disabled all OpenGL states and rendering, so that only a blank screen appears and tried using glReadPixels. A blank screen supposes to be in the buffer, but nothing is in the buffer. glGetError() doesn't produce any error. I have a similar C+ version that works fine. I'm running Windows 7, OpenGL 4.10 and LWJGL version 2.7.1 on NVIDIA Corporation GeForce GTS 450/PCI/SSE2. So, what's the problem? Any ideas? Thanks in advance. A: pixels.position() and pixels.limit() tells us that there is nothing in the buffer Do they? I think a more foolproof method would be to look at the contents of the buffer. Also, Display.update swaps buffers. The contents of the back buffer are undefined after a swap. So you should either read from the front buffer (not a good idea) or read the back buffer before swapping.
[ "superuser", "0000120424.txt" ]
Q: can I make firefox remember what spellcheck dictionary to use for particular web sites? I read and write on the web in two different languages and it would be really handy to teach firefox to use this spellcheck dictionary for that and that website while the default one would be english. Is anything like that possible? ( win XP + ff 3.6 ) A: Yes, with the add-on Dictionary Switcher: Toggles between the installed dictionaries automatically or manually and displays the currently selected dictionary in the status bar.
[ "stackoverflow", "0031774502.txt" ]
Q: Gettin the info from Json file in RoR I'm new to the RoR. My question is: how can I get the Json info into my view files? Let me explain in details: I got data.json file and it contains like these info: [ { "question" : "What's your name?", "answerA" : "Tom", "answerB" : "Bill", "answerC": "John", "answerD": "Foo" } ] How can I use this data in my views? I'm trying to make a test(quiz) app, is there any gem for this? Thanx A: Get a reference to the file in your controller: def index file_path = "/your/file/path/data.json" # You can use Rails.root.join if it's in your Rails app @questions = JSON.parse(File.read(file_path.to_s)) end You are good to go: use @questions in your Rails view, you are now able to access that json data.
[ "stackoverflow", "0004450843.txt" ]
Q: Ruby on Rails: How to set which development environment an app runs in? I'm relatively new to Ruby on Rails and occasionally I find this convention-over-configuration stuff a little confusing as a lot of things seemed to be hidden from the developer, as in this case. I'm using rails 2.3.8 and when I run my app locally through NetBeans 6.9/Mongrel on my system it runs using the development environment parameters.. when I deploy it to a Fedora box and run it there in Apache HTTPD it automatically runs using the production environment parameters. How does my app know which environment to use? I haven't changed anything in my app to set the environment.. both versions locally and on my Fedora box are identical. I can't find anywhere in the code where it is setting the environment.. so how is this working? Thanks. A: In httpd.conf file, write the following in VirtualHost:- ## Specify Rails Environment here, default value is "production" RailsEnv development Thanks...
[ "stackoverflow", "0028260565.txt" ]
Q: is it possible to create subclasses in powershell v5? I've tried to work out a solution this afternoon, but I've only had partial success so far... Here is my code: class Animal { [int] $numOfLegs = 0; [int] $numOfEyes = 2; [scriptblock] $dog = { class Dog { [int] $numOfLegs = 4 [int] getLegs(){ return $this.numOfLegs; } [int] getEyes(){ return $numOfEyes; } } return [dog]::new() } } (The Dog class can be instantiated by doing this): $mypetdog = & ([animal]::new().Dog) Basically, my idea was to try to get scriptblocks to act as closures, so that each 'subclass' definition contained within Animal could be invoked (and still have access to it's parent scope). So for example, when getEyes() is executed on the Dog object, it would in theory return the number 2. However this didn't work because I think that the scriptblock cannot see outside its own scope (when defined within a class). So when I do this: $mypetdog.getLegs() it correctly returns 4, but when I do this: $mypetdog.getEyes() Powershell has no idea what the variable $numOfEyes is and subsequently throws an error because the variable is undefined within the class. Does anyone have a solution to imitating subclasses in PowerShell without using add-type? A: Classes in PowerShell 5.0 was created to simplify development of DSC resources which do not require inheritance, so this is not yet supported. As you can see below, they will work on it, but there is no ETA, which means that you might have to wait until v6+. The focus for the September preview was to enable writing a DSC resource via PowerShell classes. This does not require inheritance, so you are correct, inheritance is not supported in the September preview. Classes are still useful for many things without inheritance – for example C is alive and well and it still doesn’t have member functions, let alone inheritance. That said, we obviously understand the importance of inheritance. No promises as to when it will be available, but it is something we are working on. Source: WMF blog - Comments You could try to get something working using New-Object, $obj.psobject.copy() and Add-Member(to define the properties and functions of the subclass), like someone has described here UPDATE: Class inheritance is available in PowerShell 5.0 RTM. Example: class Vehicle { [string]$Make [string]$Model [string]$Color } class Car : Vehicle { [string]$VIN } $car = [car]@{ Make = "Ford" Model = "Mustang" Color = "Red" VIN = "123456" } $car VIN Make Model Color --- ---- ----- ----- 123456 Ford Mustang Red
[ "stackoverflow", "0044530363.txt" ]
Q: Illuminate support collection and getting multiple values by pluck I have Collection like this [ { "user_id":1, "chat_id":1, "chat_hidden":0, "access_time":"2017-06-10 00:28:11", "name":"Dr. Harley Raynor", "image_url":null }, { "user_id":1, "chat_id":2, "chat_hidden":1, "access_time":"2017-06-12 10:59:37", "name":"Dr. Harley Raynor", "image_url":null } ] if i want to take only user_id from it, and format array like this [ { "user_id":1 }, { "user_id":1 } ] i write Collection()->pluck('user_id') and everything works fine, but what if i need to take several items? Like user_id and chat_id? I tried ->pluck('user_id', 'chat_id'), ->pluck(['user_id', 'chat_id']) and ->only('user_id', 'chat_id') nothing seems to work. A: Just use map; $myCollection->map(function($item) { return [ 'user_id' => $item->user_id, .... ]; }); But if you are building an api, I strongly recommend you to use some sort of transformers such https://github.com/spatie/laravel-fractalto handle inclusion and exclusion in the future as the service mature.
[ "math.stackexchange", "0001425269.txt" ]
Q: A colored ball problem Say you have $2n+2b$ balls where $2n$ balls are colored white, $b$ balls are colored blue and $b$ balls are colored red. You have two urns. You randomly choose $n+b$ balls and throw in urn $1$ while you place the remaining $n+b$ balls in urn $2$. What is the probability that the blue balls and red balls are in separate urns? I am most interested in case $\frac{n}b\rightarrow\infty$ such as $b=n^{\frac1c}$ with $c>1$ being fixed and in case $\frac{n}b\rightarrow c$ such as $b={\frac nc}$ with $c>1$. A: There are $\binom{2n}n$ ways of selecting $n$ of the $2n$ white balls to go with the red balls. Thus, for $b\gt0$ there are $2\binom{2n}n$ ways of separating the red and blue balls, where the factor $2$ occurs because the red balls can be in either of the two urns. There are $\binom{2n+2b}{n+b}$ ways to select balls for one of the urns, so this is the total number of outcomes. Since the selections are equiprobable, the probability for a separating selection is $$ \frac{2\binom{2n}n}{\binom{2n+2b}{n+b}}\;. $$ For $b=0$, the factor of $2$ should be omitted, and the probability of (trivial) separation is $1$.
[ "stackoverflow", "0033822291.txt" ]
Q: Deserializing Json string with C# using Newtonsoft.JSON I have read some articles but didnt fix my problem , i have a problem with JSON string when deserialize, here the string {"table":"sy_version","effected":2,"data":[{"mod_id":"CS","sub_mod":"sbm_sl.exe","version":"2015.11.07.1","upload_date ":"2015-11-10 11:34:13"},{"mod_id":"FA","sub_mod":"sbm_fa.exe","version":"2015.11.09","upload_date ":"2015-11-10 11:34:13"}]} And this is my class public class Datum { public string mod_id { get; set; } public string sub_mod { get; set; } public string version { get; set; } public DateTime upload_date { get; set; } } public class sy_periode { public string table { get; set; } public int effected { get; set; } public IList<Datum> datas { get; set; } } public static void test(string str) { // dynamic sy_periode = JsonConvert.DeserializeObject(str); var sy_periode = JsonConvert.DeserializeObject<sy_periode>(str); foreach (var data in sy_periode.datas) { Console.WriteLine(data.sub_mod); } } When I executed, string table and effected have value, but datas is null, this is the error message Object reference not set to an instance of an object. A: It shouldn't be datas, it should have the same name as JSON object: data. Here is the correct classes structure: public class Datum { public string mod_id { get; set; } public string sub_mod { get; set; } public string version { get; set; } public DateTime upload_date { get; set; } } public class sy_periode { public string table { get; set; } public int effected { get; set; } public IList<Datum> data { get; set; } } Also, note that in JSON your upload_date properties have an odd whitespace in the end: upload_date. It may be a typo. However, if it is an actual input and since C# member name cannot contain spaces, you can try to specify the name in order to serialize it: [JsonProperty(PropertyName = "upload_date ")] public DateTime upload_date { get; set; } I am not quite sure that it will work, but I see no reasons of why it shouldn't.
[ "stackoverflow", "0024114697.txt" ]
Q: Default template argument in method hidden behind class default template argument #include <iostream> template< typename T = char > struct Foo { void bar(); }; template< typename T = int > void Foo< T >::bar() { std::cout << typeid( T ).name() << std::endl; } int main() { Foo<> x1; Foo< double > x2; x1.bar(); x2.bar(); } Output: char double char is hiding the int here, why is that? Is it even possible to have multiple different template arguments for the same class? (Guess not)But why doesn't yell the compiler then? http://connect.microsoft.com/VisualStudio/feedback/details/892125/ill-formed-default-template-argument-not-throwing-error A: ill-formed snippet The code provided in your post is ill-formed as stated by the C++ Standard (n3337): 14.1p9 Template parameters [temp.param] A default template-argument is a template-argument (14.3) specified after = in a template-paraemter. A default template-argument may be specified for any kind of template-parameter (type, non-type, template) that is not a template parameter pack (14.5.3). A default template-argument may be specified in a template declaration. [ Note: >>] A default template-argument shall not be specified in the template-parameter-lists of the definition of a member of a class template that appears outside of the member's class. [ << :Note ] Conclusion With the above quotation in mind we can draw the conclusion that the compiler you are using is faulty; it's not conformant to the rules set out by the Standard, the snippet should not be accepted. What are the reason behind the Standard disallowing such construct? Honestly this most probably boils down to "well, it doesn't make sense to allow it". Since the type of x1 (and with that the type of T) is known at the type of declaration (Foo<> => F<char>), a potential default template-argument when defining a member of the class is useless; it will never be required, nor will it be used.
[ "stackoverflow", "0061879511.txt" ]
Q: How to fill in rows based on event type data So my table has 2 columns: hour and customerID. Every customer will have 2 rows, one corresponding to hour that he/she came into the store, and one corresponding to hour that he/she left the store. With this data, I want to create a table that has every hour that a customer has been in the store. For example, a customer X entered the store at 1PM and left at 5PM, so there would be 5 rows (1 for each hour) like the screenshot below. Here's my attempt that's now: select hour ,first_value(customer_id) over (partition by customer_id order by hour rows between unbounded preceding and current row) as customer_id FROM table A: Assuming that: you are running Postgres a given customer always has exactly two rows in the table hour is of a date-like datatype Then one option is to use generate_series() with a lateral join, like so: select t.customer_id, x.hour from ( select customer_id, min(hour) min_hour, max(hour) max_hour from mytable group by customer_id ) t cross join lateral generate_series(min_hour, max_hour, '1 hour') x(hour) order by t.customer_id, x.hour Demo on DB Fiddlde: customer_id | hour :---------- | :------------------ X | 2019-04-01 13:00:00 X | 2019-04-01 14:00:00 X | 2019-04-01 15:00:00 X | 2019-04-01 16:00:00 X | 2019-04-01 17:00:00 Y | 2019-04-01 17:00:00 Y | 2019-04-01 18:00:00 Y | 2019-04-01 19:00:00
[ "stackoverflow", "0030734787.txt" ]
Q: C++ 2D vector - Convert int to double What is a good way to convert vector<vector<int>> vint to vector<vector<double>>vdouble? I know from C++ convert vector<int> to vector<double> that this can be done for 1-D but I am not too sure how to do it for 2-d case. A: Here's a pretty simple solution which uses emplace_back and the vector range constructor: std::vector<std::vector<int>> intvec; //intvec filled somehow std::vector<std::vector<double>> doublevec; doublevec.reserve(intvec.size()); for (auto&& v : intvec) doublevec.emplace_back(std::begin(v), std::end(v));
[ "stackoverflow", "0009868722.txt" ]
Q: resteasy response I have a similar case as the one described here: Dynamically change RESTEasy service return type The problem I'm facing is that I'm trying to return a list of objects (annotated with @XMLRootEntity), but I get a 500 server error code: The server encountered an internal error (Could not find MessageBodyWriter for response object of type: java.util.ArrayList of media type: application/json) that prevented it from fulfilling this request. Can you give some advice how to solve this issue? I'm not sure exactly where to look. Thanks. A: You should use interface instead of using implementation of list. Try changing return type with : java.util.List EDIT: Try to wrap list into GenericEntity : List<String> myList = new ArrayList<String>(); // add ... final GenericEntity<List<String>> entity = new GenericEntity<List<String>>(myList) { }; Response.status(Status.BAD_REQUEST).entity(entity).build();
[ "stackoverflow", "0006666217.txt" ]
Q: building an xml file for flash from a mysql query using php Ok here's the the thing. I have a flash slideshow which runs from an xml file. I want to populate the xml file with data from a query, using php Now I can see on here there are some examples, and I understand some of it, however, in the xml file I am using the 'content' is inside the XML tag rather than wrapped by it. e.g. this is from an example on here... the tag goes around the data. <news> <? while($item = mysql_fetch_array($data)){ ?> <item> <url><?=$item['url']; ?></url> <title><?=$item['title']; ?></title> </item> } ?> </news> In the XML file I'm using, the tag for a link, looks like this.... <link url="" target=""></link> So, would the php code go like this <link url="<?=$item['url]; ?>" target=""></link> Hope someone can explain ! Thanks Rich :) A: An XML element can contain other elements or text like you have in your example item with url and title. Elements can also have attributes like in HTML <a href="/">Home</a>. There are some guidelines when to put "content" into an attribute but we are actually free to do whatever we want as long as the reader of the XML document know if he has to look for another element inside a tag or for the attribute <link url="www.domain.com" /> // these are equal <link> <url>www.domain.com</url> </link> // however you have get the url through different process. Getting attributes is somewhat easier why I think that a lot of documents use attributes. At w3schools are other good examples Side note: If your element does not contain text or other elements you don't need a closing tag but a slash.
[ "stackoverflow", "0002104013.txt" ]
Q: WPF Groupbox header position alignment Is it possible to set the position alignment for a GroupBox Header in WPF? The default is to place in the top left corner of the GroupBox outline but I would like it to be centered at the top. I know that you can set the properties of the text using: <GroupBox Grid.Row="1" HorizontalAlignment="Center"> <GroupBox.Header> <TextBlock Text="Cash Match" Foreground="Black" FontWeight="Bold"/> </GroupBox.Header> </GroupBox> But I'm looking to set the position of it with respect to the GroupBox outline. A: It's simple! Just edit Template of GroupBox: In Blend, do the following : Right click GroupBox > Edit Template > Edit a Copy > OK Search for following section: <Border x:Name="Header" Padding="3,1,3,0" Grid.Column="1" Grid.Row="0" Grid.RowSpan="2"> ... </Border> Change Grid.Column to 2 Also set HorizontalAlignment="Right" You have just aligned the header to right!!! But bot the white gap behind it. For that, Now search for following section : <Border BorderBrush="White" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4" Grid.ColumnSpan="4" Grid.Row="1" Grid.RowSpan="3"> <Border.OpacityMask> ... </Border.OpacityMask> ... </Border> Add RenderTransformOrigin="0.5,0.5" to the border Just above , add following code (this will shift the "white gap" behind header to right: <Border.RenderTransform> <ScaleTransform ScaleX="-1"/> </Border.RenderTransform> You are done! You just got a GroupBox with right aligned header!!! Please tell me if this is what you required.
[ "stackoverflow", "0010280367.txt" ]
Q: how to change default generated style in MVC in MVC when we want add new controller class in the scaffolding option we can choose template that generate views and etc . i want to know how can i have a custom template ? i want to add some new view A: Check out MVCScaffolding, it is a more powerful scaffolding engine than supports customizing the templates and creating custom scaffolders. I don't know of a way to do it with the default scaffolder.
[ "stackoverflow", "0019927492.txt" ]
Q: Could someone explain what is nice time in cpu stat? I know the difference between user time and sys time. However, I'm not quite sure about the nice time. I used to know that nice time is the time used in nice pr, but when I did an experiment, I found that the nice time didn't grow up after I reniced a 100%-CPU-using program(infinite loop doing add in Java) to 19. So, I'm confused... Btw, I'm going to write a C++ program to monitor the CPU usage. All I can do now, is to read /proc/stat twice and get the difference. But, I don't know how to calculate the Totle time. total = user + sys + idle or total = user + sys + nice + idle or even total = user + sys + nice + idle + iowait + ... (the entire line). Which is right? A: Mpstat(1) reads /proc/stat. Diving into kernel source tree I found a file kernel/sched/cputime.c, taken from Linux 3.11.7 sources, which seems to include relevant bits which update things reflected in /proc/stat: /* * Account user cpu time to a process. * @p: the process that the cpu time gets accounted to * @cputime: the cpu time spent in user space since the last update * @cputime_scaled: cputime scaled by cpu frequency */ void account_user_time(struct task_struct *p, cputime_t cputime, cputime_t cputime_scaled) { int index; /* Add user time to process. */ p->utime += cputime; p->utimescaled += cputime_scaled; account_group_user_time(p, cputime); index = (TASK_NICE(p) > 0) ? CPUTIME_NICE : CPUTIME_USER; /* Add user time to cpustat. */ task_group_account_field(p, index, (__force u64) cputime); /* Account for user time used */ acct_account_cputime(p); } This hints that time spent running niced tasks is not included into column displaying time spent running user mode tasks in general (the line index= seems relevant to this).
[ "stackoverflow", "0034172815.txt" ]
Q: Custom post type not appearing in Wordpress admin menu I am facing an issue. I'm new in wordpress. I created a function for custom post types. This is my code. function my_cpt(){ $labels = array( 'name' => 'SM & Points Templates', 'add_new' => 'Add New SM & Points Template(s)', 'add_new_item' => 'Add New SM & Points Template(s)', 'edit_item' => 'Edit SM & Points Template(s)' ); $args = array( 'labels' => $labels, 'menu_icon' => 'dashicons-arrow-right-alt', 'public' => true, 'supports' => array('title') ); register_post_type('custom_settings', $args); $labels1 = array( 'name' => 'Fine Print', 'add_new' => 'Add New Fine Print', 'add_new_item' => 'Add New Fine Print', 'edit_item' => 'Edit Fine Print' ); $args1 = array( 'labels' => $labels1, 'menu_icon' => 'dashicons-arrow-right-alt', 'public' => true, 'supports' => array('title') ); register_post_type('fine_prints', $args1); $labels2 = array( 'name' => 'Post Hints', 'add_new' => 'Add New Post Hint', 'add_new_item' => 'Add New Post Hint', 'edit_item' => 'Edit Post Hint' ); $args2 = array( 'labels' => $labels2, 'menu_icon' => 'dashicons-arrow-right-alt', 'public' => true, 'supports' => array('editor') ); register_post_type('post_hints', $args2); $labels3 = array( 'name' => 'States', 'add_new' => 'Add New State', 'add_new_item' => 'Add New State', 'edit_item' => 'Edit State' ); $args3 = array( 'labels' => $labels3, 'menu_icon' => 'dashicons-arrow-right-alt', 'public' => true, 'supports' => array('title') ); register_post_type('states', $args3); $labels4 = array( 'name' => 'Help', 'add_new' => 'Add Help', 'add_new_item' => 'Add Help', 'edit_item' => 'Edit Help' ); $args4 = array( 'labels' => $labels4, 'menu_icon' => 'dashicons-arrow-right-alt', 'public' => true, 'supports' => array('title') ); register_post_type('helps', $args4); } add_action('init', 'my_cpt'); The issue is that First 4 posts are appearing in admin menu. But last Helps is not appearing in menu bar. Where am I wrong? Please see the this image. After States, there should be Help. EDIT: When I was adding the last custom post, I made a small mistake. I added this code. $labels4 = array( 'name' => 'Help', 'add_new' => 'Add Help', 'add_new_item' => 'Add Help', 'edit_item' => 'Edit Help' ); $args4 = array( 'labels' => $labels4, 'menu_icon' => 'dashicons-arrow-right-alt', 'public' => true, 'supports' => array('title') ); register_post_type('states', $args4); Now the last two custom post types had same id states. But when I saw it, I changed it to helps. It was appearing when I added it for the first time with states id. But when I changed it to helps, It disappeared. In the top menu, Helps is visible under New but not in admin menu. A: I found the issue. There was a conflict with plugin WooCommerce Deals. When I deactivated it, the issue was resolved.
[ "german.stackexchange", "0000059243.txt" ]
Q: Kafka Metamorphoses sentence structure I came across this sentence in the Metamorphosis: "Mit welcher Kraft er sich auch auf die rechte Seite warf, immer wieder schaukelte er in die Rückenlage zurück." Why is the verb "schaukelte" not directly after the comma? I think that "Mit welcher Kraft er sich auch auf die rechte Seite warf" is an indirect question subordinate clause, and every other time I've seen a subordinate clause in first position, the verb is still in second position. A: I do not think this is an indirect question subordinate clause. Translated, the sentence means roughly Whichever force / strength he used to throw himself to the right, he always swung back to lying on his back. (Imagine a beetle lying on its back and trying to get off its carapace). I am pretty sure that this is an "Adverbialsatz" (adverbial clause?), either a Konzessivsatz or an Irrelevanzsatz. For my feeling, Irrelevanzsatz is the proper term here, but the only internet source I found for that is something from Leibnitz-Institut für Deutsche Sprache without any instructions to the verb order of the main clause. Konzessivsatz Wikipedia: The subject of the subordinate clause runs counter to the subject of the main clause Obwohl er sich mit aller Kraft auf die rechte Seite warf, schaukelte er immer wieder in die Rückenlage zurück. (Although he used all his power to throw himself to the right, he always swung back to lying on his back) This would be a grammatically correct Konzessivsatz - including your proposed word order of the verb being immediately after the comma. Literary freedom, however, allows you to put "immer wieder" first: Obwohl er sich mit aller Kraft auf die rechte Seite warf - immer wieder schaukelte er in die Rückenlage zurück. This emphasizes the futility of his actions in the subordinate clause - it isn't even enough to influence the grammar of the main clause. Additionally, it emphasizes "immer wieder" (again and again). Irrelevanzsatz Leibnitz-Institut page: subordinate clause(s) exhaust all possibilities, showing that it is irrelevant to whatever happens in the main clause Egal mit welcher Kraft er sich auch auf die rechte Seite warf, immer wieder schaukelte er in die Rückenlage zurück. (No matter which force/strength/power ... - see first translation) This would be my preferred translation. In Irrelevanzsatz, the main clause has a proper stand-alone sentence structure. This emphasizes the irrelevance of the subordinate clause - no matter what he does, he can't get off his back. Other examples: Egal / Ganz gleich was er (auch) hörte, er schrieb es auf. (No matter what / whatever he heard, he wrote it down) Ganz gleich / Egal welchen Weg du (auch) nimmst, alle führen nach Rom. (No matter which / whichever road you take, all of them lead to Rome.) You can leave out "Egal / ganz gleich" and not change the meaning, especially if you include the "auch" - this is what Kafka used, I think: Was er (auch) hörte, er schrieb es auf. Welchen Weg du (auch) nimmst, alle führen nach Rom. The "auch" is a short form for "auch immer" - the "-ever" part in the sentence: Was auch immer er hörte, ... (Whatever he heard,...) Welchen Weg auch immer du nimmst,... (Whichever road you take,...) Especially in the "Was" case though, the word order of the main clause is very important. If you leave it like this, it is implicitly understood that it means "No matter what he heard". If you change it to verb first and remove "auch", it loses the "no matter what" implication. Was er hörte, schrieb er auf. (He wrote down what he heard - NOT he wrote down whatever he heard!)
[ "stackoverflow", "0035599734.txt" ]
Q: Convert a csv into category-subcategory using array Above is the input table i have in csv I am trying to use array and while loops in python. I am new to this language. Loops should occur twice to give Category\sub-category\sub-category_1 order...I am trying to use split().Ouput should be like below import csv with open('D:\\test.csv', 'rb') as f: reader = csv.reader(f, delimiter='',quotechar='|') data = [] for name in reader: data[name] = [] A: And if you read the lines of your csv and access the data then you can manipulate the way you want later. cats = {} with open('my.csv', "r") as ins: # check each line of the fine for line in ins: # remove double quotes: replace('"', '') # remove break line : rstrip() a = str(line).replace('"', '').rstrip().split('|') if a[0] != 'CatNo': cats[int(a[0])] = a[1:]; for p in cats: print 'cat_id: %d, value: %s' % (p, cats[p]) # you can access the value by the int ID print cats[1001] the output: cat_id: 100, value: ['Best Sellers', 'Best Sellers'] cat_id: 1001, value: ['New this Month', 'New Products\\New this Month'] cat_id: 10, value: ['New Products', 'New Products'] cat_id: 1003, value: ['Previous Months', 'New Products\\Previous Months'] cat_id: 110, value: ['Promotional Material', 'Promotional Material'] cat_id: 120, value: ['Discounted Products & Special Offers', 'Discounted Products & Special Offers'] cat_id: 1002, value: ['Last Month', 'New Products\\Last Month'] ['New this Month', 'New Products\\New this Month'] Updated script for your question: categories = {} def get_parent_category(cat_id): if len(cat_id) <= 2: return ''; else: return cat_id[:-1] with open('my.csv', "r") as ins: for line in ins: # remove double quotes: replace('"', '') # remove break line : rstrip() a = str(line).replace('"', '').rstrip().split('|') cat_id = a[0] if cat_id != 'CatNo': categories[cat_id] = { 'parent': get_parent_category(cat_id), 'desc': a[1], 'long_desc': a[2] }; print 'Categories relations:' for p in categories: parent = categories[p]['parent'] output = categories[p]['desc'] while parent != '': output = categories[parent]['desc'] + ' \\ ' + output parent = categories[parent]['parent'] print '\t', output output: Categories relations: New Products New Products \ Best Sellers New Products \ Discounted Products & Special Offers New Products \ Best Sellers \ Previous Months New Products \ Best Sellers \ Last Month New Products \ Best Sellers \ New this Month
[ "unix.stackexchange", "0000149104.txt" ]
Q: Keymaping for re-indent source code in Vim I have key mapping in my ~/.vimrc file that re-indents edited source code on the fly. It looks like as follows: " press F4 to fix indentation in whole file; overwrites marker 'q' position noremap <F4> mqggVG=`qzz inoremap <F4> <Esc>mqggVG=`qzza Short explanation: mq place marker 'q' at cursor position ggVG select all text = re-indnet text `q return cursor back to position stored in 'q' marker zz center the display over the cursor a return to insert mode if called from it It basically works, but has two shortcomings. The first one is that it overwrites the q marker. I used this marker to store cursor position. I choose q because it is very unlikely that I would use this letter as a marker. Despite this, is there any more clever approach to achieve this, without destroying q marker? The second one occurs in the insert mode, when the cursor is on the beginning of a line. In such condition, F4 re-indents as expected, but also moves cursor one position right. I tried to fix it by using <C-o> instead of <Esc>, but it looks like <C-o> is applicable only to editor :commands, not to move commands. How can I fix it? A: You can use the last jump mark (m') as a temporary mark. To avoid using a different command to re-enter insert mode (i vs. a), you can use the gi command, which re-enters insert mode at the position where it was last exited: inoremap <F4> <Esc>m'ggVG=``zzgi
[ "stackoverflow", "0003612024.txt" ]
Q: HBRUSH to RGB value Can you get the RGB value from HBRUSH or from brush id? for example: I'm looking for GRAY_BRUSH in RGB value. A: You want to use the GetObject function to return a LOGBRUSH structure that contains the brush color.
[ "stackoverflow", "0032041709.txt" ]
Q: JOptionPane parsing arrays I am new to Java and arrays. I am trying to parse String input into int and into an array. import javax.swing.JOptionPane; public class OSL { String[] ColorType = {"blue", "green", "white"}; final int COLOURS = 3; // tshirt colours choices int[] Color = new int[COLOURS]; int order; public OSL() { for (int index = 0; index < ColorType.length; index++) { String orderItems = JOptionPane.showInputDialog("Please enter the number of T-Shirts for " + ColorType[index]); int items = Integer.parseInt(orderItems); } for (int index = 0; index < Color.length; index++) { JOptionPane.showMessageDialog(null, ColorType[index] + ": " + Color[index]); } } int orderItems; public int getorderItmes() { return orderItems; } public static void main(String[] args) { new OSL(); } } I can input the integer but it does not display them. A: Simply put, you never apply the quanity for each color to the Color array in any way. For example, you could do something like... for (int index = 0; index < ColorType.length; index++) { String orderItems = JOptionPane.showInputDialog("Please enter the number of T-Shirts for " + ColorType[index]); int items = Integer.parseInt(orderItems); Color[index] = items; } Which simply applies the quantity that the user inputted to each element in the Color array
[ "hardwarerecs.stackexchange", "0000006211.txt" ]
Q: Drive to store very small amount of data I am currently designing a board game whereby various cards, figurines, and basically all sorts of game items will be plugged into the main game board, which will be linked to a Raspberry Pi. As various items can be plugged into the same socket, I would like some data to be stored in each item, so that the main program loop can respond accordingly. This data would be very small: only a few bytes. What would be the best hardware to use as storage on the game items? USB drives would work well in terms of plugging in, however they seem a bit overkill in terms of storage size. Any suggestions welcome! A: Well, there is an argument to be made here: Which is more important, low cost, or low capacity? I would suggest this: THZY 512M USB Simply based on low price this would work. Capacity is 512MB, so not overboard.
[ "math.stackexchange", "0001885862.txt" ]
Q: Logical proposition for "Every positive integer can be written as the sum of 2 squares" I am to formulate the logical proposition for Every positive integer can be written as the sum of 2 squares (domain of integers) One of the previous questions was Formulate the logical proposition for the sentence "The number 100 can be written as the sum of 2 squares" (domain of integers) And my answer was $$ \exists x \exists y(x^2 + y^2 = 100)$$ So I thought to take the same approach with Every positive integer can be written as the sum of 2 squares And came up with $$ \forall x \exists a \exists b (a^2 + b^2 = x)$$ But there's no where stating that $x$ is positive, so would $$ \exists x \exists a \exists b (a^2 + b^2 = x)$$ be correct instead? If someone could tell me where I went wrong or give me a hint I'd greatly appreciate the help, thank you very much. A: Why would you switch from "forall" to "exists" if you wanted to specify "$x$ is positive"? You're going to want $$(\forall x > 0)(\exists a \exists b)(a^2+b^2 = x)$$ or, if your language doesn't let you formulate that, $$(\forall x)[x > 0 \to (\exists a \exists b)(a^2+b^2 = x)]$$ As an aside, the proposition is false: $3$ cannot be written as the sum of two squares. It is necessary and sufficient that primes $3 \pmod{4}$ appear only to even powers in the prime factorisation. A: You can solve this question by using your previous answer, $$P_{100}:= \exists\ x,y\ (x^2 + y^2 = 100)$$ where you replace $100$ by "any positive integer", let $z$: $$\forall z>0\ P_z,$$ giving $$\forall z>0\ \exists\ x,y\ (x^2 + y^2 = z).$$ ($x,y,z\in\mathbb Z$ is left implicit.) A: You can formulate this statement as: $\large\forall_{x\in\mathbb{N}}\exists_{a,b\in\mathbb{N}}:x=a^2+b^2$ If you're worried about $0\in\mathbb{N}$ (which is a matter of definition), then you can use $\mathbb{Z^+}$ instead. BTW, the statement itself is false.
[ "tex.stackexchange", "0000038248.txt" ]
Q: How to refer to a chapter with a word I would like to refer to my chapters with the notation "First Chapter", "Second Chapter" etc, rather than "Chapter 1", "Chapter 2", etc. How can I do this? \documentclass{scrreprt} \usepackage[english]{babel} %Loaded here: microtype,graphicx,booktabs,caption,tabularx,hyperref,amsmath \usepackage{classicthesis-preamble} \usepackage{classicthesis} % A personalization of description environment \renewcommand{\descriptionlabel}[1]{\hspace*{\labelsep}\small\textsc{#1}} \begin{document} \chapter{MyChapter} \label{ch:first} \begin{description} \item [In the \ref{ch:first}] I yada yada yada \end{description} \end{document} A: The right package to use, along with refcount, is numname: \usepackage{refcount,numname} \newcommand{\refc}[1]{\ordinaltoName{\getrefnumber{#1}} Chapter} In the \refc{ch:first} we do something. To get also a link, \newcommand{\refc}[1]{\hyperref[#1]{\ordinaltoName{\getrefnumber{#1}} Chapter}} A: You may use something like \documentclass{scrreprt} \usepackage[english]{babel} %Loaded here: microtype,graphicx,booktabs,caption,tabularx,hyperref,amsmath \usepackage{classicthesis-preamble} \usepackage{classicthesis} % A personalization of description environment \renewcommand{\descriptionlabel}[1]{\hspace*{\labelsep}\small\textsc{#1}} \usepackage{refcount} \newcommand*{\refc}[1]{% \setrefcountdefault{0}% \hyperref[#1]{\ifcase\getrefnumber{#1} ??? \or First \or Second \or Third % please extend this on your own \else A kind of yellow \fi Chapter}} \begin{document} \chapter{MyChapter} \label{ch:first} \begin{description} \item [In the \refc{ch:first}] I yada yada yada \end{description} \end{document} to do this. There's also a package engord for english ordinals, that may be used instead of a \ifcase construct. Alternative you may patch \refstepcounter and redefine \p@chapter to make all \ref to a chapter to be text references: \documentclass{scrreprt} \usepackage[english]{babel} %Loaded here: microtype,graphicx,booktabs,caption,tabularx,hyperref,amsmath \usepackage{classicthesis-preamble} \usepackage{classicthesis} % A personalization of description environment \renewcommand{\descriptionlabel}[1]{\hspace*{\labelsep}\small\textsc{#1}} \makeatletter % 1. Allow \p@… to be a command with an argument \renewcommand*\refstepcounter[1]{\stepcounter{#1}% \protected@edef\@currentlabel {\csname p@#1\expandafter\endcsname\csname the#1\endcsname}% } % Then ignore this argument at `\p@chapter` and use the completely different % output instead. \renewcommand\p@chapter[1]{\ordinalnumbertext{\value{chapter}} \@chapapp}% \makeatother \newcommand*{\ordinalnumbertext}[1]{% \ifcase#1 ??? \or First \or Second \or Third \else A kind of yellow \fi } \begin{document} \chapter{MyChapter} \label{ch:first} \begin{description} \item [In the \ref{ch:firsta}] I yada yada yada \end{description} \appendix \chapter{MyChapter} \label{ch:firsta} \begin{description} \item [In the \ref{ch:first}] I yada yada yada \end{description} \end{document} This does even work with appendices like shown in the example.
[ "stackoverflow", "0019859128.txt" ]
Q: OnCard or OffCard encryption? Because of security reason I should store encrypted data on Java card, so the question is should I encrypt data with Offcard application and send it to Java card or send pure data to Java card and let Java card encrypt it by itself? Anyway, I want to know the best way o store data on Java card and what is the best sequence diagram in order to consider security on data? Thanks in advance A: Basically it depends what you call the off-card application, and whether you consider it trusted (or to which extent you consider it trusted). In a system involving a card application, a mobile phone application, and a back-end server, usually the server and the card application are trusted, anything inbetween isn't (which means communication has to be done ciphered). The card will want to authenticate any incoming data before processing it. In that case the mobile application is not very much trusted, for various reasons, including the shortcomings of mobile OS's security. You need to elaborate a bit more on your use case. What are the attacks you wish to prevent against, and what part of your system do you trust ? Anyway to answer your question, the private data managed by the card application does not need to be encrypted before being stored, because the storage can be considered safe.
[ "stackoverflow", "0015262548.txt" ]
Q: Replace some text in a PDF template using Prawn in Ruby I am generating a PDF in Prawn using a template using code similar to: Prawn::Document.new(:template => "template.pdf") This works great, and I can add to the document in the normal way - however I would like to search for and replace some text that gets added from the template. Is this possible with Prawn? Looking at the Prawn code it does the following: if options[:template] fresh_content_streams(options) go_to_page(1) else ..... end ..... # adds a new, empty content stream to each page. Used in templating so # that imported content streams can be left pristine # def fresh_content_streams(options={}) ..... end So it creates a new content stream to prevent changing the data given in the template - the question is can I look into and change the existing stream with Prawn? A: I asked about this at Github here. Apparently it is not possible, and is a lot more complex than I realized.
[ "stackoverflow", "0020778110.txt" ]
Q: Is it possible to customize the title popup in tag? Sometimes we can add tips for a href link, like: <a href="#" title="This link leads you to Page1">Page1</a> When the cursor is on the link, sometimes it will take a quite long time to show up the text. Is it possible to change the time, duration and even animation with pure CSS? Thanks, A: In css3 you style your tooltip using :after & adding a class to the element. css3 .tooltip:hover:after { background:rgba(0,0,0,0.7); color:#fff; content:attr(rel); display:block; margin-top:-42px; position:absolute; white-space:nowrap; } html <a href="#" rel="This link leads you to Page1" class="tooltip">Page1</a> http://jsfiddle.net/eRQLQ/ And this is with time & delay .tooltip:after{ background:rgba(0,0,0,0.7); color:#fff; content:attr(rel); display:block; margin-top:-42px; position:absolute; white-space:nowrap; opacity:0; -webkit-transition:opacity 1s ease 2s; } .tooltip:hover:after{ opacity:1; -webkit-transition:opacity 1s ease 300ms; } if you want more support add also the -moz,-ms and other prefixes. 300ms delay on open/close, duration 1s http://jsfiddle.net/eRQLQ/1/ 2s delay on close, duration 1s http://jsfiddle.net/eRQLQ/2/ EDIT complex http://jsfiddle.net/eRQLQ/3/ EDIT 2 multiple elements inside a container with images arrtibute values and custom text.less html. http://jsfiddle.net/eRQLQ/8/
[ "stackoverflow", "0023847148.txt" ]
Q: Replace string value in C#? I am new to C#, and need a little help, i know in PHP that i can to something like this $SelectedEvent="event selected"; if (i > 0) { $SelectedEvent = "event"; } It replace a string easy, but in c# that is not working ok, here is example code i have that is not working string SelectedEvent = "event selected"; if (i > 0) { SelectedEvent = "event"; } This is not working like in PHP, i can not override the varible? Here is my example code EDITED for (int i = 0; i < Model.Items.Count; i++) { string SelectedEvent = "event selected"; if (i > 1) { string SelectedEvent = "event"; } } A: You should not redeclare the variable twice but only modify its value: for (int i = 0; i < Model.Items.Count; i++) { string SelectedEvent = "event selected"; if (i > 1) { SelectedEvent = "event"; } // here you can use the SelectedEventVariable // its value will be "event selected" on the first and second // iterations and "event" on subsequent }
[ "stackoverflow", "0029161812.txt" ]
Q: A try-catch one liner (like "??" or ternary operator) So we have ternary operators. Great! Then there's the ?? operator, which does a coalesce over a nullable variable. Example: string emptyIfNull = strValue ?? ""; Question: Is it possible to implement a simple operator like this for a try-catch? Example: string result = CoalesceException(someExpression, ""); public static T CoalesceException<T>(expression, defaultValue) { try { return evaluate expression; // ? } catch { return defaultValue; } } Is it possible to implement a method that can be used as easily as possible, or even some kind of coalesce-like operator? A: You can: public static T CoalesceException<T>(Func<T> func, T defaultValue = default(T)) { try { return func(); } catch { return defaultValue; } } but I'm not sure this is what you want... use: string emptyIfError = CoalesceException(() => someExpressionThatReturnsAString, ""); for example... string shortString = null; string emptyIfError = CoalesceException(() => shortString.Substring(10), ""); will return "" instead of NullReferenceException important The function, as written, will cause the "evaluation" of defaultValue always. Meaning: string Throws() { throw new Exception(); } string str1 = somethingTrue == true ? "Foo" : Throws(); Here an exception won't be thrown, because Throws() won't be evalued. The same happens with the ?? operator. string str2 = CoalesceException(() => ((string)null).ToString(), Throws()); This will cause an exception before entering in CoalesceException. Solution: public static T CoalesceException<T>(Func<T> func, Func<T> defaultValue = null) { try { return func(); } catch { return defaultValue != null ? defaultValue() : default(T); } } Use: string emptyIfError = CoalesceException(() => someExpressionThatReturnsAString, () => "");
[ "stackoverflow", "0019080637.txt" ]
Q: Go(lang) memory usage: RSIZE growing and VSIZE of 139GB? I am writing my first webserver/webservices program in Go and I realized that the RSIZE (as shown by the command line program "top") grows after repeating the same request to my webservices. Does that means there is a memory leak? I also noticed that both my app and the go process on "top" have a VSIZE of 139GB (both of them exactly that size). Is it normal? I am using Go 1.1.2 on OS X 10.8 Many Thanks A: Big VSIZE doesn't mean you're really using physical memory; wouldn't worry about that. RSIZE growing after a single request also isn't worrying. RAM's reclaimed by garbage collection, which costs CPU cycles, so Go and other GC'd languages wait many requests until they need RAM freed up (or at least until a lot of RAM has been allocated) to run a collection. Fewer collections => less CPU time spent. Leaks in the usual sense are rare because the GC should eventually free memory you aren't holding a reference to. If you have buffers that grow as needed but never shrink, those can have a leak-like effect, and if you accidentally hold a reference to memory that's really dead you can have problems. But unless the process keeps growing forever, I wouldn't assume you're having that problem here. Here are some memory-management tips for Go; some indirectly apply to other languages, too: You often don't need to worry. Collection is often pretty fast and you often have a lot of RAM to play with relative to the size of your data. Before you dive in, be sure there's a problem there to solve. :) runtime.ReadMemStats(ms) can tell you how long your program has spent in GC, along with lots of other useful information like how much you're allocating (see runtime module docs at http://golang.org/pkg/runtime/) If you're spending too much time in GC and don't know why, memprofile is the next step; a full example involving giving a program an optional -memprofile flag is on the Go blog: http://blog.golang.org/profiling-go-programs In general, you reduce GC's by reducing unneeded allocations, especially allocations of big objects (buffers holding whole HTTP responses, say). Sometimes there are natural ways to do that without dirtying your program--you can reuse an object across several iterations of a loop instead of allocating each time, for example. Other times, you can recycle old objects instead of making new ones; the standard sync.Pool package helps with that, and there's a nice general description of recycling (from before sync.Pool was standard) on the CloudFlare blog. Happy go-ing!
[ "stackoverflow", "0015595756.txt" ]
Q: Undefined method even after method_missing handling I'm studying Ruby and try to implement method_missing, but it's not working. For example, I want to print method name after find_ but ruby raises "undefined method 'find_hello'" when i call it on Book instance. TEST_05.RB module Searchable def self.method_missing(m, *args) method = m.to_s if method.start_with?("find_") attr = method[5..-1] puts attr else super end end end class Book include Searchable BOOKS = [] attr_accessor :author, :title, :year def initialize(name = "Undefined", author = "Undefined", year = 1970) @name = name @author = author @year = year end end book = Book.new book.find_hello A: You are calling method on object which looks for instance_level method. So you need to define instance_level method_missing method: module Searchable def method_missing(m, *args) method = m.to_s if method.start_with?("find_") attr = method[5..-1] puts attr else super end end end class Book include Searchable BOOKS = [] attr_accessor :author, :title, :year def initialize(name = "Undefined", author = "Undefined", year = 1970) @name = name @author = author @year = year end end book = Book.new book.find_hello #=> hello When you use self with method definition. It is defined as class level method. In your case Book.find_hello will output hello.
[ "stackoverflow", "0044898412.txt" ]
Q: dynamic Google Map triggering the null object reference error I am trying to add a dynamic google map to a fragment, this fragment contains a simple form which is working ok, i am getting an error when i add the google map part. Unable to start activity ComponentInfo{com.jdplee.proyecto/com.jdplee.proyecto.ClientDetailActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.jdplee.proyecto.ClientDetailFragment com.jdplee.proyecto.ClientDetailFragment.newInstance()' on a null object reference What i have is a mainActivity with a button that opens a detail view, this is done using a second Activity: public class ClientDetailActivity extends AppCompatActivity { public static final int REQUEST_ADD_TASK = 1; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.client_detail); ClientDetailFragment mClientDetailFragment = (ClientDetailFragment) getSupportFragmentManager().findFragmentById(R.id.cd_fragment_container); if (mClientDetailFragment == null) { mClientDetailFragment = ClientDetailFragment.newInstance(); utilities.addFragmentToActivity(getSupportFragmentManager(), mClientDetailFragment, R.id.cd_fragment_container); } } } the client_layout only has a FrameLayout where the fragment is going to be put, the fragment class is: public class ClientDetailFragment extends Fragment { private static final int PERMISSION_REQUEST_CODE = 1; private FusedLocationProviderClient mFusedLocationProviderClient; public static ClientDetailFragment newInstance() { return new ClientDetailFragment(); } public ClientDetailFragment(){ //required empty constructor } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.client_detail_fragment, container, false); if (getChildFragmentManager().findFragmentById(R.id.cd_maplocation) == null) { SupportMapFragment mapFragment = new SupportMapFragment(); getChildFragmentManager() .beginTransaction() .replace(R.id.cd_maplocation, mapFragment) .commit(); } return root; } and this fragment has his layout which inside has the framelayout for the google map: <FrameLayout android:id="@+id/cd_maplocation" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1"/> that is why i am using getChildFragment(), for me all this makes sense, i dont get why the error, am i missing something? A: put this thing on onActivityCreated() if (getChildFragmentManager().findFragmentById(R.id.cd_maplocation) == null) { SupportMapFragment mapFragment = new SupportMapFragment(); getChildFragmentManager() .beginTransaction() .replace(R.id.cd_maplocation, mapFragment) .commit(); }
[ "stackoverflow", "0058491482.txt" ]
Q: Increment column value when certain conditions are met in Excel I am trying to create a formula that increments values for 2 columns based on the previous row, the caveat being that it should increment by 1 when a certain value is present and increment by 2 when another value is present. I have shown the expected output in columns ID and NUMBER. You can see 3 sets of data that repeat, this is highlighted by the ID column, this value should increment by 1 every 24 rows - 63, 64, 65 - this can be done manually but if there is a formula for this it that would be very useful. The main part of this question is column NUMBER, when column C changes to 'emr_p_file' the NUMBER column should increment by 2 but when the next row changes to 'L2_*' then it should only increment by 1. Row 1 values for ID and NUMBER can be static, from row 2 onwards they should be calculated by a formula of some sort. Is something like this possible in excel, if so please help. CSV export: link:https://pastebin.com/zkjsB9L7 A: The starting ID and NUMBER in cell F1 and G1 will be static, in cell F2 enter the following formula and drag it down: =F1+(MOD(ROW(1:1),24)=0) the logic is to use ROW function to return the row number from previous row, and use MOD function to find out if it is fully divisible by 24, if so increase the previous ID by 1 (which is TRUE returned by the equation in the brackets). in cell G2 enter the following formula and drag it down: =G1+IF(C2=C1,0,IF(FIND("_",C1)=3,2,1)) the logic is to use nested IF functions to find out if the data set is the same as the previous data set, if so returns 0, if not means there is a change of data set. The next IF will find out if the old data set starts by LR or emr, if former return 1 otherwise 2. I notice that your example starting Row 49 is NOT increasing the values in Column G: NUMBER as prescribed. Can you please clarify if you provided incorrect expected outcome for those rows or if there is any missing criteria you did not mention in your post?
[ "stackoverflow", "0020282273.txt" ]
Q: Weird output from Android TextView I am trying to run a ping command from my android app and to see the output in a TextView , but the result is some gobbledygook. This is my output: java.io.BufferedReader@4144f2d0 And this is my code: try { Process process = Runtime.getRuntime().exec("ping -c 5 192.168.1.2"); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); txtview=(TextView)findViewById(R.id.textView); txtview.setText("output:\n"+in); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } A: you need to read a string from BufferedReader BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder total = new StringBuilder(); String line; while ((line = in .readLine()) != null) { total.append(line); } txtview=(TextView)findViewById(R.id.textView); txtview.setText("output:\n"+total.toString());
[ "stackoverflow", "0000746414.txt" ]
Q: What is the best way to get all Windows startup processes using Windows API? I know there are startup folders and certain registry keys I need to look into. But how to do that using Windows API? I'm interested to know for Windows XP and Vista. Thanks for your time. A: There is no single API to get all the programs that run while the system is starting up. Consider all the things that Autoruns shows. Updates to that program occasionally allow it to show new classes of programs, and since those are updates to the program and not to the OS, it's obviously not some API that's changing to include more things. Rather, it's the program that's gradually expanding its notion of what an "auto-run program" is. Work out what you wish to consider to be a "startup process," and then you can determine what APIs or other techniques you can combine to find out what all those processes are. Among the places to look include the following: The "run" registry key, like AJ mentioned. The "startup" menu, as given by various constants used with ShGetFolderPath and some of its related functions. Tasks scheduled to run on login. Services. Each bullet point includes at least one link to a page on MSDN that should get you started. If you need more, consider asking some more specific questions.
[ "math.stackexchange", "0000034358.txt" ]
Q: Finding a derivative I'm working through a book on relativity so this may end up being a physics question but I'm pretty sure that my problem is mathematical so I'm asking here. In deriving the "special Lorentz transformations", (where the axes of the second coordinate system, $S'$ are parallel to the those of the first, $S$, and movement is along the $x$, $x'$ axes with velocity $v$) the author notes that because $y = y'$ and $z = z'$, the requirement $$ x_1^2 + x_2^2 + x_3^2 - (ct)^2 = x_1'^2 + x_2'^2 + x_3'^2 - (ct')^2 $$ reduces to $$ x_1^2 - (ct)^2 = x_1'^2 - (ct')^2 $$ and introduces the variables $$ x_4 = ict, x_4' = ict' $$ to get $$ x_1^2 + x_4^2 = x_1'^2 + x_4'^2 $$ giving $$ \begin{eqnarray} x_1' &=& x_1\cos\phi + x_4\sin\phi\\ x_4' &=& -x_1\sin\phi + x_4\cos\phi\\ \end{eqnarray}. $$ A point at rest in $S$, i.e. for which $\frac{dx_1'}{dx_4'} = 0$ must then have $\frac{dx_1}{dx_4} = \frac{-iv}{c}$. The author is using the notation for single variable derivatives here. It seems to be that they should be partials. From here, he says that the transformation rules given above imply $$ \frac{dx_1}{dx_4'} = \frac{\frac{dx_1}{dx_4}\cos\phi + \sin\phi}{-\frac{dx_1}{dx_4}\sin\phi + \cos\phi} $$ I can't get this. I've tried inverting the transformation and taking the total derivative $$ \frac{dx_1}{dx_4'} = \frac{\partial x_1}{\partial x_4'} + \frac{\partial x_1}{\partial x_1'}\frac{dx_1}{dx_4'} = -\sin\phi $$ because $\frac{dx_1'}{dx_4'} = 0$. Treating it like a partial gets the same result. Implicitly differentiating and solving for the derivative gets the same result as well. I can't get any result other than $-\sin\phi$ How an I supposed to take this derivative? Thanks for any pointers! A: First, about the total/partial derivatives: He's talking about the trajectory of a point at rest, not about a coordinate transformation, so it's appropriate to take the total derivative with respect to $x_4'$ -- that's like taking a total time derivative along a trajectory in classical mechanics. $\partial x_1'/\partial x_4'$ would only make sense if you specified which other coordinates are meant to be held fixed; if you apply the usual interpretation that $\partial x_4'$ means that the other primed coordinates are held fixed, then $\partial x_1'/\partial x_4'=0$ by definition, independent of any points being at rest or not. I agree with Raskolnikov that there's probably a prime missing in the derivative, since this is the correct result for $\mathrm dx_1'/\mathrm dx_4'$. (You can get it by differentiating both transformation laws with respect to $x_4$.) There's no contradiction with this being $0$ for a point at rest -- the one is a general transformation law for the coordinates, the other is a statement about a certain trajectory. I always find it surprising how little care is taken in books and the like to distinguish these two concepts.
[ "stackoverflow", "0046502756.txt" ]
Q: How can I update the value of a field in every row of a list? I have this class: public class Test { public string Id { get; set; } public int Number { get; set; } public int DoubleNumber { get; set; } } and a list List<Test> myTestList; How can I make the value of the field DoubleNumber in myTestList equal to twice the value of Number? Note that I am okay to create another list if that's needed. A: If I understand your question correctly: foreach(Test item in myList) { item.DoubleNumber = 2*item.Number; } Or, if it's ok, just remove the setter and modify the getter to return 2x Number: public class Test { public string Id { get; set; } public int Number { get; set; } public int DoubleNumber { get { return 2* this.Number; } } //completely remove setter } Or, if you still want to be able to modify DoubleNumber: public class Test { private int m_num; private int m_doubleNum; public string Id { get; set; } public int Number { get { return this.m_num; } set { this.m_num = value; this.m_doubleNum = 2 * value; //when Number is set, update m_doubleNum too } } public int DoubleNumber { get { return this.m_doubleNum; } set { this.m_doubleNum = value; //allow manual setting of DoubleNumber //or maybe also modify Number here? //this.m_num = value / 2; } } }
[ "stackoverflow", "0003173303.txt" ]
Q: What is PCT for a materialized view? Saw it in a reference manual. What is PCT for a materialized view? What is "Partition Change Tracking"? A: From the Oracle documentation itself : "It is possible and advantageous to track freshness to a finer grain than the entire materialized view. The ability to identify which rows in a materialized view are affected by a certain detail table partition, is known as Partition Change Tracking. When one or more of the detail tables are partitioned, it may be possible to identify the specific rows in the materialized view that correspond to a modified detail partition(s); those rows become stale when a partition is modified while all other rows remain fresh."
[ "stackoverflow", "0033578296.txt" ]
Q: CoreData multiple persistent store coordinator? I can't fully grasp the CoreData terms. I have created two .xcdatamodeld files for two conceptually separate dataset. One is about caching static data which I downloaded from the net. One is about temporary posts which a user has written but not submitted to the server yet. These two dataset doesn't need to know each other at all. I want a setup that would give me least headache when I try to update either one. Would I need two separate persistent store coordinator? or two separate persistent store? and what does that mean anyway? ** Edit I guess Mundi suggests something like the following. 1 coordinator --- store1 --- model1 \ \ ----- store2 --- model2 How can I achieve that in code? I have the following codes (copied from tutorial sites) and the structure is more or like psc --- model1 \ \ --- store1 rather than psc --- model1 --- store1 My existing code looks like.. NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CachedURLResponse" withExtension:@"momd"]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"test.sqlite"]; NSError *error = nil; [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error] How do I achieve the separate stores for models in one coordinator? I could live with separate tables for each model in RDMS world. I could later update the table definition, and migrate data just as easily as I had two separate databases. I'm not sure how easy it would be to update different tables(models) in one database. A: Conceptually a persistent store is analogous to a database; it's a place to store data which conforms to some schema. A persistent store coordinator manages reads and writes to one or more persistent stores. How you want to structure your CoreData stack probably depends on how you want to query the data. If these two data sets are completely distinct you might give each one it's own store and coordinator and managed object context(s). However in that case you won't be able to construct a query (via a NSFetchRequest) for "all posts both saved or unsaved" and you might have to do some extra work to keep track of when a post moves from one state to the other to make sure you don't store a version of the same post in both stores. If you do need to query across both sets of data then you'd need a single coordinator which can manage which entities are saved in each store. That requires you to do some work in the coordinator but might allow the rest of the app to be ignorant of the mechanics of these persistent stores. You'll need to decide which path would be easier for you to work with and maintain.
[ "stackoverflow", "0018309864.txt" ]
Q: sec:authorize and sec:authentication annotations don't work I have a Spring + Thymeleaf project with the following view code. <!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Contacts</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <div id="content"> <h1>Welcome to the site!</h1> <p th:if="${loginError}">Wrong user or password</p> <form th:action="@{/j_spring_security_check}" method="post"> <label for="j_username">Email address</label>: <input type="text" id="j_username" name="j_username"/> <br/> <label for="j_password">Password</label>: <input type="password" id="j_password" name="j_password"/> <br/> <input type="submit" value="Log in"/> </form> </div> <div sec:authorize="isAuthenticated()"> User: <span sec:authentication="name">miquel</span> </div> </body> </html> The sec:authorize and sec:authentication attributes don't work as expected - the div is always shown, even if no user is logged in, and the span always reads "miquel". Follows a relevant snippet from my controller class. @RequestMapping(value = "/welcome.html") public String wellcome() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); System.out.println("username: " + auth.getName()); return "home"; } The println statement works as expected - if no user is logged in, it prints "anonymousUser", otherwise the username. What am I doing wrong? A: After comparing my application closely to the Thymeleaf & Spring Security demo applicaiton, I discovered the source of the error. Apparently, in order for Thymeleaf to process the sec:authorize and sec:authentication attributes, you need to register SpringSecurityDialect as an additional dialect of the template engine bean. <bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver" /> <property name="additionalDialects"> <set> <bean class="org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect" /> </set> </property> </bean> This is surprising as there is no mention of that fact on the related Thymeleaf documentation page. I hope this helps others who will face the same issue in future. A: In Spring Boot I just had to add the following dependency: <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> </dependency> A: For the java config version, it worked for me too by adding the spring security dialect: @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(new TilesDialect()); templateEngine.addDialect(new SpringSecurityDialect()); return templateEngine; }
[ "stackoverflow", "0016685200.txt" ]
Q: NSDate date with timezone and no localization of the formating I need to get the date+time+timezone of the device without any localized text (I was getting arabic letters and different time formats from different countries using [nsdate date] ) Input code: NSDate *date = [NSDate date]; What I get: ۱۳۹۲-۰۲-۳۱ ۱۰:۰۳:۱۶ 0000 - NSString *dateString = [NSString stringwithformat:@"%@",[NSDate date]]; another example (bad) 1392-02-31 10:04:56 0000 Desired Result: 22-05-2013 22:50:00 +0002 (day-month-year hour-minute-second timezone) How do I do this? A: Please use this code to convert it to your system time. NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init]; [formatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; [formatter1 setTimeZone:[NSTimeZone systemTimeZone]]; NSDate * TodaysDate=Date you want to convert; NSString *dateStrToSave =[formatter1 stringFromDate:TodaysDate]; and let me know if it works or not.
[ "stackoverflow", "0039157675.txt" ]
Q: How to get linux user id by user name? In linux, If I only have the user name, how to get the user id? I used man getuid, but can't find any clues about it. EDIT1: Sorry , I want to get the user id by api. I don't like forking a another process to do it such as calling system function. A: You can use getpwnam to get a pointer to a struct passwd structure, which has pw_uid member. Example program: #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <pwd.h> int main(int argc, char *argv[]) { const char *name = "root"; struct passwd *p; if (argc > 1) { name = argv[1]; } if ((p = getpwnam(name)) == NULL) { perror(name); return EXIT_FAILURE; } printf("%d\n", (int) p->pw_uid); return EXIT_SUCCESS; } If you want a re-entrant function, look into getpwnam_r. A: Simply use the id command id username [root@my01 ~]# id sylvain uid=1003(sylvain) gid=1005(sylvain) groups=1005(sylvain)
[ "crypto.stackexchange", "0000009684.txt" ]
Q: Pre-image resistant but not 2nd pre-image resistant? Are there any cryptographic hash functions for which there is a known pre-image attack, or a known second pre-image attack, but not both? The attack doesn't have to be practical - just anything that beats the security claim of the hash function. Intuitively, 2nd pre-image attacks would be easier to find than pre-image attacks, but I'm not aware of any examples or that either property implies the other. I believe there are no known pre-image attacks on the common crop of hash functions in use today, so I'm interested in historic, obsolete and proposed-but-not-adopted hash functions, but not toy hash functions constructed specifically to demonstrate the possibility of such attacks. A: A cryptographic hash function $f : \{0,1\}^{*} \to \{0,1\}^n$ has three properties: (1) preimage resistance, (2) second-preimage resistance, and (3) collision resistance. Even further, these properties form a hierarchy where each property implies the one before it, i.e., a collision-resistant function is also second-preimage resistant, and a second-preimage resistant function is also preimage-resistant (with a condition on $f$). In the case of (3) ⇒ (2), it's not too hard to see why: if an adversary cannot find any colliding message pairs, then they certainly cannot find a colliding message when one of the messages is fixed. However, (2) ⇒ (1) is substantially trickier. For some intuition, consider a second-preimage resistant hash function $f$ that was not preimage resistant (modeled by being given access to a preimage-finding oracle). Suppose you were given a $m_1$; then you could compute $H(m_1)$ and consult the oracle for the preimage of $H(m_1)$. The oracle would then return a $m_2$ such that $H(m_1) = H(m_2)$. This is very nearly a second preimage. The only question is if $m_1 \ne m_2$. Intuitively, given that $f$ maps infinitely-many inputs to a finite number of outputs, there "should be" a high probability that $m_1 \ne m_2$. For all real-life hash functions, this is pretty much the case, so a second-preimage resistant hash function should not lack preimage resistance. However, it is possible to define "pathological" hash functions that have perfect, provable second-preimage resistance but not preimage resistance. The example given in chapter 9 of the Handbook of Applied Cryptography is this: $$f(x) = \begin{cases} 0 || x & \text{if } x \text{ is } n \text{ bits long}\\ 1 || g(x) & \text{otherwise} \end{cases}$$ where $g(x)$ is a collision-resistant hash function. In this case, for digests beginning with $0$, it's trivial to find a preimage (indeed, it's just the identity function), but such cases are provably second-preimage resistant, as there are no possible second preimages. In other words, this $f$ is bijective across the space of $n$-bit inputs. To be more precise about when (2) ⇒ (1), Rogaway and Shrimpton have presented a theoretical analysis of the various relations between the three properties listed above in their Cryptographic Hash-Function Basics. Essentially, their analysis treats a hash function as having a finite, fixed-length domain, i.e. $f : \{0,1\}^m \to \{0,1\}^n$, wherein they show "conventional implications", like the implication (3) ⇒ (2); these are essentially "true" implications in the sense that they are unconditional, and "provisional implications", like the implication that (2) ⇒ (1); these are conditional in nature, relying on how much $f$ compresses the message space (as the message space gets larger relative to the digest space, the "stronger" the implication in a probabilistic sense). So, provisional implications are essentially true if a hash function compresses the message space to a sufficient degree. (The "sufficient" example they provide is a hash compressing 256-bit messages to 128 bits.) Hence, second-preimage resistance implies preimage resistance only if the function in question compresses its input sufficiently. For length-preserving, length-extending, or low-compression functions, second-preimage resistance does not necessarily imply preimage resistance (as stated by the authors on page 8 about halfway down the page). This should be intuitive given the above algorithm for finding second preimages given a preimage oracle. If you are expanding 6-bit inputs to 256 bits, it's actually quite unlikely that a preimage oracle would be able to find a second preimage. This isn't a formal argument, by any means, but it's a nice heuristic one. Now, back to real life. Given the above algorithm for using a preimage oracle to find second preimages, I would not expect any real-life hash functions to have preimage attacks and not second-preimage attacks, especially since real hash functions typically compress data well. On the other hand, I'm not personally aware of any historically-used, non-toy cryptographic hash function which has a second-preimage attack but not a preimage attack. Typically, collision resistance is the first thing attacked by cryptanalysts since it is (in a sense) the "hardest" property to satisfy. But if a hash function is found to be broken with regard to collisions, cryptanalysts typically go straight for the heart: preimage attacks. So, I don't know how much luck you'll have trying to find such a hash function. You can look at the hash function lounge for some historic hash functions; it hasn't been updated since 2008, apparently, but still contains some useful info. I glanced through a few attacks and found mostly collision and preimage attacks, but you may have more luck. A: In their paper Second Preimages on $n$-Bit Hash Functions for Much Less than $2^n$ Work, Kelsey and Schneier provide: a second preimage attack on all $n$-bit iterated hash functions with Damgard-Merkle strengthening and $n$-bit intermediate states, allowing a second preimage to be found for a $2^k$-message-block message with about $k\times2^{n/2+1}+ 2^{n-k+1}$ work as opposed to the expected $2^n$ work. This is firmly in the realms of theoretical attacks, but meets the criteria of being a second-preimage attack, not a preimage attack, and it applies to all the commonly used hash functions prior to SHA3. The example they provide: a second pre-image can be found for a $2^{60}$ byte message processed with SHA1 in $2^{106}$ work rather than $2^{160}$. This is the largest message SHA1 can process; if we pick a more plausible but still large message size, say a SHA1 hash over a 4TB disk, or approximately $2^{38}$ message blocks, the work to find a second pre-image is approximately $38 \times 2^{{160/2} + 1} + 2^{160-38+1} \approx 2^{123}$. Thanks to Reid for the pointer to the Hash Function Lounge where I found this paper.
[ "superuser", "0000320692.txt" ]
Q: Redirecting audio / broadcasting audio help Okay so I have an interesting problem that I have been having a lot of trouble solving. I am trying to broadcast StarCraft 2 games to Justin TV via Dyyno Universal Broadcaster. I can either have it broadcast the game audio and the audio of my party from teamspeak without my voice, or continuously broadcast my microphone without any other audio. Currently I have solved the problem by using a headset and listening to my own microphone, so my mic is pumped through my computer's audio which Dyyno picks up on so I can broadcast my mic continuously, the game audio and my party on teamspeak. This is the exact thing I need to do but I hate listening to myself, so is there a better way to do this? or somehow create an audio device that I can pump everything I want to broadcast through and then have Dyyno listen to that and then I can just listen to the game and my party and not myself?? I know this is probably tldr but any help would be greatly appreciated. A: I would look into Soundflower by Cycling '74 http://code.google.com/p/soundflower/ It allows you to control all the audio ins and outs and where they go, internally. The link seems to be unreachable ATM and I don't know why, but I think that might be what you're looking for.
[ "stackoverflow", "0011639123.txt" ]
Q: Retrieve keywords meta tag content with Simple HTML Dom? I am using Simple HTML Dom to scrape keywords off remote web pages but I can't figure out quite how to achieve this. I am currently using the following code. $html = str_get_html($remote_html); echo $html->find("meta[keywords]")->content; And receiving the following error: Trying to get property of non-object http://simplehtmldom.sourceforge.net/ A: find() returns not an object but an array containing (in this case) 1 object. Also 'keywords' is not an attribute, but 'name' is. Use: $oHTML = str_get_html( $remote_html ); $arElements = $oHTML->find( "meta[name=keywords]" ); echo $arElements[0]->content; A: $headers = array(); $headers["title"] = $html-> find("title",0)-> plaintext; $headers["keywords"] = $html-> find("meta[name=keywords]",0) ->getAttribute('content'); $headers["description"] = $html-> find("meta[name=description]",0) ->getAttribute('content');
[ "stackoverflow", "0047012967.txt" ]
Q: jq: error: Cannot iterate over string could someone please explain below warning? input file is: { "env": "DC", "hosts" : [ { "apt_update_last_success": "1495991703", "architecture": "amd64", "hostname": "h1" }, { "apt_update_last_success": "1495991703", "architecture": "amd64", "hostname": "h2" }, { "apt_update_last_success": "1496045706", "architecture": "amd64", "hostname": "h3" }, { "apt_update_last_success": "1496045705", "architecture": "amd64", "hostname": "h4" }, { "apt_update_last_success": "1496049305", "architecture": "amd64", "hostname": "h5" }, { "apt_update_last_success": "1496049307", "architecture": "amd64", "hostname": "h6" } ] } the jq command returns what expected but also prints the warning I dont know why: $ jq -r '.[][] | select(.hostname=="h6")' ddd.json jq: error: Cannot iterate over string { "apt_update_last_success": "1496049307", "architecture": "amd64", "hostname": "h6" } please tell me how to get rid of this. thank you. A: The issue is in your notation .[][]. Your input is just an object but you are trying to present it as a "container" of "containers" .[][]. The right way is: jq '.hosts[] | select(.hostname=="h6")' ddd.json { "apt_update_last_success": "1496049307", "architecture": "amd64", "hostname": "h6" } Besides, on jq 1.5 this jq -r '.[][] | select(.hostname=="h6")' ddd.json doesn't return the expected object but only prints jq: error (at jq1:36): Cannot iterate over string ("DC")
[ "stackoverflow", "0000080234.txt" ]
Q: Open .NET form in designer mode - get "The path is not of a legal form" I attempted to open a C#/VB form in designer mode, and instead of the form, I got an ugly error message saying "The path is not of a legal form". This form used to work! What happened? Thanks to all who have answered. This question is a problem I hit a while back, and I struggled with it for a long time, until I found the answer, which I posted below in order to help other people who might have hit this problem. Thanks! A: I don't know what this error message means, but it seems to be associated with third-party controls on the form. Anyway, the solution is almost as absurd as the problem: Close the designer/error message. Open the form code. Right-click on the form code and select "View Designer". Presto! The designer opens! A: Debugging design mode would help. From here: List item In visual studio, select the project you want to debug. Right click -> Properties. Select the debugging tab. Change the debug mode to Program. Set the “Start Application” to be your visual studio IDE (C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\IDE\devenv.exe) Set your solution file in the “command line argument field”. Apply -> OK Select the project you want to debug as the startup project. Run. Set a break point in the place you want to start debug (for example, your control constructor)
[ "math.stackexchange", "0002523549.txt" ]
Q: Invertible matrices multiplication I have two square matrices $X$ and $Y$ of the order of $n \times n$. It is given that $X = I - XY$. I have to show that $X$ is invertible and that $XY = YX$. The first part is fairly easy, moving stuff around gets me to the point that $X(I + Y) = I$ and therefore $X$ multiplied by another matrix yields the identity matrix and therefore $X$ is Invertible. I am stuck at the second part which requires showing that $XY = YX$. I tried multiplying $(I-XY)B$ but it got me nowhere. A: Remark: Suppose that $AB=I$; then $BA=I=AB$. As you have mentioned $X(I+Y)=I$. Considering the above remark we can write $$X(I+Y)=I=(I+Y)X;$$ now expanding both sides, one gets that: $$X+XY=X+YX \qquad \Longrightarrow \qquad XY=YX.$$
[ "stackoverflow", "0052404171.txt" ]
Q: go get: Git settings are ignored I try to go get a repository from a private gitlab server, from a mac. I set the git config (~/.gitconfig) to use ssh instead of https : [url "[email protected]:"] insteadOf = https://gitlab.mysite.com/ When I clone the project using the https url, I get the correct replacement $ git clone https://gitlab.mysite.com/group/project $ cd project $ git remote -v origin [email protected]:group/project (fetch) origin [email protected]:group/project (push) However, when I use go get, it tries to use the https url, and fail $ go get gitlab.mysite.com/group/project package gitlab.mysite.com/group/project: unrecognized import path "gitlab.mysite.com/group/project" (https fetch: Get https://gitlab.mysite.com/group/project?go-get=1: x509: certificate signed by unknown authority) Why is go get not using my git configuration ? How can I fix that ? I know the problem is similar to this question : go get: Git settings ignored and many other question concerning private repos my problem is different A: That error occurs before the git clone call. When you call go get, it makes an HTTPS call out to the URL to check the headers and see if it provides a go get redirect. That's what's failing. And it's failing because the certificate provided by the server isn't signed by a Certificate Authority that you have specified as trusted on your local system. This could be because your internal gitlab is using an unsigned certificate, because the CA used to sign it hasn't been added to your local system, or because your workplace is using a man-in-the-middle style proxy and you don't have that proxy's CA added. You can either attempt to fix the cert issue, or simply run: go get -insecure gitlab.mysite.com/group/project The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution. Notably, this bypasses the validation of the CA used to sign the server's certificate.
[ "stackoverflow", "0002069509.txt" ]
Q: Implementing different CSS on page I want to implement different CSS style sheet using javascript or code behind on aspx page so that for different web browser my page look better. Can anyone have some solution about this problem? I try a lot to implement that but failed. A: To add to Ravia: You can use Request.Browser to get browser versions: HttpBrowserCapabilities bc = Request.Browser; if (bc.Browser == "IE" && bc.Version == "6.0") { HtmlLink link = new HtmlLink(); link.Href = ResolveClientUrl("~/CSSFile.css"); link.Attributes.Add("rel", "stylesheet"); link.Attributes.Add("type", "text/css"); Page.Header.Controls.Add(link); }
[ "stackoverflow", "0049851100.txt" ]
Q: Javascript: normalize argument in a function, should I copy it? Let's say there is a function: const foo = (arg) => { do_something }; Before I run do_something, I actually want to normalize arg to an array because the function accept string or types other than array. I know it is a bad practice to directly modify the passed argument in a function because it may be mutated and resulted in bugs, which are hard to be debugged. So, I will do something like this: const foo = (arg) => { const _arg = Array.isArray(arg) ? [...arg] : [arg]; do_something(_arg) }; As above, I actually do a shallow copy of that array(arg), and use _arg to do something afterward, and I will ensure not to mutate it (since it just a shallow copy). My question is what if I just don't copy it? i.e.: const foo = (arg) => { const _arg = Array.isArray(arg) ? arg : [arg]; do_something(_arg) }; Will it be different? Or which one is a better/healthier way of coding? Will it affect the garbage collecting or any performance issue? Thanks for the answer. A: IMO, the first approach is recommended, because the second approach often leads to the unexpected issues if do_something causes some side effects. Will it affect garbage collecting? Yes. With the first approach, _arg will be cleaned because nothing references to it. I'm not sure about performance. It depends on the size of data you handle.
[ "music.stackexchange", "0000009533.txt" ]
Q: Orchestral strings disposition (numeration meaning) It's going to be the first time I'll be trying to compose a piece to be played by an orchestra and I don't know much about orchestral strings numeration/disposition. I just ran into this Composers initiative: http://patelconservatory.blogspot.com.es/2013/01/call-for-scores.html and when reading the entry requirements, it's stated the following: Scores should be written for the following instrumentation: 2 flutes, 1 oboe, 1 clarinet, 1 bassoon, 1 horn, strings (2.1.2.1.1). What does the strings part actually mean? Thanks! A: This seems to be shorthand for the number of instruments it's written for - unfortunately there doesn't seem to be a standard, and each publisher uses it's own notation. According to Wikipedia, the strings notation 2.1.2.1.1 means 2 first violins 1 second violin 2 violas 1 cello 1 double bass A: This method of notation is in fact short hand. It saves on space and time both for the person putting the information down, and for the person reading. It is true that there is no critically-accepted standard, but there are general guidelines that composers follow when they use that shorthand method; which I will outline below: Typically, dashes are used between numbers and dots are used to denote sections. For example: 2-2-2-2.4-4-3-1 looks a little bit tidier than 2.2.2.2-4.4.3.1. It is more of a matter of personal aesthetic - as long as denotation of sections is clear. For your example, if the composition is just for string orchestra, then using dots between numbers would not be confusing as only 1 section is involved. For a wind ensemble, it would be a little different if the instrumentation is other than the accepted standard. In those cases, it would be a good idea to include instrumental abbreviations. For example, here is the shorthand instrumentation of a piece that I wrote for a large wind ensemble: picc.5.2.6.bcl.bsn.2asax.tsax.bsax.4.6.3.btbn.2euph.tba-db-perc(6)-timp. As you can see, I mix both numbers and abbreviations in order to clearly define the instrumentation in a concise way. This shorthand system is read in score order. So, if you were to see: 2-2-2-2.4-4-3-1.timp.18-16-12-8-6 Then you would read your score as having 2 flute, 2 oboe, 2 clarinet, 2 bassoon, 4 horns, 4 trumpets, 3 trombones, 1 tuba, timpani, 18 Violin I, 16 Violin II, 12 Viola, 8 'Celli, and 6 Basses. This notation always appears in that order. You might also see the string numbers omitted since orchestras (especially today) can be quite variable in size. Instead you will see / write something like " timp + strings" after the wind notation. Hope that helps.
[ "stackoverflow", "0015437088.txt" ]
Q: Reset css list count and style when nested I have following html code (simplified <ol class="step"> <li><p>some content</p></li> <li><p>some content</p> <ul class="bull"> <li><p>some nested content</p></li> <li><p>some nested content</p></li> <li><p>some nested content</p></li> </ul> </li> <li><p>some content</p></li> </ol> and I created some css to make the list items of the step class twice as big than normal font size. I've used the :before class to achieve this, and it all works fine until I have a nested list, ordered or unordered in my tree. For some reason I'm not able to 'reset'the cascaded style, so any advice on how to do it correctly is welcome. This is the css I have, if you use it you will notice the ul is also having big numbers, while actually I just want to have basic simple disc again. ol.step{ counter-reset: li; list-style: none; -webkit-padding-start: 20px; } ol.step li:before{ content: counter(li); counter-increment: li; font-size: 200%; font: Arial; position: absolute; left: -20px; padding-top : 1px; } ol.step li{ display: block; position: relative; padding-left : 10px; padding-top : 1px; } ul.bull { list-style-type: disc; counter-reset: li; } So what do I have to do to 'reset'my nested listings and let them behave nicely ? Thanks in advance ! A: If you want the li styles to only apply to the li directly under the ol.step use the direct descendant CSS selector: ol.step > li:before { content: counter(li); counter-increment: li; font-size: 200%; font: Arial; position: absolute; left: -20px; padding-top : 1px; } ol.step > li{ display: block; position: relative; padding-left : 10px; padding-top : 1px; }
[ "magento.stackexchange", "0000311832.txt" ]
Q: Magento 2 join 2 custom tables in custom module First my thanks for reading my question. I learning to program in M2 so forgive me potential strange questions. So far I managed to create a custom module and an edit page. My main database table is names dsssolutions_management_vendor. My form loads this as expected, but now I want to load additional tables to also populate my form. For this I would like to follow coding standards as good as possible. From this point I'm not sure and can't find online what the correct approach is to load by default additional database tables into my form and later maybe also easily save this data correctly, but lets start with the join to figure out correctly. For the form I use ui_component. Personally I would expect that in some way I must alter the Vendor/DataProvider so that the getData() function will load the data by default. Below my current code for this file. Notice that I altered the get id with ['general'] because I do use tabs, without M2 wont populate the edit form. <?php declare(strict_types=1); namespace DssSolutions\Management\Model\Vendor; use DssSolutions\Management\Model\ResourceModel\Vendor\CollectionFactory; use Magento\Framework\App\Request\DataPersistorInterface; class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider { protected $dataPersistor; protected $collection; protected $loadedData; /** * Constructor * * @param string $name * @param string $primaryFieldName * @param string $requestFieldName * @param CollectionFactory $collectionFactory * @param DataPersistorInterface $dataPersistor * @param array $meta * @param array $data */ public function __construct( $name, $primaryFieldName, $requestFieldName, CollectionFactory $collectionFactory, DataPersistorInterface $dataPersistor, array $meta = [], array $data = [] ) { $this->collection = $collectionFactory->create(); $this->dataPersistor = $dataPersistor; parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data); } /** * Get data * * @return array */ public function getData() { if (isset($this->loadedData)) { return $this->loadedData; } $items = $this->collection->getItems(); foreach ($items as $model) { $this->loadedData[$model->getId()]['general'] = $model->getData(); } $data = $this->dataPersistor->get('dsssolutions_management_vendor'); if (!empty($data)) { $model = $this->collection->getNewEmptyItem(); $model->setData($data); $this->loadedData[$model->getId()] = $model->getData(); $this->dataPersistor->clear('dsssolutions_management_vendor'); } return $this->loadedData; } } The database that I want to join is named dsssolutions_management_vendoraddress (I know potentially naming convention should be vendoraddresses but can change this later). In this table I have a column vendor_id that should match with the id from the vendor record I retreive. For now one-to-one but later maybe one-to-many. An potential other location to achieve this would maybe be the Vendor/edit.php. To be sure also this code below. <?php declare(strict_types=1); namespace DssSolutions\Management\Controller\Adminhtml\Vendor; class Edit extends \DssSolutions\Management\Controller\Adminhtml\Vendor { protected $resultPageFactory; /** * @param \Magento\Backend\App\Action\Context $context * @param \Magento\Framework\Registry $coreRegistry * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory */ public function __construct( \Magento\Backend\App\Action\Context $context, \Magento\Framework\Registry $coreRegistry, \Magento\Framework\View\Result\PageFactory $resultPageFactory ) { $this->resultPageFactory = $resultPageFactory; parent::__construct($context, $coreRegistry); } /** * Edit action * * @return \Magento\Framework\Controller\ResultInterface */ public function execute() { // 1. Get ID and create model $id = $this->getRequest()->getParam('vendor_id'); $model = $this->_objectManager->create(\DssSolutions\Management\Model\Vendor::class); // 2. Initial checking if ($id) { $model->load($id); if (!$model->getId()) { $this->messageManager->addErrorMessage(__('This Vendor no longer exists.')); /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); return $resultRedirect->setPath('*/*/'); } } $this->_coreRegistry->register('dsssolutions_management_vendor', $model); // 3. Build edit form /** @var \Magento\Backend\Model\View\Result\Page $resultPage */ $resultPage = $this->resultPageFactory->create(); $this->initPage($resultPage)->addBreadcrumb( $id ? __('Edit Vendor') : __('New Vendor'), $id ? __('Edit Vendor') : __('New Vendor') ); $resultPage->getConfig()->getTitle()->prepend(__('Vendors')); $resultPage->getConfig()->getTitle()->prepend($model->getId() ? __('Edit Vendor %1', $model->getVendorName()) : __('New Vendor')); return $resultPage; } } Hopefully someone can point me here in the correct direction. EDIT After testing I have added the following code to Model/Vendor/Collection protected function _afterLoad() { $select= $this->getSelect(); $select->joinLeft( array('SecondTable'=>$this->getTable('dsssolutions_management_vendoraddress')), 'main_table.vendor_id=SecondTable.vendor_id', array('*') ); echo 'Afterload function<br/>'; echo $select; echo '<br/>'; return parent::_afterLoad(); } The echo from $select now gives me the following SQL Query SELECT `main_table`.*, `SecondTable`.* FROM `dsssolutions_management_vendor` AS `main_table` LEFT JOIN `dsssolutions_management_vendoraddress` AS `SecondTable` ON main_table.vendor_id=SecondTable.vendor_id WHERE (`vendor_id` = '1') So this seems to be correct, but when I now do a die(print_r($this->loadedData)); in my DataProvider I can see that I still only the main table is coming back. If I past the SQL Query into phpmyadmin I get an warning that the vendor_id column is ambiguous. So a little closer it seems. Hopefully somebody can help me further here. A: After a lot of trial and error I found out that the following will create the expected behavior The database column for the vendor table should be different in naming convention as the join table, so I changed this to id instead of vendor_id The joined table in this case 'dsssolutions_management_vendoraddress' must have an FK relationship with the table vendor The follwing coding had to be adjusted: In Vendor/Collection.php added the code protected function _initSelect() { $this->getSelect() ->from(['main_table' => $this->getMainTable()]) ->join('dsssolutions_management_vendoraddress', 'main_table.id = dsssolutions_management_vendoraddress.vendor_id', [ 'vendoraddress_id', 'vendor_addres_type', 'vendor_street', 'vendor_zipcode', 'vendor_country', 'vendor_attention' ]); return $this; } In the file ResourceModel/Vendor.php added the following coding protected function _getLoadSelect($field, $value, $object) { $field = $this->getConnection()->quoteIdentifier(sprintf('%s.%s', $this->getMainTable(), $field)); $select = $this->getConnection() ->select() ->from($this->getMainTable()) ->where($field . '=?', $value) ->join('dsssolutions_management_vendoraddress', 'dsssolutions_management_vendor.id = dsssolutions_management_vendoraddress.vendor_id', [ 'vendoraddress_id', 'vendor_addres_type', 'vendor_street', 'vendor_zipcode', 'vendor_country', 'vendor_attention' ]); return $select; } With these changes Magento loads the join by default when you retreive data. Hopefully this solution will become handy for someone else.
[ "stackoverflow", "0012122346.txt" ]
Q: Store email account's password I'm developing an email client in PHP for IMAP accounts. Which would be the most secure way to store the account's password being able to retrieve it afterward to check emails? I guess I should encrypt it somehow. However, how can I make sure that only my app will be able to decrypt it? A: If you require login without any user interactions, then there is no secure solution. You'll need to rely on your OS's storage options which might prevent hostile unprivileged applications from reading the password. If the user entering a single password on startup is fine, then you can encrypt the other passwords with symmetric encryption, and then use a KDF, such as scrypt or PBKDF2 to derive the master key from the password (and a salt).
[ "stackoverflow", "0048050405.txt" ]
Q: NodeJS cluster, Is it really needed? I decided that i want to investigate what is the best possible way to handle big amount of traffic with NodeJS server, i did a small test on 2 digital ocean servers which has 1GB RAM / 2 CPUs No-Cluster server code: // Include Express var express = require('express'); // Create a new Express application var app = express(); // Add a basic route – index page app.get('/', function (req, res) { res.redirect('http://www.google.co.il'); }); // Bind to a port app.listen(3000); console.log('Application running'); Cluster server code: // Include the cluster module var cluster = require('cluster'); // Code to run if we're in the master process if (cluster.isMaster) { // Count the machine's CPUs var cpuCount = require('os').cpus().length; // Create a worker for each CPU for (var i = 0; i < cpuCount; i += 1) { cluster.fork(); } // Code to run if we're in a worker process } else { // Include Express var express = require('express'); // Create a new Express application var app = express(); // Add a basic route – index page app.get('/', function (req, res) { res.redirect('http://www.walla.co.il'); }); // Bind to a port app.listen(3001); console.log('Application running #' + cluster.worker.id); } And i sent stress test requests to those servers, i excepted that the cluster server will handle more requests but it didn't happen, both servers crashed on the same load, although 2 node services were running on the cluster and 1 service on the non-cluster. Now i wonder why ? Did i do anything wrong? Maybe something else is making the servers reach its breakpoint? both servers crashed at ~800 rps A: Now i wonder why ? did i do anything wrong? Your test server doesn't do anything other than a res.redirect(). If your request handlers use essentially no CPU, then you aren't going to be CPU bound at all and you won't benefit from involving more CPUs. Your cluster will be bottlenecked at the handling of incoming connections which is going to be roughly the same with or without clustering. Now, add some significant CPU usage to your request handler and you should get a different result. For example, change to this: // Add a basic route – index page app.get('/', function (req, res) { // spin CPU for 200ms to simulate using some CPU in the request handler let start = Date.now(); while (Date.now() - start < 200) {} res.redirect('http://www.walla.co.il'); }); Running tests is a great thing, but you have to be careful what exactly you're testing.
[ "scifi.stackexchange", "0000143050.txt" ]
Q: Were any Imperial Officers opposed to the Death Star? In Marvel's Darth Vader comic, we run into an officer who talks to Vader about the Death Star. He calls it Tarkin's folly, and wonders how many super star destroyers could have been built using the same resources. Was this a very small minority? Were there any other officers opposed to the Death Star(s)? A: Yes Various loyal Imperials were opposed to the Death Star. For example, Jylia Shale, one of the Empire’s top strategists: “The strategy of the Galactic Empire,” Shale begins, “was not under my supreme control. I’ll make it clear yet again that I disagreed with both implementations of the Death Star. I opposed its creation from the very beginning—and in fact, that opposition marginalized my input going forward." Star Wars: Aftermath As well as Grand Moff Pandion: Moff Pandion—Grand Moff Pandion, apparently—stands up, begins to pace a semicircle around his end of the table. “I for once agree with Jylia Shale. Not just that the Death Star was our greatest mistake, but also that no truce will suffice. Star Wars: Aftermath Shale’s statement suggests that Tarkin (and Palpatine) intentionally ignored the advice of those who opposed the Death Star’s creation. They were both heavily invested in its development, whether as a symbol of the power of the Empire (Tarkin) or that of the Dark Side (Palpatine). One thing to keep in mind is that opposition to the Death Star could not have been widespread around the time of its construction, simply because knowledge of its existence was not widespread. But the presence of doubts among several of the Empire’s top command suggests that opposition may have been fairly common among those who knew about it.
[ "pt.stackoverflow", "0000344477.txt" ]
Q: Usar Hibernate para gravar duas classes iguais Boa tarde, Gostaria de relacionar a classe Partida com a classe Time, onde partida receberia a PK(Id) do time de casa e do time visitante. Estou com dúvidas de como relacionar em ambas as classes, pois utilizar na classe Partida, conforme abaixo: @ManyToOne private List<Time> times; Me parece incorreto. Como eu poderia relacionar ambas as classes e gerar as tabelas no banco? A: Você poderia transformar o mapeamento de suas classes da seguinte forma: @Entity @Table(name="time") public class Time { @Id @Column(name = "time_id") private Integer id; @Column(name = "time_nome") private String nome; Já na classe Partida, você teria o relacionamento com os dois times, o da casa e o de fora. @Entity @Table(name="partida") public class Partida { @Id @Column(name = "partida_id") private Integer id; @ManyToOne @JoinColumn(name = "time_casa_fk") private Time timeCasa; @ManyToOne @JoinColumn(name = "time_fora_fk") private Time timeFora; Para complementar, para que os 2 times não sejam iguais em uma mesma partida, você pode colocar uma chave de restrição.
[ "stackoverflow", "0004270320.txt" ]
Q: Why is my EAGLVIew not rendering anymore in iOS 4.2? Upgrading to the iOS SDK 4.2 I'm experiencing several misbehaviors in my application (another one is asked here). The one I'm gonna ask your help for concerns an OpenGL view (an EAGLView subclass) that renders no more the 3d model I'm putting in. The view is allocated and it appears to recognize the gestures but its content is not visible (I've checked that it's about the view and not the misplacing of the model by coloring the background: it does not color it through glClearColor()). When I double tap it it shall resize (it goes fullscreen, before this it is a little UIVIew) calling this method: - (void)animateToGrow{ DNSLog(@"grow"); grow = YES; oldFrame = self.frame; oldCenter = self.center; [UIView beginAnimations:@"MoveAndStrech" context:nil]; [UIView setAnimationDuration:0.5]; [UIView setAnimationBeginsFromCurrentState:YES]; self.frame = CGRectMake(0, 0, WIDTH, HEIGHT); self.center = CGPointMake(CENTER_X, CENTER_Y); [UIView commitAnimations]; [self setupGLPerspectiveNear:0.1 far:1000]; } and magically the model appears, and even the background gets colored. I have a method that resizes it and make it back to its previous frame and center position and when it gets called the view becomes 'empty' again. Prior to Any suggestion? (I can post more code if needed) UPDATE This is happening on the simulator (cannot test on a device at the moment). If this is an acknowledged bug, has anyone a reference from Apple docs? UPDATE 2 I'm using OpenGL ES 1.1 and not 2.0. Here is what I do in EAGLView's layoutSubViews : - (void)layoutSubviews { [EAGLContext setCurrentContext:_context]; [self destroyFramebuffer]; [self createFramebuffer]; [self drawView]; } And this is my createFramebuffer - (BOOL)createFramebuffer { glGenFramebuffersOES(1, &_viewFramebuffer); glGenRenderbuffersOES(1, &_viewRenderbuffer); glBindFramebufferOES(GL_FRAMEBUFFER_OES, _viewFramebuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, _viewRenderbuffer); [_context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer]; glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, _viewRenderbuffer); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &_backingWidth); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &_backingHeight); if (_useDepthBuffer) { glGenRenderbuffersOES(1, &_depthRenderbuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, _depthRenderbuffer); glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, _backingWidth, _backingHeight); glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, _depthRenderbuffer); } if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) { NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES)); return NO; } return YES; } UPDATE 3 If I create the view giving it the fullscreen frame (320x480) It appears rendered correctly. In some way It is related to the view dimensions A: It took me forever to find this out. Not well documented at all, but it's in the apple docs. On os 4.2 and higher, you need the EAGLview size to be a multiple of 32 pixels in both dimensions for it to work.
[ "worldbuilding.stackexchange", "0000029554.txt" ]
Q: Can one Battlestar conquer Earth? Suppose that nowadays Titan Class Battlestar drop out from FTL(Fast-Than-Light) near Jupiter. Its FTL drive was heavily overloaded, stops working, and need serious repairs (at least 6 months + gathering necessary resources). The ship has although fully operational Sublight propulsion which is convenient for intra-solar system travel, but cannot be used for travel outside of a solar system as the time to arrive at a destination may exceed the fuel supply of the ship or the lifetime of the crew that fly the ship. Statistics: ship crew: approx 9k (including 1.2k marines, 1.5k pilots) pretty high morale water reserves: 180 days food reserves: 1 year when rationed fuel: max range of diameter of our solar system Battlestar is basically carrier so it has: 2 flight pods 4 landing decks 120 Raptors: short FTL jumps(but not so powerful to return home), atmospheric and outer-space) armament: Nuclear missiles(max 6), Conventional missile pods, Gun pods, twin tail-mounted four-barrel Gatling cannons around 400 Vipers VII no FTL capability, atmospheric and outer-space, armament 3 forward-firing kinetic energy weapons, 2 missile-launchers under each wing(nuclear missile capability) 30 marine assault shuttle (70 equipped marines + 2 pilots) 5 repairs ships Ship itself: electronic countermeasures flak 50 primary forward batteries 106 medium twin turrets 1684 heavy CIWS numerous point-of-defense cannons missile tubes(at least 60 nuclear strategic missiles 10Mt) around 300 tactical nuclear missiles for Vipers/Raptors (200kt) viper and ammo construction facilities ship can land on planet if necessary The ship cannot contact any other colonial ship and call for help. First the captain wants to communicate with Earth authorities, exchange some of technology for resources(food, materials) repair FTL drive and return home. But something goes terribly wrong and he does not even want to hear about any form of cooperation. The question is with one ship is he capable of conquer our planet. With conquer I mean to destroy any organized form of army capable of air/sea/land operation and establish temporary base(if yes, where it should be). I would like to hear what possible scenarios he has to show dominance over us. EDIT: To give Earth more chances we can be pretty sure that Battlestar needs to land on planet to finish repairs (it may be in last phase when mining is over). It cannot be done on Moon or outer-space. With winning and showing dominance I mean to use minimal power(he could start nuclear war) but if there is other way the better. EDIT 2: So far so good, Battlestar can win almost in every aspect. You own orbit you own planet. How about possible scenarios when people from Earth use spies/computer viruses/biological weapon(unknown disease spreaded by Raptor crew)/nuclear device attached to Raptor/deception and so on... A: Given they are in space already and have access to an entire solar system of resources, I wonder why they would bother to go to Earth at all? Europa has about 3X the water of all the Earth's oceans combined, so water isn't going to be an issue, and the flux tube between Io and Jupiter produces about 2 trillion watts of electricity. There are about 67 known bodies orbiting Jupiter and thousands of bodies of all sizes in the two Jovian trojan points for metals and lots of volatile materials. They don't even have to leave Jupiter space.... If they need megatons of nitrogen or hydrocarbons, they can make a short jaunt towards to Titan (where it rains natural gas), and the atmosphere is largely composed of nitrogen. In fact, if they do want to come to Earth, it is most likely to do a recruiting drive and get new people to fill the empty slots aboard, and I doubt there would be a shortage of Earth people wanting to join. Perhaps the Captain's real issue is fending off the hordes of eager applicants.... A: Yes. They can easily win, they just go to the asteroid belt and fire asteroids at us one at a time until we surrender. They can even launch a sequence of huge asteroids that are going to hit 6 months apart for the next ten years and say that without full co-operation (including their ship being repaired) they will just let them hit. This way they can't even be hit by a surprise attack on the surface since the asteroids are already in motion. Destroying them would be suicide. A: No, but there is probably no need to even try it. Winning a battle, or defeating most of the Earth's militaries is not the same as conquering the planet. To conquer a planet they need to have absolute political control over most of it. There is simply not enough of them to govern the whole planet, not even talking about the lack of experience in how the local governments work. Take a look at how easy for a modern superpower (like the USA) is to defeat a technologically weaker opponent but how hard it is to keep governing them while having to fight a guerrilla warfare. The amount of direct firepower the battlestar has is inferior to the firepower many larger countries on Earth have. Their only direct military advantage is that they are in space, and we can barely send things up to Earth orbit in short notice, and need many years to send anything outside of the planet's orbit. So they could stay safely outside of our reach, and bombard us from there, totally wrecking our infrastructure. However, I wouldn't call this a conquest, and, more importantly, this would make their primary mission a lot harder to accomplish. Yes, they could cause significant damage to us while remaining completely unharmed. But why would they even want to do it? All they need is a lot of resources. These resources have to be mined, refined, transported, and it's much easier to do it with an existing infrastructure, than without it (while trying to protect themselves from the very pissed off remnants of the inhabitants). You specified that they have to land. This means all it takes is a single underground missile base or a single nuclear submarine (which can act independently for a long time even after its home country is utterly destroyed) to destroy them. This is the main point behind mutually assured destruction, and there are several countries today on Earth which could pull off such an attack even after the governments of the Earth either surrendered or collapsed. It seems the captain is not bound by any moral constraints regarding the inhabitants of the planet, and is only focused on getting the mission accomplished. However, that doesn't mean he has to be evil just for the sake of being evil, if the mission could be accomplished without killing millions or even billions of people. While writing a story, it is always a good thing to give your characters reasonable motivations. A villain who goes out of his ways to be evil, even if it isn't practical, makes for a dull story, and nowadays it's so much discredited that you will rarely see such villains outside of parodies. If you really need a total war, you will need more justification for it besides the captain having a distaste for diplomacy. There are a lot of possibilities between "using only diplomacy" and "shoot first and ask questions later". Take a look at how the powerful global powers in the last couple of centuries managed to get what they wanted from weaker nations: they never did such things as just arriving with their ships and starting slaughtering the natives. They showed up with force, but rarely had to use that force (or they used it only in a limited way). Your captain can do the same thing: ask for a completely uninhabited area to land on, and demand the resources to be delivered there. He might promise something in return, or he might just say "What nice cities do you have. It would be a real shame if something were to happen to them." The point is, no matter how you are afraid of spies or sabotage, if the battlestar started with opening fire as soon as it arrived instead of at least trying a friendlier approach, the chances of spying or sabotage would be even higher, as there would be plenty of people wanting revenge. If a deal is brokered and the battlestar lands, they can keep smaller craft in orbit and claim that if anything were to happen to the big ship, the smaller craft will start nuking cities. Again, mutually assured destruction would prevent Earth governments from trying to attack them. However, if they started with slaughtering the inhabitants and dropping nukes on the big cities and military bases, the inhabitants would have nothing to lose and would have no reason not to use any opportunity to destroy the battlestar. Which, while landed, is just as vulnerable to nuclear missiles fired from a submarine as is any city.
[ "stackoverflow", "0006428803.txt" ]
Q: Which normal fonts support Unicode subscript characters? I have a need to use the Unicode character 0x2091, a subscript e, rather than using markup for formatting the subscript. However, the usual-suspect fonts don't appear to include a glyph for this Unicode position. Are there any Windows- or Office-included fonts that include this character? A: Check out this website.
[ "judaism.stackexchange", "0000062206.txt" ]
Q: Can אֲדֹנָי refer to a person or just to God? In Book of Ezra chapter 10 No.3 the Bible uses the Hebrew word אֲדֹנָי to talk about Ezra. I thought this word was used only when talking about God. What does this word mean? A: In the comments, you cite this link. I believe you were confused due to English not being your first language by this sentence: "used as a proper name of God only." In context, that sentence does not mean that the word אֲדֹנָי can only refer to God. It means that the word אֲדֹנָי refers to God when it is used as a proper name. Indeed, as Yishai pointed out in the comments, that word certainly can be used to refer to people (although the verse in Ezra that you cited does seem to be using אֲדֹנָי to refer to God, not Ezra as you suggest. Rashi confirms this). In Genesis 18:3, the word אֲדֹנָי refers (according to at least one position in the Talmud [Shevuot 35b]) to the angels who were approaching Avraham rather than to God.
[ "stackoverflow", "0015991990.txt" ]
Q: My app inside iMessage UIActivityViewController When I open attached image inside my iMessage and tap on "Share" button, I can see icons of 3rd party apps like "Path" or "Evernote". The question is: How can I add my own app to this list? A: Instead of a URL scheme you need to add a document type to your app. Try adding the following fragment to your Info.plist: <key>CFBundleDocumentTypes</key> <array> <dict> <key>CFBundleTypeName</key> <string>public.jpeg</string> <key>CFBundleTypeRole</key> <string>Editor</string> <key>LSHandlerRank</key> <string>Owner</string> <key>LSItemContentTypes</key> <array> <string>public.jpeg</string> </array> </dict> </array> With this fragment (specifically with the LSItemContentTypes key) you declare that your app is an editor for documents that have the Uniform Type Identifier (UTI) public.jpeg. Because this UTI is declared by the system, I believe it is not necessary that you include the UTI declaration in your app's Info.plist. You can find all system-declared UTI's in the Apple document titled System-Declared Uniform Type Identifiers. If you are new to UTI you should probably also read the Apple document Uniform Type Identifier Concepts. Last but not least, don't forget to consult the Information Property List Key Reference to find out what you should specify for the Core Foundation keys CFBundleTypeRole and LSHandlerRank. BTW: This excellent SO answer also has details about working with UTIs, especially if you ever need to declare your own app-specific UTI.
[ "stackoverflow", "0036075232.txt" ]
Q: Ellipsis on one line of flexbox child I am using flexbox and I have a child that takes up the remaining width: .flex-container { display: flex; } .middle { flex: 1; } .left { margin-right: 15px; } .right { margin-left: 15px; } .ellipsis { display: inline-block; width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } <div class="flex-container"> <div class="left"> Left content </div> <div class="middle"> <div>Middle</div> <div class="ellipsis">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div> <span>12345</span> </div> <div class="right"> <button class="btn btn-sm btn-danger">Button 1</button> <button class="btn btn-sm btn-default">Button 2</button> </div> </div> I would like the Lorem ipsum line to truncate and show ellipsis. Is this possible considering that the 'middle' element is flexing the remaining width? Here is a plunk: https://plnkr.co/edit/GvyR280i00hnAKHu0keF?p=preview A: You simply need overflow: hidden on the flex child itself. .flex-container { display: flex; } .middle { flex-grow: 1; overflow: hidden; } .left { margin-right: 15px; } .right { margin-left: 15px; } .ellipsis { display: inline-block; width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } <div class="flex-container"> <div class="left"> Left content </div> <div class="middle"> <div>Middle</div> <div class="ellipsis">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div> <span>12345</span> </div> <div class="right"> <button class="btn btn-sm btn-danger">Button 1</button> <button class="btn btn-sm btn-default">Button 2</button> </div> </div>
[ "math.stackexchange", "0000305161.txt" ]
Q: trying to verify pdf for distance between normally distributed points Math people: I am trying to find the probability density function for the distance between two points in $\mathbb{R}^3$ selected independently according to the Gaussian pdf $F(\mathbf{z}) = \left(\frac{1}{\sqrt{2\pi}}\right)^3 \exp(-\frac{1}{2}|\mathbf{z}|^2)$. I keep getting $f(t) = \frac{t^2\exp(-\frac{t^2}{4})}{2\sqrt{\pi}}$. I found a paper (http://www.pupr.edu/hkettani/papers/HICS2008.pdf) which, if I understand correctly, states that the actual pdf is $\sqrt{\frac{2}{\pi}} t^2\exp(-\frac{t^2}{2})$ (see p. 10, second "$f(x)$"). That paper actually proves a much more general result and gives this as a special case. I am reluctant to just take their word for it, since I used only Calc 3 techniques and their arguments are much more sophisticated and difficult. Has anyone seen this problem before, perhaps as a calculus or probability exercise? Assuming that either their formula or mine is right, is there an easy way to test which is right experimentally (generating random vectors, etc.)? Stefan (STack Exchange FAN) A: The square of the distance is $r^2=(X_1-X_2)^2+(Y_1-Y_2)^2+(Z_1-Z_2)^2$, where the $X_i$s, $Y_i$s, and $Z_i$s are independent standard normal r.v.s. So, $r^2/2$ is $\chi^2$ distributed with $3$ degrees of freedom, and as you say, the distance $r$ has density $r^2\exp(-\frac{r^2}{4})/(2\sqrt{\pi}).$ p. 10 of the paper you mention is treating a different case, where each component of the difference between the two points is standard normal.
[ "codereview.stackexchange", "0000018592.txt" ]
Q: Querying a list of jobs on a server using EJBs Inspired by this question, I have a Java Enterprise application running in Glassfish 2.1 and a Java SE client that communicates with the server application. For this I have a bean that maintains a collection of jobs that is set by the server and the client then asks if his job is in the current list of jobs known to the bean. I want to ask if this code is good. The client uses this interface: import javax.ejb.Remote; @Remote public interface GeneratorCancelledRemote { public boolean isJobCancelled(String jobId); } The server uses this interface: import java.util.Collection; import javax.ejb.Local; @Local public interface GeneratorCancelledLocal { public void setJobs(final Collection<String> jobs); } And here's the implementation: import java.util.Collection; import java.util.Collections; import java.util.HashSet; import javax.ejb.Stateless; @Stateless public class GeneratorCancelled implements GeneratorCancelledLocal, GeneratorCancelledRemote { private Collection<String> jobs; public void setJobs(final Collection<String> jobs) { this.jobs = Collections.synchronizedSet(new HashSet<String>()); this.jobs.addAll(jobs); } @Override public boolean isJobCancelled(final String jobId) { return jobs != null && jobs.contains(jobId); } } Obviously access to the collection of jobs has to be synchronized somehow. Is the use of Collections.synchronizedSet the best way to do this? The EJB gurus around here shun on the use of synchronized in an EE context. I found this (in German), which also explains that synchronized is not allowed in EJB. A: Your @Stateless service contains a shared state. It looks weird for me. You never modify a state of jobs, you always create a new object this.jobs = Collections.synchronizedSet(new HashSet<String>()); Could you please clarify why ? From synchronization standpoint you have a race condition in setJobs method, so it should be synchronized. Now, since your write operation (setJobs method) is protected by the intrinsic lock, all read operations should be also protected by the same lock to ensure data visibility. Make isJobCancelled synchronized too.
[ "es.stackoverflow", "0000234968.txt" ]
Q: Traté de poner unas imágenes en el canvas. ¿Por qué no aparecen? Les indexo el código var villaplatzi = document.getElementById("villaplatzi"); var ctx = villaplatzi.getContext("2d"); var fondo = { url:"tile.png", cargaOK: false, } var pollo = { url: "pollo.png", cargaOK: false, } var cerdo = { url: "cerdo.png", cargaOK: false, } var vaca = { url: "vaca.png", cargaOK: false, } var teclasVaca = { arriba: 38, abajo: 40, izquierda: 37, derecha: 39, } fondo.imagen = new Image(); fondo.imagen.src=fondo.url; fondo.imagen.addEventListener("load",cargarFondo); pollo.imagen = new Image(); pollo.imagen.src=pollo.url; pollo.imagen.addEventListener("load",cargarPollo); cerdo.imagen=new Image(); cerdo.imagen.src=cerdo.url; cerdo.imagen.addEventListener("load",cargarCerdo); vaca.imagen = new Image(); vaca.imagen.src=vaca.url; vaca.imagen.addEventListener("load",cargarVaca); function cargarFondo() { fondo.cargaOK=true; dibujarImagen; } function cargarPollo() { pollo.cargaOK=true; dibujarImagen; } function cargarCerdo() { cerdo.cargaOK=true; dibujarImagen; } function cargarVaca() { vaca.cargaOK=true; dibujarImagen; } function dibujarImagen() { if(fondo.cargaOK) {ctx.drawImage(fondo.imagen,0,0);} if(pollo.cargaOK) {ctx.drawImagen(pollo.imagen,40,40)} if(cerdo.cargaOK) {ctx.drawImage(cerdo.imagen,80,80);} if(vaca.cargaOK) {ctx.drawImage(vaca.imagen,20,20);} } <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Villa Platzi</title> </head> <body> <canvas width="500"height="500"id="villaplatzi"></canvas> <script src="platzi.js"></script> </body> </html> Agradezco la ayuda de antemano. A: Tiene dos errores básicamente. Para llamar a la función dibujarImagen deberá hacerlo con los paréntesis dibujarImagen(); en las funciones cargarFondo,cargarPollo,cargarCerdo y cargarVaca. Y tiene un error al momento de dibujar el pollo, drawImagen no es correcto, es solo drawImage sin la letra n al final.