text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Rewarded (or "reward-based") video ads are full screen video ads that users have the option of watching in full in exchange for in-app rewards. This codelab will walk you through integrating rewarded video ads into an existing iOS mobile app, including the design considerations, as well as implementation details, to follow the best practices for rewarded video ads.. Follow the steps listed below to download all the code for this codelab: Click the following link to download all the code for this codelab: This will unpack a root folder ( admob-rewarded-video-master), which contains a directory specific to either Android or iOS. For this codelab you'll navigate to the iOS directory. The iOS directory contains the start state for this codelab, located in the work directory. The end state for this codelab is located in the final directory. You'll do all of your coding in this codelab in the work directory. If at any time you're having trouble, you can refer to the project in the final directory. AdMob is part of the Firebase mobile services platform, which uses a file called GoogleService-Info.plist to store configuration information about your app. The best way to get the file is to log in to the Firebase console and register an app. For this codelab, a sample Info.plist file has been included in the project. The easiest way to include the Firebase and Mobile Ads SDKs is using CocoaPods, which is used in this codelab. In the same directory as the RewardedVideoExample.xcodeproj file, there is already a file named Podfile that includes the following: source '' platform :ios, '7.0' target 'RewardedVideoExample' do use_frameworks! pod 'Firebase' pod 'Firebase/AdMob' end In the terminal, navigate to the same directory as the Podfile described above. Then run: pod update This command ensures you get the latest iOS SDK into your app and that all the APIs are there. Once the installation finishes, close the Xcode project. In the terminal, navigate to the same directory as the Podfile described above. Then run: open RewardedVideoExample.xcworkspace The Xcode project that opens should include a Pods project with new dependencies for Firebase and AdMob. The last step in adding the FIrebase SDK to your project is downloading a GoogleService-Info.plist file from Firebase console and including it in your app. For convenience, a sample GoogleService-Info.plist file has already been included in the project. Before loading ads, your app will need to initialize the Firebase and Mobile Ads SDKs Add the call to configure:, shown below, to the application:didFinishLaunchingWithOptions:method of AppDelegate.swift to perform Firebase initialization. It's important to note you must include the import Firebase statement before calling any Firebase methods. import Firebase Import UIKit ... func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Initialize the Firebase SDK. FIRApp.configure() return true } Add the call to configure:withApplicationID: with your AdMob App ID to the application:didFinishLaunchingWithOptions:method of AppDelegate.swift to perform Google Mobile Ads initialization. You can find your app's App ID in the AdMob UI. For this codelab, we will use the test app ID value of ca-app-pub-3940256099942544~1458002511. import Firebase ... func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FIRApp.configure() // Initialize the Google Mobile Ads SDK. GADMobileAds.configure(withApplicationID: "ca-app-pub-3940256099942544~1458002511") return true } Before going any further, a GADRewardBasedVideoAd object is required. The singleton GADRewardBasedVideoAd object instance can be retrieved using the GADRewardBasedVideoAd.sharedInstance() method. Add a call to this method in the viewDidLoad: method of the ViewController.swift and save the reference to a private instance variable. It's important to note, you must include the import Firebase statement before calling any Firebase methods. import Firebase ... /// The reward-based video ad. var rewardBasedVideo: GADRewardBasedVideoAd? ... override func viewDidLoad() { super.viewDidLoad() // Get reference to shared instance GADRewardBasedVideoAd object rewardBasedVideo = GADRewardBasedVideoAd.sharedInstance() ... startNewGame() } GADRewardBasedVideoAdDelegate notifies you of rewarded video lifecycle events. You are required to set the delegate before loading an ad. GADRewardBasedVideoAd has a singleton design, so you will need to set a delegate on the shared instance, as shown below. class ViewController: UIViewController, GADRewardBasedVideoAdDelegate ... override func viewDidLoad() { super.viewDidLoad() rewardBasedVideo = GADRewardBasedVideoAd.sharedInstance() rewardBasedVideo?.delegate = self ... startNewGame() } ... The most important event in this delegate is rewardBasedVideoAd:didRewardUserWithReward:, which is called when the user should be rewarded for watching a video. You may optionally implement other methods in this delegate. In rewardBasedVideoAd:didRewardUserWithReward:, you will reward the user for watching the ad by incrementing the coin count by the reward amount. For other delegate methods, you can add simple print statements. // MARK: GADRewardBasedVideoAdDelegate implementation func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didRewardUserWith reward: GADAdReward) { print("Reward received with currency: \(reward.type), amount \(reward.amount).") earnCoins(NSInteger(reward.amount)) } func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didFailToLoadWithError error: Error) { print("Reward based video ad failed to load: \(error.localizedDescription)") }.") } The next step to monetizing your app with rewarded video ads is making the ad request. Ad requests should be made to the singleton GADRewardBasedVideoAd instance. It is best practice to call load:withAdUnitID as early as possible so we'll make this call in the startNewGame: method, which is invoked at the beginning of every game. fileprivate func startNewGame() { gameState = .playing counter = gameLength playAgainButton.isHidden = true // Load a reward based video ad. rewardBasedVideo?.load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313") ... } For your app to present the user with the option to watch an ad, you will need to modify the app's Main.Storyboard file to add an additional UIButton, to present the user with the option to watch the rewarded video ad. After selecting the Main.storyboard file, in the bottom-right corner, select a UIButton element and drag it into your view controller. Then modify the button settings and placement to those shown below. Once you've created the UIButton, you will need a reference to it in your code. Open up the Assistant Editor by navigating to View > Assistant Editor > Show Assistant Editor. Make sure the ViewController.swift file is showing in the Assistant Editor (the right pane of the screen). Next, holding the control key, click the newly created UIButton (in the center pane), and drag your cursor over to ViewController.swift (as indicated by the blue line going from the center pane to the right pane). When prompted, configure the IBOutlet as shown below. Next, you need to configure the code to be invoked when the button is pressed. To do so, repeat the process of holding the control key, clicking the newly created UIButton, and dragging your cursor over to ViewController.swift.This time you'll will set the connection as an action instead of an outlet, as shown below. Within the generated showAd: method, you will need to invoke present:fromRootViewController: method on the singleton GADRewardBasedVideoAd object to display the rewarded video ad. @IBAction func showAd(_ sender: Any) { if rewardBasedVideo?.isReady == true { rewardBasedVideo?.present(fromRootViewController: self) } } Currently, the button presenting with the user with the option to watch a rewarded video ad is always visible. However, we only want this button to be visible at the end of the game. Let's start by hiding this button at the beginning of every game, as shown below. private void startGame() { ... playAgainButton.isHidden = true watchAdButton.isHidden = true ... } Now, we'll want to make this button visible at the end of a game if an ad has loaded and is ready to be shown. This can be determined by checking the isReady property on the GADRewardBasedVideoAd object. fileprivate func endGame() { ... playAgainButton.isHidden = false if rewardBasedVideo?.isReady == true { watchAdButton.isHidden = false } ... } Your app is now ready to display rewarded video ads using the Google Mobile Ads SDK. Run the app and once the countdown timer has expired, you should be presented with the option to watch an ad for additional coins.
https://codelabs.developers.google.com/codelabs/admob-rewarded-video-ios/index.html?hl=zh-tw
CC-MAIN-2019-43
refinedweb
1,310
50.43
Various notes about some ongoing thoughts. Please add comments, clarify wording, contribute ideas, etc. These ideas are here for discussion, and have not been implemented yet. Update: The implementation ideas around these (and other) concepts have moved to a separate page WoodyRefactoring Macros and Types -- id/define/expand/inherit A macro is a definition (or blueprint) consisting of a list of widget definitions. When a macro is "expanded" it creates instances of those widget definitions in the surrounding container. No "macro" widget or container is created, because a macro is *only* a definition. So this: <fd:macro <fd:field ... </fd:field> <fd:field ... </fd:field> </fd:macro> <fd:struct <fd:macro </fd:struct> is equivalent to this: <fd:struct <fd:field ... </fd:field> <fd:field ... </fd:field> </fd:struct> ...except that now you have a reusable macro named "mymacro" that you could expand in several places in your form instead of typing the same list of widget definition over and over in each place where you need them. Sometimes you may want to define a general macro, and then create variants based on it. Think of this as creating a blueprint that contains most of your details, and then making photocopies of this blueprint to fill in different finishing touches to customize each copy. In terms of forms, this would consist of adding, deleting, and/or modifying the widget definitions in the copies of the main macro. So this: :struct <fd:macro </fd:struct> <fd:struct <fd:macro </fd:struct> would be equivalent to: <fd:struct <fd:field ... </fd:field> <fd:field ... </fd:field> </fd:struct> <fd:struct <fd:field ... </fd:field> <fd:field ... </fd:field> <fd:field ... </fd:field> </fd:struct> This is all well and nice, but if your customizations are only used in one place it would be nice to be able to specify your changes right where you use them. So this: <fd:macro <fd:field ... </fd:field> <fd:field ... </fd:field> </fd:macro> <fd:struct <fd:macro <fd:del> <fd:field </fd:del> </fd:macro> </fd:struct> would be equivalent to: <fd:struct <fd:field ... </fd:field> </fd:struct> While thinking about how nice it would be to be able to define, inherit from, expand, and modify macros as explained above, you may realize you would like to be able to do the same to individual widget definitions... Create a widget: (Note: This is unchanged from current Woody/CForms.) <wd:field <!-- validation, etc. --> </wd:field> Create a type: <wd:field <!-- validation, etc. --> </wd:field> Create a widget inheriting from a type: <wd:field <!-- validation, etc. --> </wd:field> Create a type inheriting from an existing type: <wd:field <!-- validation, etc. --> </wd:field> Create a widget *and* create a new type based on this widget definition: <wd:field <!-- validation, etc. --> </wd:field> Create a widget inheriting from an existing type and create a new type based on this widget definition: <wd:field <!-- validation, etc. --> </wd:field> Create a widget inheriting from a type without knowing what kind of widget it is(e.g. Field/Repeater/etc.): (Note the use of the generic "wd:widget" element.) <wd:widget <!-- validation, etc. (limited to aspects that do not depend on the kind of widget represented) --> </wd:widget> Repository -- wd:import/wd:widget After types are implemented (as described above), we can add type repositories to Woody/Cforms. A repository could simply be a Source identified by URI and given a prefix for later reference. This will allow us to store widget type definitions anywhere that can be referenced as a source: cocoon://some/path/and/filename context://some/other/path/and/filename cvs://... webdav://... Each repository would contain a set of type definitions. A form would bring the set of types into scope via an import statement: <wd:import Type repositories may be originally be implemented for different projects. When they are later used together there needs to be a way to resolve the naming conflicts that arise. This is the purpose of the "prefix" attribute. <wd:widget Alternative suggestion (''added 20040329 by mpo''): (tim: +1 to this alternative; nice syntax, and conveys the right ideas more clearly.) SylvainWallez: -0.5. I consider a wd:import as nothing more than an externally-defined container widget and therefore the "." notation can be used as everywhere else. Accordingly "prefix" on wd:import should actually be "id". Let's also strees the concept: what if a repository includes another repository. Can we have several colons in a widget reference? Also (unrelated to repositories, actually) we need a way to crawl up the ancestor hierarchy if a widget in a container (e.g. repeater) is of a type defined outside the container. TimLarson: I will answer this in several steps. First, the "wd:import" is meant as direct parallel to java's "import" statement. It should not create or insert any widget definitions on its own, but just bring widget definition types into scope. The "inherit" syntax defined in the section above is used to actually create widget definitions based on the types defined in the imported source. Second, imports are private to the form or repository that declares them. If a repository imports another repository and wants to make its types available, it will have to do "<wd:widget for each imported type it wants to expose, and these would then become part of its own namespace. Internally this will just add some references, not not waste memeory on unchanged copies of the definitions. We could also introduce a mass syntax for this. Third, could you explain further about this crawling need? Given the fact that this starts looking like namespaces a lot, why not also adopt the syntax of namespaces? <wd:any-scope wdns: and reference some definition in there with: (preferig the colon over the dot) <wd:widget IMHO having the prefix-to-source binding declared as attributes makes the scoping a lot more transparant. (otherwise the lookup for resolving would not only be about looking in the ancestor axis, but also into the preceding-sibling which IMHO 'blurs' the relation between containment and scope?) This would also stress nicely that prefixes only have local scope, that the sources are the real important things, and that the form-manger could cache these repositories based on the source. (tim: +1 the pre-built definition caching is one of the reasons for importing instead of just using (x||c)include) Additionally we could have the form-manager entry in the xconf kind of pre-load repositories like this by adding the sources (without prefixes since those have only local meaning) to the configuration? Questions: - Where should imports be allowed? - Top of the form definition. - Top of any container widget definition. - Anywhere a widget definition is allowed. (+1 mpo, +1 tim, +1 sylvain) - Where should imported types be registered (affects namespace)? (mpo: I don't get this question) (tim: let's ignore it, I don't think it makes sense anymore.) - Children of the form definition. - Children of the container widget definition that contains the import statement. - What should be importable? - Widget definition prototypes. (+1 mpo) - Widget definitions that will have instances created. (tim: Does this have any usecases?) - Other? - Are forward references allowed? Conditional -- choice/case The following structure supports dynamic (runtime) widget selection and lazy (a.k.a. on-demand) widget creation based on a static form definition. This is intended to replace the "union" widget. Two (mutually exclusive) versions are available: - Single string-valued expression selects a case (almost like a switch statement in the 'C' language). - Boolean-valued expression on each case (like a chain of if...else if...else if...else). (mpo: I like the latter most, reads like <xsl:choose><xsl:when..<xsl:otherwise>..) (tim: I was thinking of offering both forms, not just one-or-the-other, because I have usecases for both.) Single string-valued expression selects a case: Semantics: The expression is evaluated to produce a string matching one of the case id's. The widgets referenced or contained by this selected case are created if they do not yet exist. Questions: Instead of using an empty "id" attribute should we use <wd:default/> as the default case? (+1 tim, +1 mpo, +1 jh) - How should we indicate when we do not want to allow a default selection? - Use 'required="true"'. - Do not supply a default case. (+1 mpo) What should we do if the expression evaluates to the default anyway? (mpo: seems more logic in the when@test/otherwise filosophy?) (tim: I do not understand; could you clarify your comment?) - What namespace (read: generated request parameter names) should the widget id's be in? - widget-id -- Same as widgets outside the choice. (+1 tim, +1 mpo, +1 jh) - choice-id.widget-id -- wrapped by the choice's namespace. (-0 tim, +0 jh) - case-id.widget-id -- wrapped by th case's namespace. (-0 tim, -1 mpo, see below, -1 jh) - choice-id.case-id.widget-id -- wrapped by the choice's and the case's namespaces. (-1 tim, -1 mpo since the cases are exclusive, -1 jh) Form model syntax: <wd:choice <!-- Zero or more widget definitions --> <!-- One or more cases --> <wd:case <!-- list of inline widget definitions and/or references to the widgets defined above --> </wd:case> <!-- Optional default case specified by empty "id" attribute: --> <wd:default> <!-- list of inline widget definitions and/or references to the widgets defined above --> </wd:default> </wd:choice> Example: <wd:choice <wd:field <wd:ref </wd:case> <wd:case <wd:ref <wd:ref </wd:case> <wd:case <wd:booleanfield <wd:ref <wd:field <!-- Other non-template elements --> <ft:when <!-- Templates and other elements --> </ft:when> <!-- Other non-template elements --> <ft:when <!-- Templates and other elements --> </ft:when> <!-- Other non-template elements --> </ft:choose> (Minor thought: Should we allow other template elements where it is currently marked "Other non-template elements", to allow for easy conditional sequencing of conditional and non-conditional templates?) Expression on each case: Semantics: The case expressions are evaluated in sequence. The first case with an expression that evaluates to true is selected, expression evaluation stops, the widgets referenced or contained by the selected case are created if they do not yet exist. Questions: Pretty much the same questions as above. mpo comments: I would prefer the case/@expr and default to become when/@test and otherwise tim comments: when/@test would be fine with me; should we also copy the word 'choose' from xslt, instead of using 'choice'? 'choice' seems more declarative, but I would be ok with either word. <wd:choice <!-- Zero or more widget definitions --> <!-- One or more cases --> <wd:case <!-- list of inline widget definitions and/or references to the widgets defined above --> </wd:case> </wd:choice> <wd:choice <wd:field <wd:ref </wd:case> <wd:case <wd:ref <wd:ref </wd:case> <wd:case <wd:booleanfield <wd:ref <wd:field id="field-B".../> </wd:case> </wd:choice> Masks Evolution of an idea: union -> choice/case -> masks What if instead of choosing between disjoint sets (union), or choosing between cherry-picked widgets (choice/case), we could specify action masks for trees of widgets (masks!) A mask is similar to a "case" from the "choice/case" proposal above except that it does not choose between states, but instead it performs actions on a tree of widgets, changing various attributes as it goes. This would allow us to individually control attributes like existence, visibility, validation, enabled/disabled, processing of request parameters, and even changing sets of labels on the fly. I picture something similar to Jetty's configuration files, where calls to java methods with parameters and calls to simple setters and getters are all encoded into an XML format. We can create a simplified XML format for these action masks, and then either embed them in the form model files or supply them externally via pipelines (using XSLT, etc. for freeform transformations) for mask builders to parse into mask objects. If we provide a good API we could even build our own masks dynamically from Java or Javascript. A mask would sit in the middle between being declarative and being procedural. Instead of choosing between cases, we could apply one or more masks in sequence to apply a series of sweeping changes to trees of wigets. You could think of it as a type of shorthand for changes, possibly backed up with some internal mechanism to make mass changes ligher weight than individually performing each attribute change. WDYT? Here are some options/stages we could use on the way to masks: - Hacky, but we get full control now with no changes to CForms: - For each piece of data that needs to be controlled, make a set of widgets wrapped in a union, and use flowscript, java or widget event code to copy data between these widgets when switching between "union" cases, to make them roughly simulate one controllable widget. If we have code that reacts to valueChanged events we would of course have to filter out the events that are caused by copying values between these widgets. - Modify CForms to make more attributes dynamically controllable. Then we can make calls from flowscript, java, or widget event code to change the attributes at runtime, with no need for "unions" or for using sets of widgets to simulate more flexible widgets. - The "masks" idea presented earlier. This builds on the changes listed above (making more attributes dynamically controllable), by providing a way to specify the changes via masks encoded as XML fragments. This would involve creating the XML mask syntax, and making classes that would build and execute mask objects based on XML fragments that are written in this syntax. This would allow us to dynamically apply masks that we processed via XSLT, as well as masks that we defined statically in our form model files. Here is a sample set of "masks", using some plausible syntax. We would define our widgets normally in our form model, and then also either include these mask in our form model or supply them via a pipeline where we do our XSLT or other processing. Note that none of this is coded yet, this is just a proposal: <mask id="make-stuff-editable"> <!-- ...and if it does not exist yet, create it. --> <widget id="someWidget" exist="true" mode="edit"/> <widget id="someOtherWidget" mode="edit"/> </mask> <mask id="and-now-change-it-again"> <widget id="someWidget" exist="true" mode="read"/> <!-- Don't need "exist" because this widget is static. --> <widget id="someOtherWidget" mode="hide"/> </mask> <mask id="remove-that-widget"> <!-- If widgets exists, delete it, otherwise do nothing --> <widget id="somewidget" exist="false"/> </mask>
http://wiki.apache.org/cocoon/WoodyScratchpad
crawl-003
refinedweb
2,437
55.03
[ ] Bob Smith updated SANDBOX-291: ------------------------------ Attachment: src.zip I'll try to list most of the changes here, but I'm sure I'm forgetting some. This should include all of the big changes at least. I focused mostly on the parser, but I also made a few changes to the printer classes (although I don't think I added any new test cases there). General Changes: - Changed all class names with "CSV" in them to use "Csv". This is how it appears in the commons-lang "escapeCsv" methods and I think it's easier to read the class name when acronyms are not in all upper case. - Formatted the code. I used Eclipse with a version of the Java formatting style that uses spaces instead of tabs and with a few other small changes to try to make it more similar to the style of this code. The formatting was inconsistent before (sometimes 2 space indent, sometimes 4) which made it really hard to work on. - Removed all deprecated methods/constructors - Made all public classes final. If there is ever a need to create subclasses of them then this could be changed, but I think it would be better to at least start them as final (since once they are released as non-final it's hard to go back). - A few bug fixes (and test cases for them) ----- CsvParser: - There were a few bugs for special cases, so I made as small of changes as I could to the parser code to fix these. - Added a lot of test cases. I created a test case for all bugs that I found, so even if you don't use my changes to this class you should be able to use the test cases to find all of the same bugs. - Added a close method. - Renamed the nextValue method to getValue (so it is more consistent with the getAll and getLine method names). I think I would prefer to use a different method name prefix for all three of these (like "readAll") since I wouldn't normally expect a "get" method to have side effects, but I didn't want to just change the names of the most used methods. - Changed the getLineNumber method to return the correct line number when there are multi-line values. - Moved all of the lexer methods into an inner CsvLexer class that is completely independent of the CsvParser class. The methods were already separated out, so it wasn't a very big change. I also moved the lexer test cases into a new CsvLexerTest class. - Got rid of the interpreting unicode escape options. This doesn't really have anything to do with parsing a CSV file so I think it should be left up to the user of the class to implement this if needed. As an example, I made a CsvParserUnicodeEscapeTest class that uses the code from the lexer in a Reader subclass. One nice thing is that with this implementation, the interpretted values can be used as the delimiter, encapsulator, etc. - Got rid of the "escape" option for the same reason as the unicode escape option. I replaced it with an encapsulator escape option that is only used as an escape operator on the encapsulator character. ----- ExtendedBufferedReader - Greatly simplified this class. I removed all the methods that weren't being used (including keeping track of the line number) and changed the lookahead option to use the BufferedReader mark and reset methods. ---- CsvStrategy: - I split this class into three classes: an abstract base class (CsvStrategy), a parser-specific version (CsvParseStrategy) and a printer-specific version (CsvPrintStrategy). I didn't like that the strategy was used for both parsing and printing even though some of the values only applied to parsing (and there could be values that apply only to printing as well). - Made this class immutable (as described in SANDBOX-279) - Changed the whitespace options to not ignore whitespace by default. This is what the document at recommends for the CSV format, so I think it should be like that by default. I added an "IGNORE_WHITESPACE_STRATEGY" field that works the same as the old defaults. - Removed the interpretUnicodeEscape option and replaced the escape field with an encapsuatorEscape field (as described in the CsvParser change details). - Added an ignoreEncapsulationTrailingCharacters field. This is used to either ignore or append characters that are after an encapsulated value. Previously an IOException was being thrown here, which I don't think is ever a good idea. - Added some restrictions to prevent the values from being things that would break the parser. This includes using a line break for anything or having equal two values (other than the encapsulator and encapsulator escape). ----- CsvPrinter: - I changed this to use a modified version of the commons-lang escapeCsv method (I hope it is ok to copy a small amount of code from one commons project to another?). The escaping is a little different (and simpler) that the old version, but I think the commons-lang version seems to be the best way to do it. - I added an option to the constructor to allow disabling auto-flushing of the output stream (similar to what is in the PrintStream class). I also reduced the number of times the output is flushed when using the print method that take array input. ----- CharBuffer: - I didn't really make any changes other than to make it a non-public class. > Lots of possible changes > ------------------------ > > Key: SANDBOX-291 > URL: > Project: Commons Sandbox > Issue Type: Improvement > Components: CSV > Affects Versions: Nightly Builds > Reporter: Bob Smith > Priority: Minor > Attachments: src.zip > > > I made a lot of changes to pretty much all of the classes in the csv package. I thought it would be better to put all of the the changes here in one issue, but feel free to only take the parts you like (if any). Hopefully if nothing else the test cases will be useful to you. > I'll attach the changes and add more details in the next post. -- This message is automatically generated by JIRA. - You can reply to this email to add a comment to the issue online.
http://mail-archives.apache.org/mod_mbox/commons-issues/200902.mbox/%3C1092952606.1235528821943.JavaMail.jira@brutus%3E
CC-MAIN-2014-41
refinedweb
1,025
69.01
I have been working on this assignment for a while. I have read a couple other threads in this site regarding similar solutions but I feel mine might be a little more unique. This tic-tac-toe board is user entered, simply setup as 9 characters in 3x3 format. Input should look something like this: xxo .ox o.x The above would output, as well as the actual board itself(something similar to what I have shown below): x | x | x --------- | o | x --------- o | | x Then determine the winner. After it determines the winner, it will ask if the player would like to play another game. This is not a 2 player game. It's quite simple, but quite frustrating and I'm a bit stuck. My code is not working. Take a look at what I have. It may seem all over the place...any suggestions are much appreciated. Thank you. #include <cstdlib> #include <iostream> using namespace std; void input (char board [3][3]); void print (char board [3][3]); bool win (char board [3][3], char player); int main(int argc, char *argv[]) { char board [3][3]= {0}; //tic tac toe board int row, col; //current row and column in the array char x,o ; char space; //characters to be placed into the board char player; //player of the tic tac toe game char play; //play again bool game_over; //game over while (play != 'n'); { input (board); print (board); win (board, player); //Determines winner of the game if (win (board, 'x')) cout << "x wins!"; else if(win (board, 'o')) cout << "o wins!"; else cout << "No winner!"; //Prompts user if want to play again cout << "Would you like to play again (y or n)?: "<<endl; cin >> play; if (play == 'y') { game_over = false; //game will continue. } else if (play == 'n') { game_over = true; //game will not continue cout << "Thanks for playing!" << endl; return 1; } else { cout << "Invalid answer! Try again!" << endl; cin >> play; } } system("PAUSE"); return EXIT_SUCCESS; } //What is being read in from the user void input (char board [3][3]) { char r,c; //current row and col cout << "Enter your board as characters (x, o, .): "<< endl; for (r = 0; r < 3; r++) { for (char c = 0; c < 3; c++) { cin >> board [r][c]; } } } //what is being printed void print (char board [3][3]) { char r,c; //current row and col for (r = 0; r < 3; r++) { for (c = 0; c < 3; c++) cout << " " << board[r][c]; } //This is the start of the board setup...I got stuck here and commented it out. /* if (board[r][c] = 'x') {cout << " | " << board[r][c];} if (r < 2) {cout << " | " << board[r][c];} cout << "/n---------"; if (board[r][c] == '.') cout << " "; if (board[r][c] == 'x') cout << " | "<< if (board [r][c] == 'o') cout << " | "; if (board [r][c] < 2) cout << " "; */ //Decides who wins the game, 'x' or 'o' or no winner bool win (char board [3][3], char player) { if ((board[0][0]==player && board[0][1]==player && board[0][2]==player) return true; else if(board[1][0]==player && board[1][1]==player && board[1][2]==player) return true; else if(board[2][0]==player && board[2][1]==player && board[2][2]==player) return true; else if(board[0][0]==player && board[1][0]==player && board[2][0]==player) return true; else if(board[0][1]==player && board[1][1]==player && board[2][1]==player) return true; else if(board[0][2]==player && board[1][2]==player && board[2][2]==player) return true; else if(board[0][0]==player && board[1][1]==player && board[2][2]=='player return true; else if(board[0][2]==player && board[1][1]==player && board[2][0]==player) return true; else if(board[2][0]==player && board[1][1]==player && board[0][2]==player)); return true; else return false;
https://www.daniweb.com/programming/software-development/threads/176804/tic-tac-toe-board-using-2d-arrays-please-help
CC-MAIN-2017-34
refinedweb
627
67.99
Source criterion / www / tutorial.md % A criterion tutorial % Learn how to write Haskell microbenchmarks. Installation To install the criterion package, simply use cabal, the standard Haskell package management command. cabal update cabal install -j --disable-tests criterion Depending on how many prerequisites you already have installed, and what your Cabal configuration looks like, the build will probably take just a few minutes. Getting started Here's a a simple and complete benchmark, measuring the performance of the ever-ridiculous fib function. import Criterion.Main -- The function we're benchmarking. fib m | m < 0 = error "negative!" | otherwise = go m where go 0 = 0 go 1 = 1 go n = go (n-1) + go (n-2) -- Our benchmark harness. main = defaultMain [ bgroup "fib" [ bench "1" $ whnf fib 1 , bench "5" $ whnf fib 5 , bench "9" $ whnf fib 9 , bench "11" $ whnf fib 11 ] ] The defaultMain function takes a list of Benchmark values, each of which describes a function to benchmark. (We'll come back to bench and whnf shortly, don't worry.) To maximise our convenience, defaultMain will parse command line arguments and then run any benchmarks we ask. Let's compile our benchmark program. $ ghc -O --make Fibber [1 of 1] Compiling Main ( Fibber.hs, Fibber.o ) Linking Fibber ... If we run our newly compiled Fibber program, it will benchmark all of the functions we specified. $ ./Fibber --output fibber.html benchmarking fib/1 time 23.91 ns (23.30 ns .. 24.54 ns) 0.994 R² (0.991 R² .. 0.997 R²) mean 24.36 ns (23.77 ns .. 24.97 ns) std dev 2.033 ns (1.699 ns .. 2.470 ns) variance introduced by outliers: 88% (severely inflated) ...more output follows... Even better, the --output option directs our program to write a report to the file fibber.html. Click on the image to see a complete report. If you mouse over the data points in the charts, you'll see that they are live, giving additional information about what's being displayed. <a href="fibber.html" target="_blank"><img src="fibber-screenshot.png"></img></a> Understanding charts A report begins with a summary of all the numbers measured. Underneath is a breakdown of every benchmark, each with two charts and some explanation. The chart on the left is a kernel density estimate (also known as a KDE) of time measurements. This graphs the probability of any given time measurement occurring. A spike indicates that a measurement of a particular time occurred; its height indicates how often that measurement was repeated. <div class="bs-callout bs-callout-info"> Why not use a histogram? A more popular alternative to the KDE for this kind of display is the histogram. Why do we use a KDE instead? In order to get good information out of a histogram, you have to choose a suitable bin size. This is a fiddly manual task. In contrast, a KDE is likely to be informative immediately, with no configuration required. </div> The chart on the right contains the raw measurements from which the kernel density estimate was built. The $x$ axis indicates the number of loop iterations, while the $y$ axis shows measured execution time for the given number of iterations. The line "behind" the values is a linear regression generated from this data. Ideally, all measurements will be on (or very near) this line. Understanding the data under a chart Underneath the chart for each benchmark is a small table of information that looks like this. <table> <thead> <tr style="font-weight:700"><th></th> <th style="opacity:0.6" title="0.95 confidence level">lower bound</th> <th>estimate</th> <th style="opacity:0.6" title="0.95 confidence level">upper bound</th> </tr></thead> <tbody> <tr> <td title="Estimate of expected time for a single execution.">OLS regression</td> <td title="95% of estimates fall above this value."><span style="opacity:0.4">31.0 ms</span></td> <td title="Estimate of expected execution time.">37.4 ms</td> <td title="95% of estimates fall below this value."><span style="opacity:0.4">42.9 ms</span></td> </tr> <tr> <td title="Numeric description of the how well the OLS estimate above fits the actual data.">R² goodness-of-fit</td> <td title="95% of estimates fall above this value. Note that this lower bound is suspiciously low, as it is less than 0.9."><span style="opacity:0.4">0.887</span></td> <td title="This value is between 0 and 1. A value below 0.99 indicates a somewhat poor fit. Values below 0.9 are outright suspicious.">0.942</td> <td title="95% of estimates fall below this value."><span style="opacity:0.4">0.994</span></td> </tr> <tr> <td>Mean execution time</td> <td title="95% of estimates fall above this value."><span style="opacity:0.4">34.8 ms</span></td> <td title="The estimated mean execution time.">37.0 ms</td> <td title="95% of estimates fall below this value."><span style="opacity:0.4">43.1 ms</span></td> </tr> <tr> <td>Standard deviation</td> <td title="95% of estimates fall above this value."><span style="opacity:0.4">2.11 ms</span></td> <td title="The estimated standard deviation of execution time.">6.49 ms</td> <td title="95% of estimates fall below this value."><span style="opacity:0.4">11.0 ms</span></td> </tr> </tbody> </table> The first two rows are the results of a linear regression run on the measurements displayed in the right-hand chart. "OLS regression" estimates the time needed for a single execution of the activity being benchmarked, using an ordinary least-squares regression model. This number should be similar to the "mean execution time" row a couple of rows beneath. The OLS estimate is usually more accurate than the mean,. A value below 0.9 is outright worrisome. "Mean execution time" and "Standard deviation" are statistics calculated (more or less) from execution time divided by number of iterations. On either side of the main column of values are greyed-out lower and upper bounds. These measure the accuracy of the main estimate using a statistical technique called bootstrapping. This tells us that when randomly resampling the data, 95% of estimates fell within between the lower and upper bounds. When the main estimate is of good quality, the lower and upper bounds will be close to its value. Reading command line output Before you look at HTML reports, you'll probably start by inspecting the report that criterion prints in your terminal window. benchmarking ByteString/HashMap/random time 4.046 ms (4.020 ms .. 4.072 ms) 1.000 R² (1.000 R² .. 1.000 R²) mean 4.017 ms (4.010 ms .. 4.027 ms) std dev 27.12 μs (20.45 μs .. 38.17 μs) The first column is a name; the second is an estimate. The third and fourth, in parentheses, are the 95% lower and upper bounds on the estimate. timecorresponds to the "OLS regression" field in the HTML table above. R²is the goodness-of-fit metric for time. meanand std devhave the same meanings as "Mean execution time" and "Standard deviation" in the HTML table. How to write a benchmark suite A criterion benchmark suite consists of a series of Benchmark values. main = defaultMain [ bgroup "fib" [ bench "1" $ whnf fib 1 , bench "5" $ whnf fib 5 , bench "9" $ whnf fib 9 , bench "11" $ whnf fib 11 ] ] We group related benchmarks together using the bgroup function. Its first argument is a name for the group of benchmarks. bgroup :: String -> [Benchmark] -> Benchmark All the magic happens with the bench function. The first argument to bench is a name that describes the activity we're benchmarking. bench :: String -> Benchmarkable -> Benchmark bench = Benchmark The Benchmarkable type is a container for code that can be benchmarked. By default, criterion allows two kinds of code to be benchmarked. Any IOaction can be benchmarked directly. With a little trickery, we can benchmark pure functions. Benchmarking an IO action This function shows how we can benchmark an IO action. import Criterion.Main main = defaultMain [ bench "readFile" $ nfIO (readFile "GoodReadFile.hs") ] (examples/GoodReadFile.hs) We use nfIO to specify that after we run the IO action, its result must be evaluated to <span id="normal-form">normal form</span>, i.e. so that all of its internal constructors are fully evaluated, and it contains no thunks. nfIO :: NFData a => IO a -> IO () Rules of thumb for when to use nfIO: Any time that lazy I/O is involved, use nfIOto avoid resource leaks. If you're not sure how much evaluation will have been performed on the result of an action, use nfIOto be certain that it's fully evaluated. IO and seq In addition to nfIO, criterion provides a whnfIO function that evaluates the result of an action only deep enough for the outermost constructor to be known (using seq). This is known as <span id="weak-head-normal-form">weak head normal form (WHNF)</span>. whnfIO :: IO a -> IO () This function is useful if your IO action returns a simple value like an Int, or something more complex like a Map where evaluating the outermost constructor will do "enough work". Be careful with lazy I/O! Experienced Haskell programmers don't use lazy I/O very often, and here's an example of why: if you try to run the benchmark below, it will probably crash. import Criterion.Main main = defaultMain [ bench "whnfIO readFile" $ whnfIO (readFile "BadReadFile.hs") ] (examples/BadReadFile.hs) The reason for the crash is that readFile reads the contents of a file lazily: it can't close the file handle until whoever opened the file reads the whole thing. Since whnfIO only evaluates the very first constructor after the file is opened, the benchmarking loop causes a large number of open files to accumulate, until the inevitable occurs: $ ./BadReadFile benchmarking whnfIO readFile openFile: resource exhausted (Too many open files) Beware "pretend" I/O! GHC is an aggressive compiler. If you have an IO action that doesn't really interact with the outside world, and it has just the right structure, GHC may notice that a substantial amount of its computation can be memoised via "let-floating". There exists a somewhat contrived example of this problem, where the first two benchmarks run between 40 and 40,000 times faster than they "should". As always, if you see numbers that look wildly out of whack, you shouldn't rejoice that you have magically achieved fast performance---be skeptical and investigate! <div class="bs-callout bs-callout-info"> Defeating let-floating Fortunately for this particular misbehaving benchmark suite, GHC has an option named -fno-full-laziness that will turn off let-floating and restore the first two benchmarks to performing in line with the second two. You should not react by simply throwing -fno-full-laziness into every GHC-and-criterion command line, as let-floating helps with performance more often than it hurts with benchmarking. </div> Benchmarking pure functions Lazy evaluation makes it tricky to benchmark pure code. If we tried to saturate a function with all of its arguments and evaluate it repeatedly, laziness would ensure that we'd only do "real work" the first time through our benchmarking loop. The expression would be overwritten with that result, and no further work would happen on subsequent loops through our benchmarking harness. We can defeat laziness by benchmarking an unsaturated function---one that has been given all but one of its arguments. This is why the nf function accepts two arguments: the first is the almost-saturated function we want to benchmark, and the second is the final argument to give it. nf :: NFData b => (a -> b) -> a -> Benchmarkable As the NFData constraint suggests, nf applies the argument to the function, then evaluates the result to <a href="#normal-form">normal form</a>. The whnf function evaluates the result of a function only to <a href="#weak-head-normal-form">weak head normal form</a> (WHNF). whnf :: (a -> b) -> a -> Benchmarkable If we go back to our first example, we can now fully understand what's going on. main = defaultMain [ bgroup "fib" [ bench "1" $ whnf fib 1 , bench "5" $ whnf fib 5 , bench "9" $ whnf fib 9 , bench "11" $ whnf fib 11 ] ] We can get away with using whnf here because we know that an Integer has only one constructor, so there's no deeper buried structure that we'd have to reach using nf. As with benchmarking IO actions, there's no clear-cut case for when to use whfn versus nf, especially when a result may be lazily generated. Guidelines for thinking about when to use nf or whnf: If a result is a lazy structure (or a mix of strict and lazy, such as a balanced tree with lazy leaves), how much of it would a real-world caller use? You should be trying to evaluate as much of the result as a realistic consumer would. Blindly using nfcould cause way too much unnecessary computation. If a result is something simple like an Int, you're probably safe using whnf---but then again, there should be no additional cost to using nfin these cases. Using the criterion command line By default, a criterion benchmark suite simply runs all of its benchmarks. However, criterion accepts a number of arguments to control its behaviour. Run your program with --help for a complete list. Specifying benchmarks to run The most common thing you'll want to do is specify which benchmarks you want to run. You can do this by simply enumerating each benchmark. ./Fibber 'fib/fib 1' By default, any names you specify are treated as prefixes to match, so you can specify an entire group of benchmarks via a name like "fib/". Use the --match option to control this behaviour. Listing benchmarks If you've forgotten the names of your benchmarks, run your program with --list and it will print them all. How long to spend measuring data By default, each benchmark runs for 5 seconds. You can control this using the --time-limit option, which specifies the minimum number of seconds (decimal fractions are acceptable) that a benchmark will spend gathering data. The actual amount of time spent may be longer, if more data is needed. Writing out data Criterion provides several ways to save data. The friendliest is as HTML, using --output. Files written using --output are actually generated from Mustache-style templates. The only other template provided by default is json, so if you run with --template json --output mydata.json, you'll get a big JSON dump of your data. You can also write out a basic CSV file using --csv, and a JUnit-compatible XML file using --junit. (The contents of these files are likely to change in the not-too-distant future.) Linear regression If you want to perform linear regressions on metrics other than elapsed time, use the --regress option. This can be tricky to use if you are not familiar with linear regression, but here's a thumbnail sketch. The purpose of linear regression is to predict how much one variable (the responder) will change in response to a change in one or more others (the predictors). On each step through through a benchmark loop, criterion changes the number of iterations. This is the most obvious choice for a predictor variable. This variable is named iters. If we want to regress CPU time ( cpuTime) against iterations, we can use cpuTime:iters as the argument to --regress. This generates some additional output on the command line: time 31.31 ms (30.44 ms .. 32.22 ms) 0.997 R² (0.994 R² .. 0.999 R²) mean 30.56 ms (30.01 ms .. 30.99 ms) std dev 1.029 ms (754.3 μs .. 1.503 ms) cpuTime: 0.997 R² (0.994 R² .. 0.999 R²) iters 3.129e-2 (3.039e-2 .. 3.221e-2) y -4.698e-3 (-1.194e-2 .. 1.329e-3) After the block of normal data, we see a series of new rows. On the first line of the new block is an R² goodness-of-fit measure, so we can see how well our choice of regression fits the data. On the second line, we get the slope of the cpuTime/ iters curve, or (stated another way) how much cpuTime each iteration costs. The last entry is the $y$-axis intercept. Measuring garbage collector statistics By default, GHC does not collect statistics about the operation of its garbage collector. If you want to measure and regress against GC statistics, you must explicitly enable statistics collection at runtime using +RTS -T. Useful regressions <table> <thead><tr style="font-weight:500"> <th align="left">regression</th> <th align="left"> --regress</th> <th align="left">notes</th> </tr></thead> <tbody><tr> <td>CPU cycles</td> <td> cycles:iters</td> <td></td> </tr> <tr> <td>Bytes allocated</td> <td> allocated:iters</td> <td> +RTS -T</td> </tr> <tr> <td>Number of garbage collections</td> <td> numGcs:iters</td> <td> +RTS -T</td> </tr> <tr> <td>CPU frequency</td> <td> cycles:time</td> <td></td> </tr></tbody> </table> Tips, tricks, and pitfalls While criterion tries hard to automate as much of the benchmarking process as possible, there are some things you will want to pay attention to. Measurements are only as good as the environment in which they're gathered. Try to make sure your computer is quiet when measuring data. Be judicious in when you choose nfand whnf. Always think about what the result of a function is, and how much of it you want to evaluate. Simply rerunning a benchmark can lead to variations of a few percent in numbers. This variation can have many causes, including address space layout randomization, recompilation between runs, cache effects, CPU thermal throttling, and the phase of the moon. Don't treat your first measurement as golden! Keep an eye out for completely bogus numbers, as in the case of -fno-full-lazinessabove. When you need trustworthy results from a benchmark suite, run each measurement as a separate invocation of your program. When you run a number of benchmarks during a single program invocation, you will sometimes see them interfere with each other. How to sniff out bogus results If some external factors are making your measurements noisy, criterion tries to make it easy to tell. At the level of raw data, noisy measurements will show up as "outliers", but you shouldn't need to inspect the raw data directly. The easiest yellow flag to spot is the R² goodness-of-fit measure dropping below 0.9. If this happens, scrutinise your data carefully. Another easy pattern to look for is severe outliers in the raw measurement chart when you're using --output. These should be easy to spot: they'll be points sitting far from the linear regression line (usually above it). If the lower and upper bounds on an estimate aren't "tight" (close to the estimate), this suggests that noise might be having some kind of negative effect. A warning about "variance introduced by outliers" may be printed. This indicates the degree to which the standard deviation is inflated by outlying measurements, as in the following snippet (notice that the lower and upper bounds aren't all that tight, too). std dev 652.0 ps (507.7 ps .. 942.1 ps) variance introduced by outliers: 91% (severely inflated)
https://bitbucket.org/bos/criterion/src/4eefba8adb2a/www/tutorial.md
CC-MAIN-2015-40
refinedweb
3,249
56.86
On a previous post in this series I talked about a possible approach to take when starting to learn Prism as a whole (the Tip numbering is resumed from the previous post). In this post I will get more specific and talk about one of the most used (if not the most used) pattern when developing Prism applications (either for WPF & Silverlight): MVVM. Most people are familiar with this pattern (if you are not great places to read about it are here for WPF and over here for Silverlight), so I will not go deep into what is the main idea of it. Instead I will try to go over some core concepts that usually lead to different levels of confusion. What’s the difference between MVVM and PresentationModel? The above question is one asked a lot, as people tend to get confused when they hear all the talk about MVVM and then open some Prism Quickstarts or RI and find most of them “implement the PresentationModel pattern”. Well, there is not a certain answer (and if there was I probably wouldn’t be the one who came up with it), but as far as Prism development is concerned they are synonyms. There is no difference between them, except for the coined term. As Martin Fowler explains in his PresentationModel article: .”, so if you think about it, the way to “project the state of the PresentationModel (or ViewModel) onto the glass is WPF/Silverlight DataBinding in our case (or as Julian likes to explain it: “the ViewModel is a bindable Presenter”). Always remember the main objective, testability and decoupling. How do I do pure MVVM? This is another point of confusion as people tend to relate MVVM with DataTemplates and no View code behind, so they get the idea that the only way to implement the pattern is that one. In my opinion there is no pure MVVM, it is a design pattern, so it can have many different implementations which will depend mainly on who implements it and what his requirements are. In this particular topic I would like to “branch you” to Glenn’s post “The spirit of MVVM (ViewModel), it’s not a code counting exercise.” as I agree with his point of view in this topic, so there is no point in duplicating the information. Now that you have finished reading Glenn’s post, I hope you understand what I am trying to explain (not necessarily agree). I for once like the “View First” (you “talk” to the view) implementation to relate the View to its ViewModel in Prism could be the following (using DI): public class MyView { public MyView(IMyViewModel viewModel) { this.DataContext = viewModel; InitializeComponent(); } } In the code above, Unity’s DI provides the decoupling between the View and the ViewModel, so the ViewModel “does not have to know anything about the view” and allows you to test the VM in isolation (of course this is just one of the ways to do it). How should I manage my View/ViewModel? This question addresses both creation/destruction of View and ViewModels as well as its interaction with other components in the application. Often it is not “clear” which component should handle a specific action. Say that when a button is clicked an event should be published. Where should this be done? Well, without information about the application and its patterns it is hard to say. It could be done in the ViewModel or it could be done in a module level controller that manages interaction with other modules, but this depends on how your application is structured. Instead of expanding on this topic, I would like to branch you (yet again), to these posts from Ward Bell which talk about these common questions and provide some really interesting and thought answers: Should I always use commands to communicate with the ViewModel? Before using a command, I usually stop and think: “Can this be done in another way?, Can I achieve this same functionality with binding?”. Well, sometimes the answer is yes, and that is when I think commands are not necessary. The most common example is binding a command to execute every time and item in a Listbox is selected. This same behavior can be achieved by binding the SelectedItem property of the Listbox to your ViewModel (most of the times), and executing the required action on the setter. Having thought of the above, what if I do need a command? Well, my first recommendation would be understanding how do Commands with attached Behaviors work, a topic explained by Julian in this great post. After that you can use the code snippet I created some time ago to help you with the tedious task of creating the classes required for this to work. Things to add to your reading list To help you comply with Tip 4, you can find below a couple of articles about MVVM and MVVM with Prism that I think might be of use to better understand this topic (the ones mentioned above would be in this list, but there is not need in duplicating them): - Erwin’s MVVM series (with some more posts to go) - David’s Visual Studio templates Hopefully, this post has helped you understand a little more about MVVM and how to use it with Prism. As always, your feedback is appreciated, so if you believe any link should be added or anything of the sort, just drop a comment. 3 Comments I’m really interested in your thoughts on how to do dialogs properly using MVVM and Prism. Most of the time the answer is “Use a mediator” or “Use EventAggregator” — how exactly? If I have a command that needs to open a new window, how should that work? I’d like to see a working example vs. a theoretical implementation. Hi, Great information on using MVVM with Prism. I was wondering if you could post a sample where the views are hosted in a Tab Region (unlike the the examples with prism where the view itself is a TabControl. I am looking for an IE style tab control, which has a close button on top. Thanks Arun Subscribed to your RSS, your blog is pretty interesting. Thanks
http://southworks.com/blog/2009/11/16/learning-prism-composite-application-guidance-for-wpf-silverlight-mvvm-fundamentals/
CC-MAIN-2015-40
refinedweb
1,042
65.76
Get size of web page Project description Site Size Returns the size of the webpage which url is passed Usage import sitesize # get the size of webpage in bytes sitesize.get_webpage_size('') # check if the url is valid or not sitesize.url_checker('') Installation Using pip pip install sitesize Without pip For Installing the dependency and saving the package python setup.py install If you just want to test the package without installing - Clone the repository git clone - Navigate to sitesize folder containing main.py - Run main.py as python main.py Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/sitesize/
CC-MAIN-2021-21
refinedweb
119
65.73
BASENAME(3) Linux Programmer's Manual BASENAME(3) basename, dirname - parse pathname components #include <libgen.h> char *dirname(char *path); char *basename(char *path); / / / . . . .. . .. Both dirname() and basename() return pointers to null-terminated strings. (Do not pass these pointers to free(3).)basename(), dirname() │ Thread safety │ MT-Safe │ └──────────────────────┴───────────────┴─────────┘ POSIX.1-2001, POSIX.1-2008. There.. The); basename(1), dirname(1) This page is part of release 5.07 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. GNU 2020-06-09 BASENAME(3) Pages that refer to this page: dmstats(8)
https://www.man7.org/linux/man-pages/man3/basename.3.html
CC-MAIN-2020-34
refinedweb
108
70.19
Objects are indispensable but exactly how a language implements them and makes them available to the programmer matters. Sometimes the class-based approach complete with inheritance makes things complicated. So much so that it is easy to misunderstand and make mistakes. This C# puzzle isn't particularly unique to the language but it doesn't go out of its way to make this aspect of inheritance easy to understand. There is a sense in which the background to this puzzle is the whole philosophy of class-based, object-oriented programming. A quick sketch of the idea is that you don't create objects directly. Instead you create a class which is a template for an object and use inheritance. That is you can create derived classes which inherit all the methods and properties of the base class and the set of derived classes form the type hierarchy. It is also assumed that anywhere you can use a base class you can use a derived class because the derived class is "bigger" than the base class, in the sense it has at least the set of methods and properties of the base class. That is, if you create class A and then create class B which inherits from class A, then anywhere you use class A you can use a class B because it "contains" a class A. All this is very reasonable and translates to the C# programmer's knowledge that a variable of a type can reference an object of a derived type. This means that is there is nothing wrong with: ClassA myVariable=new ClassB(); as long as ClassB inherits from ClassA. However, things get tricky when you introduce the need to modify what the derived class inherits. You could forbid modification or overriding and say that any methods and properties ClassB inherits are fixed and cannot be changed. This would result in a simple and safe world but one that would be difficult to work with. In practice we do allow methods and properties to be redefined in derived classes and this is where our puzzle and many others originate. As always with a puzzle, the actual details of the code that caused the real problem have been reduced down to the very minimum necessary. This should allow you to see the problem more quickly and without any diversions to waste your time. One way to work with an array of mixed types is to use the base type. An array of base type elements will also store any derived types. For example, if we define two classes, a Base type and a Derived type which inherits from Base: public class Base{ public string MyMethod() { return "Base Method"; }}public class Derived : Base{} then you can create an array that will store either type: Base[] myArray = new Base[2];myArray[0] = new Base();myArray[1] = new Derived();foreach (Base element in myArray){ MessageBox.Show(element.MyMethod());} In this case, as the Derived class doesn't define its own MyMethod, the one inherited from the base class is used and in both cases you see the message "Base Method". Of course practical considerations lead to MyMethod being modified and the new definition of MyMethod in Derived is: public class Derived : Base{ public string MyMethod() { return "Derived Method"; }} Now when the program is run what the programmer expects to see is that the Base class method is called for Base class elements and the Derived class method is called for Derived class elements. This is, of course, exactly what doesn't happen. Despite the redefinition of the method, the Base class method is used both times. This isn't what is supposed to happen. Object-oriented philosophy demands "polymorphism", which is where the method appropriate for the object is used. That is, the array element myArray[1] may be of type Base, but it holds an object of type Derived and so it should use the Derived method not the Base method. This is what polymorphism is all about, but it isn't working. It also doesn't work if you try casting the derived class to the base class. What is the problem? Why isn't the object's own method used? Turn to the next page when you are ready to find out. <ASIN:1449380344> <ASIN:1430225378><ASIN:0470447613> <ASIN:1933988924>
http://www.i-programmer.info/programmer-puzzles/140-c/3832-overriding-problems.html
CC-MAIN-2017-30
refinedweb
723
67.69
When I started working at my current job I was surprised to see that everyone used IRC as their primary means of communication - much more so than email or IM. I recently wrote a small irc bot library in python - it was a ton of fun and reminded me of some of the first programs I wrote that were bots and scripts for America Online: Remember AOHell? I wrote probably 10 different kinds of ripoffs (mass-mailers, room busters, punters?) but my favorite AOL scripts were always chat bots. There was string parsing involved (something every programmer loves), real time interaction, and of course it was fun to try and predict how people would pwn your bot and then write clever checks to make sure this didn't happen. Coincidentally, I was going through my backup drive and ran across a bunch of old source code I'd squirreled away -- stuff I'd written almost 15 years ago! So, here's a guided tour of AOL bot writing! In Visual Basic 3.0 parlance, the .bas file was a module full of constants, globals, subroutines and functions. In order to do any srs work it was necessary to talk to AOL through the Windows API, sending fake messages directly to AOL's user-interface. This bad-boy: Declare Function SendMessage& Lib "User" (ByVal hWnd%, ByVal wMsg%, ByVal wParam%, ByVal lParam As Any) Windows API was divided up into a few big .dll files, User, GDI, Kernel and probably some more, and to call out to the API you needed to throw a declaration like the one above in your code. This was useful for, say, killing the hourglass, which one would do by invoking the modal "About Window" then killing it (don't ask me why this worked, it just did): Sub TB_KillWait () 'Gets rid of the hourglass Dim hWnd%, about%, x hWnd% = FindWindow("AOL Frame25", 0&) Call RunMenuByString(hWnd%, "&About America Online") Do: DoEvents Loop Until FindWindow("_AOL_Modal", 0&) <> 0 about% = FindWindow("_AOL_Modal", 0&) x = SendMessageByNum(about%, WM_DESTROY, 0&, 0&) x = SendMessageByNum(about%, WM_CLOSE, 0&, 0&) End Sub The .bas file I had was comprised of functions like TBC_Send, which would send a string into the currently active chat room: Sub TBC_Send (Text) 'Sends text to the chatroom AOL% = FindWindow("AOL FRAME25", 0&) List% = TB_FindChildByClass(AOL%, "_AOL_Listbox") If List% = 0 Then Exit Sub End If Room% = GetParent(List%) TXT% = TB_FindChildByClass(Room%, "_AOL_EDIT") SendBtn% = TB_FindChildByTitle(Room%, "Send") x = SendMessageByString(TXT%, WM_SETTEXT, 0, Text) x = SendMessageByNum(TXT%, WM_CHAR, 13, 0) timeout .05 End Sub As you can see, it identifies the chatroom naively as "the room with the listbox" (!), then it finds the edit box, sets the text in it and appends an "Enter" key. In addition to SendMessage, the FindWindow and GetWindow API calls were also very useful, as they would find controls, textboxes, windows, etc that could then be manipulated with calls to SendMessage. I ran into some problems with VB being pokey, so I ended up writing a small .dll file to find child windows by their titles or class-names (I've taken the liberty of cleaning up the variable names as they were originally all one-letter and making the indentation uniform): #include <string.h> #include <windows.h> extern "C" HANDLE _export _far _pascal TB_FindChildByTitle (HANDLE hWnd, char title[]) { HANDLE chld, tmp_chld; char tmp[200]; int len; chld = GetWindow(hWnd, GW_CHILD); while (chld) { len = GetWindowText(chld, tmp, 199); tmp[len] = '\0'; if (!strcmpi(tmp, title)) return chld; tmp_chld = TB_FindChildByTitle(chld, title); if (tmp_chld) return tmp_chld; chld = GetWindow(chld, GW_HWNDNEXT); } return NULL; } There was this really handy file called VBMsg.vbx that basically allowed your program to listen in on events that were sent to other windows. This was useful when the chat textbox was updated - just listen for WM_SETTEXT and parse the incoming bits. The following is taken from an "AFK Bot", basically an answering machine for when you're idling in chat or just wanted to seem cool:$ = Mid(ChatText$, Colon% + 2) If UCase(Left(TextSaid$, 4)) = "/MSG" Then Mesg$ = Mid(TextSaid$, 5) List1.AddItem SN$ & ": " & Mesg$ TBC_Send (CBracket(SN$ & ", message saved!")) End If End Sub I still totally remember that incantation: $SN = Mid(ChatText, 3 Colon% - 3) -- I think the first two must've been CR/LF, then there was a tab before the colon. Another fun one was the 8-Ball Bot which would just respond with a randomly chosen phrase:$ = UCase(Mid(ChatText$, Colon% + 2)) If InStr(TextSaid$, "/8BALL") Then x = Int(Rnd * 7) + 1 Select Case x Case 1 TBC_Send ("<-·´¯`·.·°( " & SN$ & ", Outlook good") Case 2 TBC_Send ("<-·´¯`·.·°( " & SN$ & ", Reply hazy, try again") Case 3 TBC_Send ("<-·´¯`·.·°( " & SN$ & ", Sources point to 'Yes'") Case 4 TBC_Send ("<-·´¯`·.·°( " & SN$ & ", Don't count on it") Case 5 TBC_Send ("<-·´¯`·.·°( " & SN$ & ", Definetely 'no'") Case 6 TBC_Send ("<-·´¯`·.·°( " & SN$ & ", Yes") Case 7 TBC_Send ("<-·´¯`·.·°( " & SN$ & ", No") End Select End If End Sub The last snippet I'll paste is from a "warez server" -- to me this was like the holy grail! The way that it worked was you'd go into a chat room and some d00d would say, "Hey, who wants free software?" Everyone would say "I do" so he'd start up his warez server. People would type in something like "/Send List" and the bot would email you a list of everything the guy had in his mailbox. If you saw something you liked, you could say "/Send 123" or whatever number it was on the list and the bot would forward you a copy which you could then download. Pretty ingenious! This source code comes from the last AOL script I wrote, some time around 1997 or so -- it processes several lists (aptly named List1, List2, and List3). It's worth noting that it does no caching, no prioritizing, and there's even the use of a few "GoTo" statements with descriptive labels like "HD" and "H". One of the neat tricks I see is it repeatedly clicks "Send" and checks for either the compose window going away or an error window appearing. If an error window appears it scans it for problematic screen names and tries again. Also, all those GetWindow calls with integer arguments -- 2 = gw_next (the window's sibling). Sub Timer1_Timer () AOL% = FindWindow("AOL Frame25", 0&) NewMail% = TB_FindChildByTitle(AOL%, "New Mail") Tree% = TB_FindChildByClass(NewMail%, "_AOL_TREE") ReadBtn% = TB_FindChildByTitle(NewMail%, "Read") KeepAs% = TB_FindChildByTitle(NewMail%, "Keep As New") MailCount% = SendMessageByNum(Tree%, LB_GETCOUNT, 0, 0) If List1.ListCount Then Label4.Caption = Str(Val(Label4.Caption) + 1) MailLst$ = "<p align = center><font size=2<B>" & TBC_Bracket2("micro server by timeBomb") & Chr(13) & TBC_Bracket2("warez server list [" & MailCount% & "] items") & Chr(13) & "</p><p align=left></b><br>" For i = 0 To MailCount% - 1 MailStr$ = String$(255, " ") Q% = SendMessageByString(Tree%, LB_GETTEXT, i, MailStr$) NoDate$ = Mid$(MailStr$, InStr(MailStr$, "/") + 4) NoSN$ = Mid$(NoDate$, InStr(NoDate$, Chr(9)) + 1) MailLst$ = MailLst$ & Chr(13) & "[" & i & "] ~" & TBT_TrimNull(NoSN$) DoEvents Next i For i = 0 To List1.ListCount - 1 m$ = m$ & List1.List(i) & ", "&, m$) F = SendMessageByString(Subj%, WM_SETTEXT, 0&, TBC_Bracket("micro server ~ list")) D% = GetWindow(Subj%, 2) D% = GetWindow(D%, 2) Body% = GetWindow(D%, 2) F = SendMessageByString(Body%, WM_SETTEXT, 0&, MailLst$) F = SendMessageByString(Rich%, WM_SETTEXT, 0&, MailLst$) Button% = TB_FindChildByClass(MailWin%, "_AOL_Icon") GoTo Hd Hd: ViewStr$ = UCase(TBW_GetWinText(FindChildByClass(ErrorWin%, "_AOL_View"))) For i = 0 To List1.ListCount - 1 If InStr(ViewStr$, UCase(List1.List(i))) Then List1.RemoveItem i End If Next i m$ = "" For i = 0 To List1.ListCount - 1 m$ = m$ & List1.List(i) & ", " Next i F = SendMessageByString(MailTo%, WM_SETTEXT, 0&, m$) GoTo Hd End If List1.Clear DoEvents List1.Clear TBC_Send ("") TBC_Send (TBC_Bracket("pending lists sent out!")) End If If List2.ListCount Then Label4.Caption = Str(Val(Label4.Caption) + 1) m$ = List2.List(0) List2.RemoveItem 0 Req = Left(m$, InStr(m$, ":") - 1) SN$ = Mid(m$, InStr(m$, ":") + 1) If Not IsNumeric(Req) Then Exit Sub If Req > MailCount% Then Exit Sub x = SendMessageByNum(Tree%, LB_SETCURSEL, Req, 0&) Do: DoEvents TBW_Click ReadBtn% Timeout (.2) Stat1% = TBM_MMForwardWin(False) Loop Until Stat1% <> 0 Forward% = Stat1% FwdBtn% = TBM_MMForwardWin(True) Do: DoEvents TBW_Click FwdBtn% Timeout (.5) SendWin% = TBM_MMFindFwd() Loop Until SendWin% <> 0 ToEd% = TB_FindChildByClass(SendWin%, "_AOL_EDIT") SubjEd% = TBW_GetChild(SendWin%, "_AOL_EDIT", 3) If TBA_AOLVer() = 25 Then MainEd% = TBW_GetChild(SendWin%, "_AOL_EDIT", 4) Else MainEd% = TB_FindChildByClass(SendWin%, "RICHCNTL") End If SendBttn% = TB_FindChildByClass(SendWin%, "_AOL_ICON") DoEvents x = SendMessageByString(ToEd%, WM_SETTEXT, 0&, SN$) DoEvents x = SendMessageByString(MainEd%, WM_SETTEXT, 0&, "<p align=center><font color=""#000080""><B>" & TBC_Bracket2("micro server by timeBomb") & "<BR>" & TBC_Bracket2("warez server item index [" & Req & "]")) DoEvents SubjText$ = TBW_GetWinText(SubjEd%) SubjText$ = Mid$(SubjText$, 5) x = SendMessageByString(SubjEd%, WM_SETTEXT, 0&, SubjText$) Do: DoEvents TBW_Click SendBttn% Timeout (1) SendWin% = TBM_MMFindFwd() ErrorWin% = TB_FindChildByTitle(AOL%, "Error") Loop Until SendWin% = 0 Or ErrorWin% <> 0 If ErrorWin% <> 0 Then TBW_KillWin ErrorWin% TBW_KillWin Forward% TBW_KillWin SendWin% TBC_Send ("") TBC_Send (TBC_Bracket(SN$ & ", unable to send mail")) GoTo H End If TBW_KillWin Forward% GoTo H H: DoEvents TBW_Click KeepAs% Timeout (.01) TBW_Click KeepAs% TBC_Send ("") TBC_Send (TBC_Bracket(SN$ & ", item #" & Req & " was sent!")) End If If List3.ListCount Then Label4.Caption = Str(Val(Label4.Caption) + 1) Colon% = InStr(List3.List(0), ":") reqz$ = Left(List3.List(0), Colon% - 1) SN$ = Mid(List3.List(0), Colon% + 1) reqz$ = UCase(reqz$) List3.RemoveItem 0 For i = 0 To MailCount% - 1 MailStr$ = String$(255, " ") Q% = SendMessageByString(Tree%, LB_GETTEXT, i, MailStr$) NoDate$ = Mid$(MailStr$, InStr(MailStr$, "/") + 4) NoSN$ = Mid$(NoDate$, InStr(NoDate$, Chr(9)) + 1) NoSN$ = TBT_TrimNull(NoSN$) If InStr(UCase(NoSN$), UCase(reqz$)) Then iCnt% = iCnt% + 1 sRes$ = sRes$ & "Item [" & i & "] ~ " & NoSN$ & Chr(13) End If DoEvents&, SN$) F = SendMessageByString(Subj%, WM_SETTEXT, 0&, "micro tools server found: [" & iCnt% & "]") D% = GetWindow(Subj%, 2) D% = GetWindow(D%, 2) Body% = GetWindow(D%, 2) F = SendMessageByString(Body%, WM_SETTEXT, 0&, "<p align = center><font size=2<B>" & TBC_Bracket2("micro server by timeBomb") & Chr(13) & TBC_Bracket2("warez server find results [" & iCnt% & "] items") & Chr(13) & ("<p align=left>") & sRes$ & " ") F = SendMessageByString(Rich%, WM_SETTEXT, 0&, "<p align = center><font size=2<B>" & TBC_Bracket2("micro server by timeBomb") & Chr(13) & TBC_Bracket2("warez server find results [" & iCnt% & "] items") & Chr(13) & ("<p align=left>") & sRes$ & " ") Button% = TB_FindChildByClass(MailWin%, "_AOL_Icon") TBW_KillWin ErrorWin% TBW_KillWin MailWin% TBC_Send ("") TBC_Send (TBC_Bracket(SN$ & ", unable to send mail")) Exit Sub End If DoEvents TBC_Send ("") TBC_Send (TBC_Bracket(SN$ & ", find results sent!")) End If End Sub I hope you found this entertaining! I wish I had some screen-shots - I'll see about getting a Windows 95 VM going tomorrow and take some. Edit screen shots added! If you remember writing proggies, using them, any anecdotes, feel free to post them in the comments! What epic things did you do to get your account TOSed? AppActivate "America Online" ' remember how it had two spaces?!?! SendKeys "%{F4}" Wow! This brings back memories indeed. I started programming thanks to AOL "Proggiez" Oh man this surely brings back memories. IM punters and the rest were always a blast, especially when aol changed versions on you and did not support the older stuff. I remember there were some big program names out there "FateX", "Hellraiser" etc. Wow, all the bad stupid stuff I did. Faking aol sign-on windows to steal accounts for random purposes. Thanks for the still through my early teens. -jason Probably dating myself, but AOHell with the automatic, random account generator (with CC#!) was amazing. Wow, great memories. That's how I, and countless others, got their start coding. Great times as a kid. A lot of people did like AOL. A lot of people like iThings today. Awesome! I got my start programming AOL "progz." I hung out in private room: "test" with the "DoW Jones" crew (I was GooDy). I remember when some of the crew discovered the various uses of chr(0). I wrote a mass mailer that let the user re-arrange the mail before sending it out, what an innovation I thought at the time :P. Things got really crazy when we learned to hex edit the aol class name to allow opening multiple instances of the client. Things got super extra crazy when we cracked the protocol (with the help of leaked docs) that let us log in many many accounts without a client at all. Man, those were the days! This brings back so much memories! This is how I got started in programming. Did anyone use to hang out in the room vb32? Wow this is great! Writing proggiez was my first programming experience too. I was all of 13 years old in 1997 and I dove into the world of AOL "hacking" head first. I remember all of this too well. I wish I had some of my old source code...but it's gone with the wind. I'm sure there are a few dozen 3.5 disks sitting in landfills with my old proggiez on them. I got my account TOSed several times, so I entered the world of AOL "phishing". It was amazingly easy to get people to give you their password, and so I lived on dozens of different <>< (phish) accounts for a year or so. Now I'm 26 and a professional software engineer. Not as exciting anymore. Man - zeraw, private(#), red, blue, vb, vb32, and was it server(#) or something else for all the server rooms? When beginning programming, "they say" to pick a project and just get at it. AOL was an awesome and fun project, and definitely helped to get me hooked. One of my favorite periods of life. .. private channel vb4. That's what it was all about. I remember when chat com / mp3 players became popular. I was a 7th grader who wrote one and used it as a final test for my Advanced Programming in Visual Basic college class. Then it was AIM spammers, and spam in general. So much money to be made by finding vulnerable email gateways. I miss those days like no other. Thanks for the trip down memory lane. It's great to see that so many people remember this stuff and enjoyed it as much as I did! Thanks for reading! Wow. I wish that I still had some of my old AOL source. Doing that was what made me decide to be a software engineer "when I grew up." My favorite program was a baited to find internal aol accts called "Live Bait.". Me and one of my buddies would then try to crack them later. ah... memories. AOL Progz are what got me into the game, then jumping to AIM, then Yahoo now I'm a web developer... go figure... oh man, the memories..the memories. Thanks for this blast from the past! Commenting has been closed, but please feel free to contact me
http://charlesleifer.com/blog/a-stroll-down-memory-lane-scripting-aol/
CC-MAIN-2013-48
refinedweb
2,423
71.85
Simple data archiving tool Project description arx - a simple data archiving tool 'arx' is a simple data archiving tool. A local directory, or "repo", is initialized (with the 'init' command) to be a staging ground and mirror of a remote archive. Files and directories can be copied into the repo and then committed to the remote archive (with the 'commit' command). Files and directories in the remote archive can be checked out from the archive for viewing and processing (with the 'checkout' command). Arx assumes a repository exists as tree of files on a remote server accessible via ssh and rsync. No other remote configuration is needed. NOTE: Arx maintains only a write-once archive. Once a file has been committed to the repository it can't be changed or updated. installation requirements arx only depends on one python package that's not included in the standard library ( pyyaml). It otherwise depends on a couple of non-python packages that are usually available by default in most systems: - ssh client - rsync - find It is unlikely on most systems that these apps wouldn't be available. usage command line interface Assuming an existing pre-configured remote of the form HOST:PATH, initialize a local repo mirror: $ arx init HOST:PATH my_repo $ cd my_repo $ arx config root: /path/to/my_repo remote: HOST:PATH Add a file to the repo: $ cp /path/to/other_file file2 List files in the archive and in the local repo: $ arx list - file1 + file2 The '-'/'+' prefixes indicate files that only exist remotely/locally, respectively. No prefix indicates the file exists in both places. $ arx checkout file1 $ arx list file1 + file2 Commit a file to the repo: $ arx commit file2 $ arx list file1 file2 python library Arx also includes a python library from which all of the same functionality can be accessed. The basic interface is through the Repo class. A new repo can be created with the Repo.init method: import arx repo = arx.Repo.init(HOST:PATH, '/path/to/my_repo') You can then use the commit, and list methods: repo = arx.Repo('/path/to/my_repo') for f in repo.list(remote=True): print(f) repo.checkout('file1') repo.commit('file2') for f in repo.list(): print(f) Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/arx/
CC-MAIN-2022-33
refinedweb
399
54.73
#include <dePropFieldType.h> Prop Field Type. Defines a prop type in a prop field. Each prop type has a static model, a skin and a list of instances. Each instance uses the parameters of the type but has a specific placement. Instances are projected onto the hosting surface. For performance and memory reasons the number of instances is an immutable parameter given during construction time. In games you need to init this number anyways only during loading time and during run time the number is constant. Editors can recreate the type to alter the count of instances. The parent prop field allows to mutate the list of types so this restriction is not a road blocking one. Creates a new prop field type. The instance count has to be at least 1. Cleans up the prop field type. Retrieves the bend state at the given index. Referenced by GetBendStateCount(). Retrieves the number of bend states. References GetBendStateAt(), and SetBendStateCount(). Retrieves the list of bend states. Be careful with this method call as it is one intended only for performance usage. Make sure you to not read or write more than GetBendStateCount elements. This array is not guaranteed to be the same for the entire lifetime of this object but is a continuous list. If possible use the GetBendStateAt method call to obtain the individual bend states as there boundary checks are conducted. If you need direct access due to performance reasons only keep to this pointer for the short time you do some work. Retrieves the collision filter. Retrieves the instance at the given index. Referenced by GetInstanceCount(). Retrieves the number of instances. References GetInstanceAt(), and SetInstanceCount(). Retrieves the list of instances. Be careful with this method call as it is one intended only for performance usage. Make sure you to not read or write more than GetInstanceCount elements. You can be sure that the returned array is the same for the entire lifetime of this object and contains the instances in a continuous list. If possible use the GetInstanceAt method call to obtain the individual instances as there boundary checks are conducted. Retrieves the model or NULL if not set. References SetModel(). Retrieves the restitution. References SetRestitution(). Retrieves the rotation per force. References SetRotationPerForce(). Sets the number of bend states. Referenced by GetBendStateCount(). Sets the number of instances. Referenced by GetInstanceCount(). Sets the model or NULL it not set. Referenced by GetModel(). Sets the restitution. Referenced by GetRestitution(). Sets the rotation per force. Referenced by GetRotationPerForce().
http://dragengine.rptd.ch/docs/dragengine/latest/classdePropFieldType.html
CC-MAIN-2017-51
refinedweb
417
70.6
Using a js file in another (object orientated) Hi there, is this possible? I would like to create a file called util.js. Now i put some functions in there, which i will need often. And I now would like to usw this functions in all my other javascript files. I thought this has something to do with Ext.ns('...') but seems not to be right. So is this possible and if yes, how? Thanks Chriz mhm seems that I got it. I now use namespace and do something like that: Ext.namespace("bla"); bla = function(){ //do some stuff } if I initialize this utilities js file in the html file BEFORE I use my main js file, i can use it there. Just one question remains: is there a possibilities to init the utilities file from another javascript file, or do i have to init this like <scrip language="text/javaScript" src=""></script> in the html file? Chriz namespace just creates variables/objects. It has nothing to do with loading javascript. If you want to include the file, just add the script tag.Tim Ryan Read BEFORE posting a question / BEFORE posting a Bug Use Google to Search - API / Forum API Doc (4.x | 3.x | 2.x | 1.x) / FAQ / 1.x->2.x Migration Guide / 2.x->3.x Migration Guide just add the script tag? So that means I have to add the <script language="text/javascript"...> tag into the html file. I cant load the js file like I do in Java (Utilities u = new Utilities()) Right? Is the namespace thing a good possibility to use Methods in other javascript files? Chriz Once again - the 2 are unrelated. Read the API doc for namespace It has nothing to do with loading javascript. If you're asking about dynamically loading javascript files, there are ways to do this. I suggest you spend some time reading the, so you have a better understanding and can formulate some questions that make clear what you're trying to accomplish.Tim Ryan Read BEFORE posting a question / BEFORE posting a Bug Use Google to Search - API / Forum API Doc (4.x | 3.x | 2.x | 1.x) / FAQ / 1.x->2.x Migration Guide / 2.x->3.x Migration Guide
https://www.sencha.com/forum/showthread.php?60645-Using-a-js-file-in-another-(object-orientated)
CC-MAIN-2015-48
refinedweb
379
85.18
On 2017-09-06 09:03, Serge E. Hallyn wrote:> Quoting Richard Guy Briggs (rgb@redhat.com):> ...> > > I believe we are going to need a container ID to container definition> > > (namespace, etc.) mapping mechanism regardless of if the container ID> > > is provided by userspace or a kernel generated serial number. This> > > mapping should be recorded in the audit log when the container ID is> > > created/defined.> > > > Agreed.> > > > > > As was suggested in one of the previous threads, if there are any events not> > > > associated with a task (incoming network packets) we log the namespace ID and> > > > then only concern ourselves with its container serial number or container name> > > > once it becomes associated with a task at which point that tracking will be> > > > more important anyways.> > > > > > Agreed. After all, a single namespace can be shared between multiple> > > containers. For those security officers who need to track individual> > > events like this they will have the container ID mapping information> > > in the logs as well so they should be able to trace the unassociated> > > event to a set of containers.> > > > > > > I'm not convinced that a userspace or kernel generated UUID is that useful> > > > since they are large, not human readable and may not be globally unique given> > > > the "pets vs cattle" direction we are going with potentially identical> > > > conditions in hosts or containers spawning containers, but I see no need to> > > > restrict them.> > > > > > From a kernel perspective I think an int should suffice; after all,> > > you can't have more containers then you have processes. If the> > > container engine requires something more complex, it can use the int> > > as input to its own mapping function.> > > > PIDs roll over. That already causes some ambiguity in reporting. If a> > system is constantly spawning and reaping containers, especially> > single-process containers, I don't want to have to worry about that ID> > rolling to keep track of it even though there should be audit records of> > the spawn and death of each container. There isn't significant cost> > added here compared with some of the other overhead we're dealing with.> > Strawman proposal:> > 1. Each clone/unshare/setns involving a namespace type generates an audit> message along the lines of:> > PID 9512 (pid in init_pid_ns) in auditnsid 00000001 cloned CLONE_NEWNS|CLONE_NEWNET> new auditnsid: 00000002> associated namespaces: (list of all namespace filesystem inode numbers)As you will have seen, this is pretty much what my most recent proposal suggests.> 2. Userspace (i.e. the container logging deamon here) can watch the audit log> for all messages relating to auditnsid 00000002. Presumably there will be> messages along the lines of "PID 9513 in auditnsid 00000002 cloned...". The> container logging daemon can track those messages and add the new auditnsids> to the list it watches.Yes.> 3. If a container is migrated (checkpointed and restored here or elsewhere),> userspace can just follow the appropriate logs for the new containers.Yes.> Userspace does not ever *request* a auditnsid. They are ephemeral, just a> tool to track the namespaces through the audit log. They are however guaranteed> to never be re-used until reboot.Well, this is where things get controvertial... I had wanted this, akernel-generated serial number unique to a running kernel to track everycontainer initiation, but this does have some CRIU challenges pointedout by Eric Biederman. Nested containers will not have a consistentview on a new host and no way to make it consistent. If we couldguarantee that containers would never be nested, this could be workable.I think nesting is inevitable in the future given the variety andcreativity of the orchestration tools, so restricting this seemsshort-sighted.At the moment the approch is to let the orchestrator determine the ID ofa container. Some have argued for as small as u32 and others for a fullUUID. A u32 runs the risk of rolling, so a u64 seems like a reasonablestep to solve that issue. Others would like to be able to store a fullUUID which seemed like a good idea on the outset, but on furtherthinking, this is something the orchestrator can manage while minimisingthe number of bits of required information per audit record to guaranteewe can identify the provenance of a particular audit event. Let's seeif we can make it work with a u64.> (Feels like someone must have proposed this before)Thsee ideas have been thrown around a few times and I'm starting tounderstand them better.> -serge- RGB--Richard Guy Briggs <rgb@redhat.com>Sr. S/W Engineer, Kernel Security, Base Operating SystemsRemote, Ottawa, Red Hat CanadaIRC: rgb, SunRaycerVoice: +1.647.777.2635, Internal: (81) 32635
http://lkml.org/lkml/2017/9/14/22
CC-MAIN-2018-09
refinedweb
762
60.55
[Date Index] [Thread Index] [Author Index] Re: Writing functions in packages that define values of global variables On Nov 9, 12:53 am, "Blackwell, Keith" <Keith.Blackw... at rbccm.com> wrote: > Is there a way to have functions inside packages define global > variables? > > Specifically, is there a way to have a function that imports a data set > and then cuts it up and defines the pieces as variables that I can > access with other functions I've written in a notebook. > > For instance, if I always want it to take the dates from the data and > define them as variable called Dates or whatever. You can directly define through Global`dates = {...} You can context switch with Begin/End (I would not recommend this.) You can expose YourPackage`dates on the context path (I'm unsure how you define your package, typically, people put their package code deeper in the package namespace, ie. YourPackage`Private`blah, and then only expose what they need.) BeginPackage["a`"]; b::usage="I'm exposed!"; (* I exist at a`b *) Begin["`Private`"]; b = "Hello"; c::usage="I'm hidden!"; (* I exist at a`Private`c *) c = "World"; End[]; EndPackage[]; Needs["a`"]; MemberQ[$ContextPath, "a`"] === True ??b should return usage/value ??c should return nothing (since MemberQ[$ContextPath, "a`Private`"] === False)
http://forums.wolfram.com/mathgroup/archive/2010/Nov/msg00231.html
CC-MAIN-2015-40
refinedweb
214
65.22
Record Object (ADO) Represents a row from a Recordset or the data provider, or an object returned by a semi-structured data provider, such as a file or directory. Remarks A Record object represents one row of data, and has some conceptual similarities with a one-row Recordset. Depending on the capabilities of your provider, Record objects may be returned directly from your provider instead of a one-row Recordset, for example when an SQL query that selects only one row is executed. Or, a Record object can be obtained directly from a Recordset object. Or, a Record can be returned directly from a provider to semi-structured data, such as the Microsoft Exchange OLE DB provider. You can view the fields associated with the Record object by way of the Fields collection on the Record object. ADO allows object-valued columns including Recordset, SafeArray, and scalar values in the Fields collection of Record objects. If the Record object represents a row in a Recordset, it is possible to return to that original Recordset with the Source property. The Record object can also be used by semi-structured data providers such as the Microsoft OLE DB Provider for Internet Publishing, to model tree-structured namespaces. Each node in the tree is a Record object with associated columns. The columns can represent the attributes of that node and other relevant information. The Record object can represent both a leaf node and a non-leaf node in the tree structure. Non-leaf nodes have other nodes as their contents, but leaf nodes do not have such contents. Leaf nodes typically contain binary streams of data and non-leaf nodes may also have a default binary stream associated with them. Properties on the Record object identify the type of node. The Record object also represents an alternative way for navigating hierarchically organized data. A Record object may be created to represent the root of a specific sub-tree in a large tree structure and new Record objects may be opened to represent child nodes. A resource (for example, a file or directory) can be uniquely identified by an absolute URL. A Connection object is implicitly created and set to the Record object when the Record is opened by using an absolute URL. A Connection object may explicitly be set to the Record object via the ActiveConnection property. The files and directories that can be accessed by using the Connection object define the context in which Record operations may occur. Data modification and navigation methods on the Record object also accept a relative URL, which locates a resource using an absolute URL or the Connection object context as a starting point. Note URLs using the http scheme will automatically invoke the Microsoft OLE DB Provider for Internet Publishing. For more information, see Absolute and Relative URLs. A Connection object is associated with each Record object. Therefore, Record object operations can be part of a transaction by invoking Connection object transaction methods. The Record object does not support ADO events, and therefore will not respond to notifications. With the methods and properties of a Record object, you can do the following: Set or return the associated Connection object with the ActiveConnection property. Indicate access permissions with the Mode property. Return the URL of the directory, if any, that contains the resource represented by the Record with the ParentURL property. Indicate the absolute URL, relative URL, or Recordset from which the Record is derived with the Source property. Indicate the current status of the Record with the State property. Indicate the type of Record - simple, collection, or structured document - with the RecordTypeproperty. Stop execution of an asynchronous operation with the Cancel method. Disassociate the Record from a data source with the Close method. Copy the file or directory represented by a Record to another location with the CopyRecord method. Delete the file, or directory and subdirectories, represented by a Record with the DeleteRecord method. Open a Recordset that contains rows that represent the subdirectories and files of the entity represented by the Record with the GetChildren method. Move (rename) the file, or directory and subdirectories, represented by a Record to another location with the MoveRecord method. Associate the Record with an existing data source, or create a new file or directory with the Open method. The Record object is safe for scripting. This section contains the following topic. See Also Fields Collection (ADO) Properties Collection (ADO) Records and Streams Recordset Object (ADO)
https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/record-object-ado?redirectedfrom=MSDN&view=sql-server-ver15
CC-MAIN-2020-24
refinedweb
746
54.12
In this blog I am going to explain how to integrate speech recognition in your Scala project. Speech recognition enables us to integrate the recognition and translation of spoken language into our projects in form of text. Speech recognition is really upcoming feature in electronic and computer devices so as to make them smarter. In the project we shall be using the CMU Sphinx Toolkit. It allows us to integrate offline speech recognition. It is an open source toolkit which provides us with several speech recognizer components. There are several components available depending upon the needs of the application. The available components include speech recognizer , speech decoders, software for acoustic model training,language model and pronunciation dictionary. We shall be using the Sphinx 4 speech recognizer, it is a pure java speech recognition library. It is used for identification of speech devices,adapt models and to recognize and translate speech . Now let us look at the code.First of all let us include the following two dependencies in our build.sbt libraryDependencies += "edu.cmu.sphinx" % "sphinx4-core" % "1.0-SNAPSHOT" libraryDependencies += "edu.cmu.sphinx" % "sphinx4-data" % "1.0-SNAPSHOT" or libraryDependencies += "de.sciss" % "sphinx4-core" % "1.0.0" libraryDependencies += "de.sciss" % "sphinx4-data" % "1.0.0" The next step is to import the following into the application import edu.cmu.sphinx.api._ Next comes the code for setting up the configuration for speech recognition object SpeechRecognitionApp extends App { val configuration = new Configuration configuration.setAcousticModelPath("file:models/acoustic/wsj") configuration.setDictionaryPath("file:models/acoustic/wsj/dict/cmudict.0.6d") configuration.setLanguageModelPath("models/language/en-us.lm.dmp") } The code above will create a configuration variable which is responsible for setting up the acoustic model, language model and path to the dictionary. The cmudict is a text file used as dictionary of recognizable words which can be extended for a given language. It looks something like this ONE HH W AH N ONE(2) W AH N TWO T UW THREE TH R IY Now the last step is to create the recognition object, enable it to start recognition and store the result.And we have stored that result in form of a string. println("Start speaking :") val speechRecognizer = new LiveSpeechRecognizer(configuration) speechRecognizer.startRecognition(true) var result = speechRecognizer.getResult while ({result = speechRecognizer.getResult; result != null}) { println(result.getHypothesis) } Now we are done, so we can use the above code to enable speech recognition into our Scala Project. References - - - 6 thoughts on “Speech Recognition with Scala2 min read” To resolve the deps, had to change them to: libraryDependencies += “edu.cmu.sphinx” % “sphinx4-core” % “5prealpha-SNAPSHOT” libraryDependencies += “edu.cmu.sphinx” % “sphinx4-data” % “5prealpha-SNAPSHOT” Nice concept to write a blog on… Hi, I am getting an error that Not enough agrument for constructor SpeechAlighner. Can you please help? Hi, can you send me the code block where you are getting the error, may be then I can help you better. Hi Pallavi, This is very helpful. Thanks. Have you tried doing this demo in databricks community edition () with Apache Spark? It will help those interested in combining sphinx with Spark for scaling up the transcription task to terbytes of audio files in s3 of hdfs. I like this idea. I would love to see this run on Spark.
https://blog.knoldus.com/speech-recognition-with-scala/
CC-MAIN-2021-04
refinedweb
545
50.84
. Imagine that you have a beautiful rose garden. It takes many hours of work to keep it beautiful and the roses healthy. Did you know, a key aspect of growing roses is pruning. That is, you need to cut out the dead and dying flowers so that the young, healthy buds can thrive. Pruning roses also gives them a more attractive shape. But pruning can also be applied elsewhere. For example, in the timber industry, where entire mountainsides of forest need to be kept healthy, different types of pruning are used. The first of these is selective cutting, where specific types of trees are identified and only those are cut. Then there is thinning, where large trees are cut out of thick heavy forests, so the small trees that are struggling can grow and be healthy. Finally, there is clear-cutting, which is used to completely clear a side of a mountain of all trees. Certain types of trees will not survive if selective cutting or thinning is used, so clear-cutting is the only alternative. Also, if a forest is attacked by disease or insects, clear-cutting may be used to remove a section of forest in an effort to save the entire forest. In all cases, the timber company replants trees so that new growth will keep the forest healthy. In all cases, the forest is still a forest. Pruning has not changed the functionality of what nature gave. This article is published from the DotNetCurry .NET Magazine – A Free High Quality Digital Magazine for .NET professionals published once every two months. Subscribe to this eMagazine for Free and get access to hundreds of free .NET tutorials from experts Just like the roses or the forest, pruning is necessary to keep software healthy. As software gardeners, our term for pruning is refactoring. The first important thing you need to know about refactoring is that it isn’t rewriting. Refactoring is defined as “the process of restructuring existing computer code – changing the factoring – without changing its external behavior”. Source Let’s think back to a past column I wrote about unit testing. The process of unit testing is shown in Figure 1. You can see that refactoring is a key part of unit testing. And, not surprisingly, unit testing is a key part of refactoring. After all, how do you know if you haven’t changed the external behavior of the piece of code, without testing? Figure 1: The unit testing process includes refactoring The most famous book on refactoring was written by Martin Fowler. Its title is “Refactoring: Improving the Design of Existing Code”. The book is a catalog of refactorings and includes a chapter called “Bad Smells in Code” that discusses ways to identify and fix problematic code that could be a good candidate for refactoring. The smells include duplicated code, long methods, large classes, and long parameter list. (I once had to update code written by someone else and found a class with a constructor that had 144! parameters). There are nearly 20 more code smells listed. In addition to describing code smells and cataloging refactoring patterns, the book gives reasons to refactor: improve the design of software, make software easier to understand, help you find bugs, and help you to program faster. This last one seems contradictory. How can you program faster if you have to refactor the code? The answer is that refactoring makes it easier to read the existing code. Martin Fowler also lists what he calls, “The Rule of Three”, which are three rules for when to refactor. First, you should refactor when you add function. Second, refactor when you need to fix a bug. And third, refactor as you do a code review. Once you’ve identified the specific code smell, the book points you to refactorings that can be used to fix it. You can fix the code with copy and paste. But there is a better way. Visual Studio has some built-in refactoring tools that are easier to use than copy and paste. Hover over a variable in the Visual Studio editor (for this column, I used the free Visual Studio 2013 Community Edition, which is functionally equivalent to VS 2013 Professional), then right-click and select Refactor. You’ll see that six refactorings are available. You will also notice that each refactoring has a keyboard shortcut that begins with Ctrl+R. Figure 2: The Visual Studio refactoring menu In the rest of this column, I will take you through each of these refactorings. The late computer scientist Phil Karlton said, “There are only two hard things in Computer Science: cache invalidation and naming things.” (A variation says “There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.”). How often have you named a class, variable, or other object and after sometime realized that the name you chose turns out to be wrong? How often have you needed to name something and wasted time trying to come up with just the right name for it before even typing it into your editor? Often times the correct name comes to you only after you’ve seen how it will be used in the code. This is where Rename Refactoring comes into play. Martin Fowler describes Rename Method, “An important part of the code style I am advocating is small methods to factor complex processes. Done badly, this can lead you on a merry dance to find out what all the little methods do. The key to avoiding this merry dance is naming the methods…Remember you code for a human first and a computer second” (Refactoring, p. 273) In Visual Studio, the Rename Refactoring works on more than just a method. It can be used on variables, classes, even namespaces. Place the cursor on the object to be renamed and press Ctrl+R,Ctrl+R (think of this as Refactor, Rename). The Rename dialog appears. Figure 3. Caption: The rename dialog is used for the rename refactoring. Enter the new name and select the options you want, then select OK. If you checked Preview reference changes, you will get an additional dialog showing you where each refactoring takes place and what the changes will look like. You can then unselect the places you don’t want the refactoring to occur. Figure 4: The Preview Changes dialog Click Apply in the Preview Changes dialog and the refactorings will be made. One of the rules for good methods is that a method should do only one thing. Also, a good method will be short and not require you to scroll though lots of code. This next refactoring, Extract Method helps you fix these issues by removing code and putting it in its own method. You can also use this refactoring to simplify code. From Martin Fowler: “Extract Method is one of the most common refactorings I do. I look at a method that is too long or look at code that needs a comment to understand its purpose. I then turn that fragment of code into its own method.” (Refactoring, p. 110) To use this refactoring, highlight the code to extract, then press Ctrl+R,Ctrl+M (Refactor, Method). Here’s some real code from one of my projects. if (viewModel.NewEmailParentTable.ToLower() == "company" && viewModel.NewEmailIsDefault) { var companyEmailAddresses = _context.CompanyEmailAddresses.Include("EmailAddress"); if (companyEmailAddresses.Any()) { var currentDefault = companyEmailAddresses.FirstOrDefault(e => e.EmailAddress.IsDefault).EmailAddress; if (currentDefault.Id != viewModel.NewEmailAddressId) { currentDefault.IsDefault = false; _context.EmailAddresses.Attach(currentDefault); _context.Entry(currentDefault).State = EntityState.Modified; _context.SaveChanges(); } } } After I wrote the code and it passed unit tests, I went back to refactor. The original method was about three screens long. This piece of code has a smell in that it has several nested if statements. I highlighted the entire code section and pressed Ctrl+R,Ctrl+M. The Extract Method dialog was displayed. Figure 5: The Extract Method dialog Notice how the refactoring tools figured out what parameters the method needed and set those up automatically. I entered the name for the new method and clicked OK. Visual Studio did all the work of creating the method in my class and replacing the selected code with a single line of code. I then refactored the nested if statements. Later on, I decided my original name wasn’t quite right and used the Rename refactoring to change the name of the method. In the end, the code is easier to read and maintain. The next refactoring, Encapsulate Field, turns a field into a property. Look at this code: public class Line { public int length, width; } public class MyLine { public static void Main() { Line line = new Line(); line.length = 12; line.width = 1; // Some code to draw the line on the screen } } Length and width are technically fields, not properties because they don’t have getters or setters. Let’s change that, but first, here’s what Martin Fowler has to say, “One of the principal tenets of object oriented programming is encapsulation, or data hiding. This says that you should never make your data public. When you make data public, other objects can change and access data values without the owning object’s knowing about it. This separates data from behavior…Encapsulate field begins the process by hiding the data and adding accessors. But this is only a first step. Once I’ve done Encapsulate Field, I look for methods that use the new methods to see whether they fancy packing their bags and moving to the new object with a quick Move Method.” (Refactoring, p. 206) Now let’s look at how to do this refactoring in Visual Studio. Put the cursor on length in the Line class then press Ctrl+R,Ctrl+E (Refactor, Extract). The Encapsulate Field dialog is displayed. Figure 6: Use the Encapsulate Field dialog to change a field to a property Visual Studio recommended ‘Length’ as the property name. You can change it to something else if you want. When you click OK, a Preview dialog is displayed. Click Apply there. Here’s the refactored code. public class Line { public int length, width; public int Length { get { return length; } set { length = value; } } } public class MyLine { public static void Main() { Line line = new Line(); line.Length = 12; line.width = 1; // Some code to draw the line on the screen } } This is nice and tidy and follows a common standard that property name begin with a capital letter. Interfaces are a terrific way to get reuse and inheritance in your code. They also make code easier to unit test because it’s quite easy to mock an interface. The Extract Interface refactoring is very useful for that legacy code that you need to test and it looks at the class and creates an interface for it. Here’s Martin Fowler’s take: …Interfaces are good to use whenever a class has distinct roles in different situations. Use Extract Interface for each role.” (Refactoring, pp 341-342) Let’s see this refactoring in action. Here’s the original method. Note that I’ve left out the actual implementation code. public class CustomerRepository { public Customer Find(int id) {} public IQueryable< Customer > GetAll() { } public void InsertOrUpdate(Customer customer) { } public void Save() { } public void Delete(int id) { } public Customer GetByPartialName(string name) { } } Place the cursor on the class name and press Ctrl+R,Ctrl+E (Refactor, Extract) to display the Extract Interface dialog. Visual Studio suggests a name for the Interface and allows you to select which methods to include. I selected all except GetByPartialName. When you click OK, Visual Studio created a new file (ICustomerRepository) and placed it in the same folder as the original class. Figure 7: Extract Interface interface ICustomerRepostory { void Delete(int id); Customer Find(int id); IQueryable< Customer > GetAll(); void InsertOrUpdate(Customer customer); void Save(); } The original class is then changed to inherit from the new interface. public class CustomerRepostory : ICustomerRepostory { public Customer Find(int id) {} public IQueryable< Customer > GetAll() { } public void InsertOrUpdate(Customer customer) { } public void Save() { } public void Delete(int id) { } public Customer GetByPartialName(string name) { } } Now it’s easier to mock the code or substitute a different repository implementation for this one. Getting all the parameters you need for a particular method is hard. As you develop the functionality, you realize that some parameters aren’t needed at all. Others may turn into properties or fields. It’s easy to do this if the method is called one or two times, but what if you call it many times from many places in the project? Then it becomes more difficult. This next refactoring helps you remove parameters. Sticking with the pattern of this discussion, here’s Martin Fowler’s explanation: “A parameter indicates information that is needed; different values make a difference. You caller has to worry about what values to pass. By not removing the parameter you are making further work for everyone who uses the method.” (Refactoring, p. 277) To use this refactoring, place the cursor over either the method definition or usage and press Ctrl+R, Ctrl+V (Refactor, remoVe) to display the Remove Parameters dialog. Figure 8: It’s easy to remove parameters with the Remove Parameters dialog. Select the parameter to remove and press Delete. The parameter you want to remove is then shown in strikeout font and a preview of the method is shown. Click OK. If you selected Preview reference changes, a second dialog showing the changes is displayed. Click Apply. Visual Studio then refactors out the parameter. Do you think about the order of parameters in a method? Does it really matter? Good coding practices says it does. You should order parameters from most important to least important and optional parameters should fall at the end. Now, you may have a differing opinion and that’s okay. But this refactoring helps you get parameters in the order needed. Interestingly, this is one refactoring pattern Martin Fowler doesn’t catalog. Now on to the usage. Place the cursor on the method definition or usage and press Ctrl+R, Ctrl+O (Refactor, reOrder). The Reorder Parameters dialog is displayed. Select the parameter to move, then use the mover arrows on the right. You can optionally preview changes. Click OK, then Apply if you previewed changes. Again, Visual Studio does all the updates for you. There you have it. You’ve learned a bit about what refactorings are and why you want to refactor your code. I have shown you the built-in refactorings in Visual Studio. If you look at the Martin Fowler book, you’ll see dozens of refactorings. He also has an online catalog with even more refactoring at. If you want more automatic refactorings, look to tools like Resharper or CodeRush. These commercial tools add enhancements to the built-in Visual Studio refactorings and add even more refactorings. Refactoring your code is important to keep it maintainable and easy to read. It also helps reduce potential bugs and could improve your application’s performance. It’s pretty clear that refactoring is a practice that will keep your code lush, green, and vibrant. Read our.
https://www.dotnetcurry.com/software-gardening/1105/code-refactoring
CC-MAIN-2018-51
refinedweb
2,523
65.32
Learning C++ as a beginner can seem daunting given the enormity of the language. However, as C++ is both old and ubiquitous, there’s already tons of material online to help you get started. So then why write another guide? This one aims to be a little different from most C++ intros. We won’t spend much time on syntax - you can find all that better-documented elsewhere (1) (2) . Instead, this guide is a fast-paced lecture-style treatment of the ‘Big Ideas’ behind C++. These ideas are the fundamental reasons C++ is still widely used today, despite all the progress that has been made in the field of programming languages. The aim of this guide is to ground you so that, afterward, you should be able read up on nitty-gritty details and work them into the bigger picture. The only requirements are some background in a more modern object-oriented language with C-style syntax (Java, C# and Go all qualify), and completion of a basic syntax-oriented tutorial for C++. You don’t need to know C, nor will we cover C. Without further ado, here are the big ideas: - Close-to-the-Metal Type System - Resource Lifetimes Tied to Execution Flow - Single-Pass Compilation Model 1: Close-to-the-Metal Type System One of the commonly cited reasons people use C++ is that it provides ‘low-level memory access.’ To understand what that means, let’s reflect for a moment on programming type systems. You’ve probably heard before that everything stored by a computer, whether in RAM, on a hard disk, in a CPU register, or barreling down an Ethernet cable, is just binary. One of the chief jobs of a programming language is to insulate you from this. To you, ints are just mathematical integers, on which you can perform arithmetic. strings are just bits of text that can be sliced, diced and spliced. But every time you manipulate a variable, you’re really just changing a number that’s stored as binary in some cell in RAM. Different ‘types’ are just different ways of interpreting these numbers. Like most programming languages, C++ provides an abstraction over bytes as primitive types, and objects composed of primitive types. Unlike many programming languages, C++ provides a very thin abstraction, and makes it easy to drop into the actual byte representation. For starters, C++ makes some guarantees about the byte representation for its primitive types. It provides a range of numeric types, which differ only by the number of bytes it takes to represent them: charis always 1 byte (for this reason, programmers often use chars to manipulate byte buffers) shortis larger than char, but smaller than a standard int(typically 16 bits) intis typically 32 bits longis typically 32-64 bits, depending on your processor architecture long longis typically 64 bits - and so on. For user defined types ( classes and structs), C++ simply concatenates the byte representation for each field in the type. So the following struct: struct MyData { int SomeData; int MoreData; }; ends up stored something like this in memory: If you had an instance of MyData and set its MoreData field to some value (say, 7), the compiler would generate machine code that says: - Start at the byte address of the MyDatainstance - Skip forward 4 bytes - Set the next 4 bytes to 0x00 0x00 0x00and 0x07, respectively. One result of this strategy is that type information is only known at compile time: the compiler generates machine code that, at runtime, used a fixed offset and byte count to assign a value to some variable. Since the type information is gone at runtime, C++ has very primitive reflection abilities. Another result of this strategy is accessing some field of an object is dirt cheap, especially compared to those modern languages which must look up every field in a hash table! C++’s object representation works recursively for nested user-defined types. So if we nested the struct above in another one as follows: struct Complex { int Before; MyData Data; int After; }; the byte representation would be similarly nested: Now if you set Complex.Data.MoreData = 7, the compiler would start at the address of the Complex instance, jump 8 bytes forward, and set that 32-bit integer to 7. Since every C++ object has a well-defined byte structure, C++ treats both primitives and user-defined data types as value types; that is, when you assign one instance of a certain object to another instance, the compiler simply does a byte-by-byte copy from one instance to the other. Subsequently modifying either of those objects does not affect the other. MyData a; MyData b; a.SomeData = 1234; a.MoreData = 5678; assert(a.SomeData == 1234); assert(a.MoreData == 5678); b = a; assert(b.SomeData == 1234); assert(b.MoreData == 5678); a.SomeData = 4321; a.SomeData = 8765; assert(a.SomeData == 4321); assert(a.MoreData == 8765); assert(b.SomeData == 1234); // Important: b has not changed, assert(b.MoreData == 5678); // even though a has been changed. Similarly, each time you call a function, C++ copies in each argument by value, using the same byte-by-byte copy technique. As a result of this, a function which modifies one of its arguments does not affect the value that the caller passed in: void fiddleWithData(MyData data) { data.SomeData = 1234; data.MoreData = 5678; } // ... MyData data; data.SomeData = 4321; data.MoreData = 8765; fiddleWidthData(data); assert(data.SomeData == 4321); assert(data.MoreData == 8765); And, like arguments passed into the function, return values are passed out of the function using a byte copy as well. This means that modifying the return value of a function doesn’t modify the original value that was returned: class Container { private: MyData data; public: Container() { data.SomeData = 1234; data.MoreData = 5678; } MyData getData() { return data; } }; // ... Container container; MyData data = container.getData(); data.SomeData = 4321; data.MoreData = 8765; assert(container.getData().SomeData == 1234); assert(container.getData().MoreData == 5678); Of course, all this copying isn’t free. One common criticism of C++ is the difficulty of diagnosing performance problems caused by excessive copying. It’s not too unusual for objects to be dozens of bytes long. A program that is constantly passing hundreds of bytes into every function call is liable to be uniformly slow: there is no obvious bottleneck, because CPU time is being wasted every time a function is called. The fix for excessive copying is to pass objects by reference instead. To do that, we’ll need to start using pointers. Like all data types, a pointer is just some binary with a special meaning. C++ pointers work a lot like integers: you can assign them arbitrary numeric values and do arithmetic on them. Unlike ints though, pointers can be dereferenced. When you dereference a pointer, the compiler treats the pointer’s value as a byte address in memory. If you picture all of RAM as a giant array of bytes (regardless of how your program is using these bytes), a pointer is just an index into this byte array. C++ provides the pointer-dereferencing operator * to allow you to dereference a pointer, in order to read or write the value at the RAM address stored in that pointer: void pointerTest(int *intPtr, MyData *dataPtr) { int num = *intPtr; num += 1; *intPtr = num; MyData data = *dataPtr; data.SomeData = 4321; *dataPtr = data; } C++ also provides field deferencing operator -> void pointerTest2(MyData *data) { (*data).SomeData = 4321; // This syntax is equivalent data->SomeData = 4321; // to this syntax } Let’s reconsider the example near the beginning of this section, where we walked through how the compiler would set data.MoreData = 7. Let’s do the same thing with a pointer to a MyData instance: what does the compiler do with data->MoreData = 7? The answer is basically the same; only the first step is different: - Start at the byte address stored in the datapointer - Skip forward 4 bytes - Set the next 4 bytes to 0x00 0x00 0x00and 0x07, respectively. What’s important to realize is that we never actually checked that what we’re doing makes sense :-). When you say data->MoreData = 7, the compiler generates machine code that does some pointer arithmetic and then copies some bytes. It does not (and, in fact, cannot) verify that the address you’re writing to is really an instance of MyData, or that the memory address is valid at all! In other words, the snippet data->MoreData = 7 does exactly the same thing as the following snippet: char *bytes = (char*)data; int *moreData = (int*)(bytes + 4); *moreData = 7; These semantics for referencing memory and dealing with types are what makes C++ so ‘close to the metal’. The entire type system is basically syntactic sugar on top of byte offsets that get hardcoded by the compiler. Although this is about as fast as you can get, you also can’t be sure that the pointer contains a meaningful memory address. If you’re lucky, a buggy pointer will contain an invalid address, and attempts to dereference it will crash the program. If you’re unlucky, a buggy pointer will actually point back into data your program is using, returning bogus data when read from and corrupting memory when written to! To help prevent this kind of bug, C++ has reference types. Reference types are just pointers in disguise. They also come with additional semantics: unlike pointers, references must always be initialized to the address of an existing object. You also cannot do arithmetic on references as you can with pointers. This makes reference types safer than pointers for referencing object instances, but less powerful than pointers overall. Back to our original discussion about passing function arguments, we can now use pointer types to pass a MyData instance by reference. Note that, internally, what actually happens is the compiler copies in the pointer itself by value; but since both copies of the pointer contain the same memory address, the same object gets modified when either copy of the pointer is dereferenced: void acceptPointer(MyData *data) { data->SomeData = 1234; data->MoreData = 5678; } We can accomplish the same thing using reference types instead of pointers: void acceptReference(MyData &data) { data.SomeData = 1234; data.MoreData = 5678; } When calling functions, it’s often better performance-wise to pass in a pointer or reference to an object rather than copying the whole object by value. In fact, this is true pretty much any time sizeof(Object) > sizeof(Object*). Copying a reference rather than the full object reduces the overhead induced in calling the function. Unfortunately, though, passing by reference opens the door to functions modifying the caller’s passed-in objects as a side effect. To work around this, a common idiom in C++ is to accept a const reference to an object as the input to a function: void acceptConstRef(const MyData &data) { // data.SomeData = 1234; <-- causes a compilation error MyData localCopy = data; localCopy.SomeData = 4321; } With this idiom, we can reap the performance benefits of passing an object by reference, while also guaranteeing that calling the function will not modify the original object. Note that a function that takes a const reference to an object can still make a local copy of the object (see localCopy in the example above). This is allowed because all that’s needed to initialize localCopy is to read data byte by byte - no modification occurs. Even though creating a local copy of an object negates any performance benefit we gained by passing in the original argument by reference, it’s rarely necessary to make local copies, as functions tend to only read most of their input arguments. That wraps up our discussion of types, pointers and memory addressing! The key takeaways are as follows: Types are an interpretation of byte offsets relative to a starting byte. Pointers are integers which store a starting byte. Variables are always initialized using a byte copy, but you can pass a pointer by value to share a reference. 2: Resource Lifetimes Tied to Execution Flow One common description of C++ is that it has no automatic memory management. Whenever you use new to allocate an object, you must later call delete to free the memory when you’re done with it. If you forget to delete this memory, it stays marked as allocated, but your program stops using it (in other words, the memory gets leaked). If you leak enough memory, eventually your program will run out. And once it fully runs out, it basically has one option: crash. Of course, all but the smallest programs require frequent memory allocation. So why don’t C++ programmers all go crazy trying to track their news and deletes? The answer is simple: C++ doesn’t require you to manage all of your memory. In fact, you can have C++ handle almost all the memory you use; there are only a few cases where you need to manage memory yourself. If you’ve been following this guide so far, you’ve already made plenty of automatically managed allocations. To have the compiler manage a variable’s memory, just declare it directly: void stackAllocation() { int value; // Allocates sizeof(int) bytes on the stack MyClass obj; // Allocates sizeof(MyClass) bytes } These allocations are local to the scope in which they appear. In C++, a scope is defined by the { } characters: { denotes the beginning of a scope, and } marks the end of the matching scope: void aFunction() { // function-level scope while (true) { // sub-scope } } This type of allocation is known as stack allocation, because the compiler allocates memory for variables on the call stack. The call stack is a data structure implemented in your computer’s hardware. It’s called the call stack because it keeps track of function calls, allowing a callee function to return the context of the caller. It’s called the call stack because the last bytes allocated are the first bytes freed. This is in line with function calling, where the last function called must be the first function to return. In C++, usage of the call stack roughly corresponds to program scope. Memory for a variable within a { } pair is allocated allocated when control flow reaches the beginning of the scope ( {), and is deallocated when control reaches the end of the scope ( }). It might seem strange to mix a function’s local variables with the bookkeeping information needed to return from a function, but doing so has some nice benefits. For example, when a variable is allocated on the stack, the compiler knows exactly when the variable is and is not accessible, and can thus allocate and deallocate memory for that variable by itself: void someFunction() { // (A) if (true) { // (B) int num = 1; } // (C) // (D) } At point (A) in the example above, the variable num is not yet accessible, so no memory needs to be allocated for it yet. At point (B), we enter the scope in which num is declared. At this point, the compiler will allocate sizeof(num) bytes on the call stack to hold the value for num. THen, at point (C), we exit the scope that contains num. At this point, the compiler deallocates the memory for num. At point (D), num is no longer accessible, and there is no longer memory allocated for num. There’s a second benefit to stack allocation as well: on modern CPU architectures, the compiler can allocate room on the stack with just one instructions. This is about as fast as memory allocation can get :-) Unfortunately, there are some drawbacks to stack allocation. The compiler always deallocates memory once its parent scope exits. If you need to return a value to a caller outside that scope, you have to incur the cost a full byte-by-byte copy. Also, the call stack generally has a fixed size (usually a handful of megabytes). If you try to stack-allocate more memory than the stack has room for, you end up overflowing the stack, which crashes the program. Heap allocation addresses the shortcomings of stack allocation. You can allocate on the heap using new and delete, as previously mentioned: void heapAllocation() { MyClass *obj = new MyClass; delete obj; } The primary difference between the stack and the heap is that memory allocated on the heap is not freed until your program uses the delete operator on a new-allocated pointer. This has more or less the inverse pros and cons as stack allocation: Unlike the stack, the heap makes it easy to return memory from a local scope to the parent scope. In stack allocation, this was impossible without a byte-by-byte copy. The size of the heap is more or less unlimited, constrained only by the amount of physical storage your machine has. In stack allocation, we were limited to a handful of megabytes. The compiler does not know when you’re done with heap memory; you have to tell it explicitly using the deleteoeprator. In stack allocation, we let the compiler clean up automatically. Allocating on the heap is relatively slow, since the heap allocator must run a complex algorithm to find a free spot. In stack allocation, we could allocate with a single instruction. The key takeaway is that allocating on the stack is both fast and hard to mess up. You want to use the stack whenever possible. You only want to allocate on the heap if the object must survive after its original scope ends, and/or if the object is very large. Let’s take another look at the heap allocation snippet we showed earlier: void heapAllocation() { MyClass *obj = new MyClass; delete obj; } There are two allocations in the function above. Can you spot them both? The answer is in the next paragraph. The first allocation (chronologically speaking) is the trickier of the two to spot. The compiler first stack-allocates a MyClass * (a pointer to a MyClass object). Second, the new operator allocates a MyClass instance on the heap, and returns a MyClass * that points to that instance. The stack-allocated MyClass * is initialized to a reference to the heap-allocated MyClass. When the delete operator is used in the example above, the MyClass instance on the heap gets deallocated. It’s important to note that the MyClass * on the stack is still allocated, and now points to an invalid memory address! The MyClass * gets automatically cleaned up once heapAllocation() returns, ending the scope in which obj is defined. The following rewrite of the example above makes it a little clearer what’s going on: void heapAllocation() { MyClass *obj; // Stack-allocate MyClass * obj = new MyClass; // Heap-allocate MyClass delete obj; // Heap-deallocate MyClass } // Stack-deallocate MyClass * So far we’ve discussed ‘use-after-free’ bugs with heap-allocation, a class of bug where a program continues to dereference a pointer after the value the pointer contained has already been freed. There is another similar type of bug in heap allocation called a double-free. C++ requires that any pointer returned by new must be deleted exactly once. A double-free occurs when the program tries to delete a pointer whose value has already been deleted. C++ programmers deal with the risk of double-frees by employing the concept of ‘ownership’. C++ itself does not have a notion of ownership; instead, ownership rules are usually communicated through function-level documentation comments. The function or object which ‘owns’ a pointer is responsible for freeing it. This can be done either by directly calling delete, or by transferring ownership to another function or object, which will then take on the onus of deleting it later. A common ownership pattern is for an object to own a pointer. The pointer is a member of the object, and gets deleted by the object in its destructor. That way, whenever the object gets deleted, the data it owns also gets deleted. Refer to the following example: class Owner { private: MyData *m_data; public: Owner() : m_data(NULL) { } ~Owner() { if (m_data != NULL) { delete m_data; m_data = NULL; } } // Returns the MyData object tracked by this Owner. // The caller does not own the MyData * returned and must // not release its memory. MyData *getData() { return m_data; } // Sets the MyData object tracked by this Owner. // This object will take ownership of the given MyData instance. void setData(MyData *data) { if (m_data != NULL) { delete m_data; } m_data = data; } }; In the example above, the Owner object ‘owns’ the m_data pointer by convention. The getData() method is documented as not transferring ownership to the caller, meaning the caller must not delete the return value. The setData() method is documented as transferring ownership of the pointer to the Owner object, meaning the Owner is taking on the onus of calling delete in the future, and that, again, the caller must not delete the value being passed in. The Owner object above lets us do something interesting: even though Owner owns a heap-allocated pointer to a MyData object, Owner itself can be stack allocated: void someFunction() { Owner own; own.setData(new MyData); } When control flow reaches the } at the end of someFunction() above, own (which is stack allocated) goes out of scope. This causes the destructor own.~Owner() to get called, which in turn heap-deallocates own’s m_data instance before the own itself is stack-deallocated. Thus, even though the MyData instance in the example above is heap-allocated, we’re still able to tie its lifetime to control flow, just like stack-allocated variables! The Owner object above exhibits the basis for a type of C++ object called a smart pointer. Smart pointers are typically stack-allocated, but track a single heap-allocated ‘inner’ pointer. When the outer object goes out of scope, C++ calls the smart pointer’s destructor, which in turn heap-deallocates the inner pointer. This is the pattern exhibited by the Owner object above. Unlike Owner, real smart pointer objects typically use advanced features like templates and operator overloading so that the smart pointer object behaves as much as possible like the inner pointer type. In summary, You control when memory is allocated and freed. Use destructors to tie memory lifetime to execution scope for maximum convenience. Explicitly define in your program logic who owns which object(s). 3: Single-Pass Compilation Model C++ supports a different compilation model than you may be familiar with. Namely, C++ is designed to work with single-pass compilers, whereas modern languages tend to rely on multiple-pass compilation. To understand what this means, we’ll have to take a tiny peek at compiler internals. In a compiled programming language, the compiler’s job boils down to: - Finding type definitions - Compiling each definition to executable machine code - Hooking definitions together to form a complete program Let’s compare a multi-pass Java compilation to a single-pass C++ compilation. Consider this Java source file: public class Counter { private int field; public Counter() { field = 0; } public int getNext() { System.out.println("Somebody called getNext()"); incrementField(); return field; } private int incrementField() { field += 1; } } Here’s how Java handles this class: First, it scans the source file for type definitions. It finds definitions for symbols like Counter, Counter.field, and Counter.getNext(), to name a few. It saves basic type information about these symbols for later. Then the compiler revisits the source file and compiles each definition. Whenever a definition references another type, Java uses the basic type information to generate a stub referencing that type. Finally, once each definition has been fully compiled, Java combines the compiled definitions together into a single program. This model is called multi-pass, because Java needs to scan each source file multiple times to compile it. Now let’s take a look at the equivalent C++ class: class Counter { private: int field; int incrementField(); public: Counter(); int getNext(); }; Counter::Counter() { field = 0; } Counter::getNext() { incrementField(); return field; } Counter::incrementField() { field += 1; } C++ is designed to be compatible with single-pass compilation: a compiler should only need to walk through a C++ file once to completely compile it. Given a source file, the compiler parses it from top to bottom and compiles it. Whenever it runs into a definition, it compiles the definition on the spot. Then, at the end of compilation, it combines all those compiled definitions into a single program. This poses a problem, though: if the definition references another type, the compiler must already know about the type being referenced. Otherwise the compiler wouldn’t be able to validate that this type actually exists later on in the file, and isn’t just a user typo. To solve this problem, C++ makes extensive use of a technique called forward declarations. Unlike a definition, a forward declaration doesn’t give the compiler enough information to compile the type being declared. Instead, the declaration just tells the complier that you intend to fully define that symbol later, and also gives the compiler basic information about what that symbol is (a class, a variable, a method, etc). In the example above, we gave the compiler two forward declarations: inside the class Counter scope, we gave the compiler forward declarations for getNext() and incrementField(). Later in the file, we actually defined those methods by writing a method body. The compiler processed the file from top to bottom, and since we declared these two methods at the top, the complier knew about each method before it reached either method’s definition near the bottom. This allowed us to reference incrementField() inside of getNext(), even though incrementField() is defined later in the file. Here’s the same example file as above, except we put the method definitions before their declarations. This file won’t compile, since the compiler won’t know about incrementField(), or even class Counter, by the time it gets to the definition for getNext(): Counter::getNext() { std::cout << "Somebody called getNext()\n"; incrementField(); return field; } Counter::incrementField() { field += 1; } Counter::Counter() { field = 0; } class Counter { private: int field; int incrementField(); public: Counter(); int getNext(); }; One last note about forward declarations: the compiler allows you to declare a symbol as many times as you want, provided each declaration is the same. However, you can only define a symbol once. So far we’ve only been talking about compiling a single file, but only the smallest of programs consist of just one source file. How can we compile multiple files into a single program? In C++, programs are compiled in two steps: First, the compiler compiles each source file individually. For each source file, it produces a corresponding object file containing compiled machine code for each definition contained in that source file. References to external types are stubbed out in these object files. Second, the linker links the object files into a single binary file, which is typically either a library or an executable program. The linker basically joins all the compiled definitions, and then fills in stubs left by the compiler. Herein lies another problem: each time the compiler processes a source file, it starts from scratch and scans the source file from top to bottom. No state is shared between different invocations of the compiler. But source files often reference each other: it’s not uncommon for one source file to define a method, and for another source file to use it. A simple, but hard-to-maintain way to get around this is to manually declare objects and methods you want to use at the top of every C++ source file. But this is cumbersome and hard to maintain, especially once you start trying to use classes in the standard library. The C++ solution to this is the header file. The idea behind header files is to move declarations (but not definitions!) to a single shared file. Every .cpp source file that needs those declarations can import the .h header file using the #include directive. For example, we can rewrite our example above as follows: counter.h: class Counter { private: int field; int incrementField(); public: Counter(); int getNext(); }; counter.cpp: #include "counter.h" Counter::Counter() { field = 0; } Counter::getNext() { std::cout << "Somebody called getNext()\n"; incrementField(); return field; } Counter::incrementField() { field += 1; } Again, notice how counter.h only has declarations, and counter.cpp only has definitions. Now we can write a main() method that uses the counter class: main.cpp #include "counter.h" int main(int argc, const char *argv[]) { Counter myCounter; for (int i = 0; i < 10; ++i) { int num = myCounter.getNext(); bool debug = (i == myCounter.getNext()); // debug should always be true } return 0; } One important thing of note: the compiler processes #include directive using a component called the preprocessor, and the preprocessor is pretty dumb. Here’s how include directives are processed: First, the compiler makes a temporary copy of the source file in memory. It invokes the preprocessor on this in-memory source file (note this never gets written back to the original file on-disk). The preprocessor walks through the file from top to bottom. Whenever it finds an #includedirective, it loads the file to include. If there is no such file, compilation is aborted. Next, the preprocessor deletes the source file line containing the #includedirective Finally, the preprocessor pastes the full text of the included file into the .cpp source file at the line of the #include directive Once the preprocessor exists, the compiler walks through the preprocessed file to compile the program. That has a few important ramifications. One is that, even though the counter.cpp above compiles correctly, this one won’t: Counter::Counter() { field = 0; } Counter::getNext() { std::cout << "Somebody called getNext()\n"; incrementField(); return field; } Counter::incrementField() { field += 1; } #include "counter.h" Why doesn’t this work? The fully preprocessed text of this file is as follows, and we’ve already discussed why this doesn’t compile: Counter::Counter() { field = 0; } Counter::getNext() { std::cout << "Somebody called getNext()\n"; incrementField(); return field; } Counter::incrementField() { field += 1; } class Counter { private: int field; int incrementField(); public: Counter(); int getNext(); }; To recap, here’s the core idea from this section: C++ requires every symbol you reference to be declared or defined prior to the time you use it. Publish declarations in header files, so that any definition in a source file can reference the symbols it needs. Now it’s time to try putting everything together. We’re going to compile the counting example above into a working program. Here’s our high-level strategy: We will invoke the compiler twice: once on each source file. The output of each invocation will the source file’s corresponding object file. Then we will invoke the linker on the object file. The output will be a working program! Let’s walk through the compilation process. We (or our IDE) invokes the compiler on counter.cpp. The compiler loads this file into memory: #include "test" test #include "counter.h" Counter::Counter() { field = 0; } Counter::getNext() { std::cout << "Somebody called getNext()\n"; incrementField(); return field; } Counter::incrementField() { field += 1; } The compiler preprocesses the in-memory file. Upon finding #include "counter.h", the preprocessor loads it in. After preprocessing, the in-memory file looks like this: class Counter { private: int field; int incrementField(); public: Counter(); int getNext(); }; Counter::Counter() { field = 0; } Counter::getNext() { std::cout << "Somebody called getNext()\n"; incrementField(); return field; } Counter::incrementField() { field += 1; } The compiler walks through the file. - At the top, it finds a definition for class Counter. - Walking through that definition, it finds forward declarations for the constructor, incrementField(), and getNext(). - As it continues to walk the file, it finds definitions for those methods. It compiles each method as it encounters the definition. The resulting compiled definition contains a stub wherever the code referenced another definition. - The compiler saves all the compiled definitions in an object file for counter.cpp (usually counter.oon UNIXes, counter.objon Windows). We repeat step (2.) on main.cpp. The preprocessed result looks like this: class Counter { private: int field; int incrementField(); public: Counter(); int getNext(); }; int main(int argc, const char *argv[]) { Counter myCounter; for (int i = 0; i < 10; ++i) { int num = myCounter.getNext(); bool debug = (i == myCounter.getNext()); // debug should always be true } return 0; } We repeat step (5.) on main.cpp. The resulting object file is either main.oor main.obj, depending on your platform. We invoke the linker on counter.o[bj]and main.o[bj]. - The linker concatenates each of the compiled definitions into a single program binary. - The linker scans through the compiled definitions. Whever it finds a stub for referencing another definition, it fixes the stub to actually call into the referenced code. The linker writes the final binary to disk. Now we can run it! Recap In summary, here are the three core concepts this guide boils down to: - Types are an interpretation of byte offsets relative to a starting byte. Pointers are integers which store a starting byte. Variables are always initialized using a byte copy, but you can pass a pointer by value to share a reference. - You control when memory is allocated and freed. Use destructors to tie memory lifetime to execution scope for maximum convenience. Explicitly define in your program logic who owns which object(s). - C++ requires every symbol you reference to be declared or defined prior to the time you use it. Publish declarations in header files, so that any definition in a source file can reference the symbols it needs. Having grokked the concepts above, we hope you now have enough of a working framework to fit in all the small details about writing C++ code. You’re not done with your journey, but you’re off to a good start. Best of luck!
http://davekilian.com/framing-cpp.html
CC-MAIN-2018-39
refinedweb
5,596
54.02
Etelemetry python client API Project description Etelemetry-client A lightweight python client to communicate with the etelemetry server Installation pip install etelemetry Usage import etelemetry etelemetry.get_project("nipy/nipype") {'version': '1.4.2', 'bad_versions': ['1.2.1', '1.2.3', '1.3.0']} or to take advantage of comparing and checking for bad versions, you can use the following form import etelemetry etelemetry.check_available_version("nipy/nipype", "1.2.1") # github_org/project A newer version (1.4.2) of nipy/nipype is available. You are using 1.2.1 You are using a version of nipy/nipype with a critical bug. Please use a different version. returns: {'version': '1.4.2', 'bad_versions': ['1.2.1', '1.2.3', '1.3.0']} Adding etelemetry to your project You can include etelemetry in your project by adding etelemetry package to your setup process and by adding the following snippet to your __init__.py. The code snippet below assumes you have a __version__ and usemylogger (logger) variables available. The check takes the form of github_org/project. # Run telemetry on import for interactive sessions, such as IPython, Jupyter # notebooks, Python REPL import __main__ if not hasattr(__main__, "__file__"): import etelemetry etelemetry.check_available_version("dandi/dandi-cli", __version__, lgr=usemylogger) To add support checking for bad versions you will need to add a file named .et to your github project containing a simple json snippet. { "bad_versions" : [] } Here is an example: Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/etelemetry/
CC-MAIN-2021-49
refinedweb
256
68.47
DaST pattern and ASP.NET DaST Rendering Engine is a further development of the ASP.NET Scopes Framework and its underlying server page technology based on fully templated data scope trees which I proposed in my first article in November 2010. From now on the pattern will be called DaST which stands for Data Scope Trees. After working with DaST for a while, my opinion is that this approach opens unmatched web development opportunities and has all chances to completely replace standard ASP.NET Forms and MVC patterns in the near future. This article consists of 4 parts. First of all, I'll present a new VideoLibrary DEMO application which demonstrates full power of DaST pattern on a real web site. This application will serve as a good how-to sample and a DaST technology demonstrator for all further releases of ASP.NET DaST framework. In the second part I'll give a brief overview of the DaST concept itself and will decompose a VideoLibrary page to a scope tree, so that those who see this technology for the first time could get an idea about the new DaST approach and its advantages. In the third section I'll take a closer look at the demo application back-end architecture and implementation and will highlight all important syntax and design changes that took place since 1st Alpha release in November. This section is targeted only for those, who read my previous article. And in the final section I'll share some framework development plans for the near future. One more thing As many of you criticized my previous article for its length, I'll keep this one short, lean and mean. But if you come across this framework for the first time and you wish to try it in your projects, current article will not be enough and you'll have to read my more detailed and deep Scopes Framework article from November. Currently, all DaST releated news and events are posted on the DaST development site. Check this site for framework updates and important changes. The latest version of ASP.NET DaST Rendering Engine as well as the VideoLibrary DEMO source code are located in the download section of the site. !!!UPDATE (May 11, 2011): ASP.NET DaST Rendering Engine project has officially become open-source starting from May 9th! We're looking for open-source developers, so if you feel you can contribute the project, you're welcome to contact the DaST team. DaST open-source information site is here. DaST project console home on SourceForge is here. Public DaST discussion forums are here (anynimous access is enabled) To demonstrate advantages of DaST web development pattern over the standard Forms and MVC approaches, I created a sample application, VideoLibrary, which will serve us as an example, tutorial, and technology demonstrator in the same time. VideoLibrary DEMO is a prototype of a video portal built on ASP.NET DaST framework. Having complex and dynamic UI, this sample application includes most of typical functional elements used to build rich Web 2.0 sites and demonstrates how these functionalities could be achieved using DaST Rendering Engine. Here are some nice and very popular Web 2.0 features that are implemented in VideoLibrary: The following are some application screenshots (Fig. 1 and Fig. 2) and brief description of how the application operates on a user level. Although the application does not do much meaningful things by itself and serves mostly as demonstrator, it can be used as a prototype for a similar applications in a real world. Note that Fig. 1 and Fig. 2 show the application in 2 different jQuery UI themes. Fig. 1: VideoLibrary DEMO initial look The application displays paged selection of a number of video packshots (see Fig. 1). Of course, there are no real videos -- we just use black rectangle with colored text on it. Color of that text defines the category of the video: red category, green category etc. Each packshot has "+" button in the top-right corner. Clicking on it, the video is added to the playlist on the left side and button turns to "-". Clicking "-" removes video from the playlist. On mouse hover, the packshot displays "i" button which invokes the details dialog window. Fig. 2: VideoLibrary DEMO details dialog The dialog window (see Fig. 2) displays some more details and paged list of video packshots in the same category (i.e. with the same color). Packshots in this list work the same way as in the playlist and the selection grid. The dialog window is tabbed. You can switch to another tab to add video reviews and ratings. Note that all changes you make are saved within your current session only. You can also play with application look-and-feel by selecting your favorite jQuery UI theme in the top-left corner. All application data comes from data layer simulated by XML file and LINQ. Since this application is a DEMO, I've made it so that all changes you make (add reviews, ratings, playlist, etc) are persisted within the current session only and are discarded when the session ends. On Fig. 3 you can see a part of XML file used as a data source. It's structure is trivial and you can get an idea how VideoLibrary data is organized. Fig. 3: Back-end data XML Although, beautiful and attractive UI elements is an important part of the application, all the advantages of DaST web development pattern become obvious only when we look at the application back-end code. Being clear, transparent and uniform, the DaST architecture of the VideoLibrary back-end results in unmatched front-end flexibility and allows almost unlimited complexity of the web application UI. If you wish to run the live test of VideoLibrary DEMO application immediately, you can do this on the DaST Development Site where I'll always deploy the latest version of this application. The entire VideoLibrary DEMO source code is available for download as attachment to this article. I suggest that you get the source code, browse and get familiar with it, as for the rest of this article I'll use this sample code for all my explanations. Do you think it is possible to create an ultimate server page rendering engine that outperforms standard Forms and MVC in easiness, architecture, flexibility, performance, presentation separation, and all other important web development attributes? As the answer to this question I'd like to present the ASP.NET DaST Rendering Engine based on a new DaST web development pattern. The name of the pattern stands for Data Scope Trees and you'll understand what this means later. Even if you're an experienced web application programmer or architect, and not familiar with this pattern yet, I promise that the rest of this article will change your idea about the server-page based web application design and development. The entire DaST concept departs from a very simple thought that every web site in the world is nothing, but a bunch of data produced by server-side logic and presented to the user in the client browser. All you see on a web site is just some data wrapped into HTML text! This means that the entire page rendering process can be viewed as two separate steps: 1) generation of some data values and 2) presentation of these data values in the form of HTML to the client. To accomplish data generation on the first step we need some kind of codebehind class. Speaking abstractly, the output of such class would be a set of string values. In DaST framework this class is called a controller (like in MVC). The second rendering step is more interesting. After all string values are generated by the controller, we need to mix them with some markup and give the HTML output to the client. Sounds simple, but how to accomplish this technically? Every experienced developer knows how standard Forms or MVC platforms render their pages by going though the complicated and resource consuming page lifecycle, rendering multiple individual server controls, applying master pages, calling data binding implementations for repeating controls, processing events, etc. etc. This process is quite complex and we will try to approach the rendering task from another side. In order to render our prepared data into HTML, we will just take a complete and valid HTML template and insert the prepared string values into this template at the right spots. The spots where data values get inserted are marked with special placeholders which are replaced on rendering stage by real data values. And this is it! We just need a pure HTML template and nothing else -- no server controls, no page lifecycle, no data binding -- we just dumped all that complexity at once! Look at our demo application on Fig. 1. Now imagine if we had a list of prepared data values (like all those names, descriptions, page numbers, etc) and a complete HTML template with placeholders at the locations where values are to be inserted. What would our rendering process be? Well, the entire rendering would be reduced to a trivial search-and-replace operation for substituting placeholders by the real values. And this is basically all the DaST does to render your pages! Of course, I abstract away some technical details by just saying that a bunch of data gets applied to the template. In reality, this process has to be more granular, because we also need some way to manage our data values so that they get applied at the right location only. Having placeholders is not enough, because we simply don't want to produce all data values at once and, moreover, we may not be able to. It's much better to, first, produce values for one area of the page, then for another, and so on. Plus we need some way to provide data for repeated content that can be nested in another repeater at any level. And what about Ajax and partial page updates? Thinking about all these requirements I finally came to the idea of the data scopes and data scope trees which became the core of the DaST pattern (hence, the pattern name) and the framework based on it. Data scope is simply a group of cohesive data values. Cohesion criteria is chosen by the developer. Data scope can be applied to the specific area of an HTML template, meaning that placeholders in that area are replaced by the corresponding data values from data scope. As a result, we get the final HTML output for this specific piece of the template. Extending this technique for the entire page, we can have multiple data scopes applied to all of the areas of HTML template to render the template completely and output the page to the client. Data scopes can also be nested to form hierarchical structure called data scope tree. And finally, I assert the every page of any complexity can be viewed as an HTML template with a data scope tree applied to it. Voila! So, first thing that a web developer must accomplish is to decompose the application UI to a set of randomly nested data scopes. From my own experience, choosing the right data scope nesting structure requires some DaST specific skills that come after several exercises. Let's do this for a part of our demo application UI shown on Fig. 1. The resulted data scopes are shown on Fig. 4. Fig. 4: VideoLibrary partial UI decomposition into data scopes First of all, there is always a root scope (NULL scope) that serve as a parent of all other scopes. Then we have PageSizeRepeater and SiteThemeRepeater to output items for page size and for jQuery theme drop-down lists (see Fig. 1). Next we have several other data scopes on the left side to form playlist UI. PlaylistHeader scope shows current pager info. PlaylistPager scope wraps a playlist item pager. PlaylistRepeater is needed to display multiple video packshots represented by a nested VideoItem scope. Each VideoItem scope has 2 more nested scopes: AddButton and RemoveButton. The idea is to show only AddButton scope when item is not in the playlist, and only RemoveButton scope otherwise. Next, on the right side of the page we have a video item selection grid. Structure for this grid is absolutely the same as for playlist except that data scopes on the same level have different names. Now, if we depict our nested data scopes on Fig. 4 as tree, we will get a data scope tree identifying our page. A complete data scope tree for the VideoLibrary application is shown on Fig. 5. Upper part of the tree corresponds to UI on Fig. 1 which we have just decomposed. The bottom subtree coming from DetailsPopup scope corresponds to UI on Fig. 2. Data scopes with attached controllers have red backgrounds and this will be explained later. Fig. 5: VideoLibrary complete data scope tree Ok, after we logically decomposed the UI into data scopes, next question is how to point the specific data scope at the specific area in the template. The solution here is straightforward. Since our data scope tree is built so that it represents the logical structure of the document, we just use the same structure in the HTML template by wrapping corresponding areas into valid DIV container elements representing boundaries within which data scopes are are applied. This means, that these containers in the HTML template have the same hierarchical structure defined by the data scope tree. Each data scopeis identified by its name e.g. "PlaylistPager" or "VideoItem". The same name should be specified in the scope attribute of the corresponding HTML container element. So, the system does not care how complex your template is is and what type of markup it has -- it only cares about nested scope DIVs i.e. the data scope tree inside this template. For example, if we wanted to create a valid template for data scope tree on Fig. 5, a part of this template could look like the markup on Listing 6. scope your markup here ... <div scope="PageSizeRepeater">your markup here ...</div> <div scope="SiteThemeRepeater">your markup here ...</div> <div scope="PlaylistHeader">your markup here ...</div> <div scope="PlaylistPager"></div> <div scope="PlaylistRepeater"> your markup here ... <div scope="VideoItem"></div> your markup here ... </div> rest of template follows ... NOTE that using only DIVs for scope containers is a limitation of the current version of DaST Rendering Engine and will go away in one of the next versions of the framework. To generate real data for template the developer has to implement a controller class. The process of generating data for the corresponding template I call data binding. For every data scope in the tree and the corresponding scope DIV in the template the controller contains a data binding function called binding handler. The output of a binding handler is basically a set of values for a current data scope. In the simplest case, there is a single controller responsible for generating data for all data scopes in the scope tree. In the normal case, there are multiple controllers and each one of them is responsible only for a part of a scope tree. When a controller is attached to a data scope, it becomes responsible for generating data for this scope and all child scopes in the subtree unless those child scopes have their own controllers attached. Look at Fig. 5 again -- data scopes on the red background are the ones that have controllers attached. There is always at least one controller attached to a NULL scope called a root controller. Other controllers are child controllers. Just like user controls in Forms or partial views in MVC, child controllers in DaST should be used whenever it is appropriate to factor out a certain common piece functionality. One of the examples in our demo application is PagerController attached to PlaylistPager, VideoItemPager, AlikeVideosPager, and data scopes (see Fig. 5). PagerController Now I will redefine the DaST rendering process in terms of controllers and binding handlers. To render the entire page, the framework starts from generating data for the NULL data scope in the tree by invoking the corresponding binding handler in the root controller and recursively repeats this operation for all data scopes in the tree invoking appropriate handlers on responsible controllers. There is always a specific and consistent order in which data scopes are processed. In terms of tree walking algorithms, the framework uses post-order walk with top-to-bottom in-order traversal. Recalling graphs from high school, it's actually called right-to-left in order traversal, but because it is more appropriate to depict scope tree horizontally (like I did on Fig. 5), I call it top-to-bottom. Such traversal order is chosen, because the actual scope DIV tags in HTML template are encountered exactly in this order. So, all the developer needs to do to render a page using DaST Rendering Engine is to 1) create an HTML template similar to the one on Listing 6 and then 2) implement a controller for it (or multiple controllers for multiple templates). Listing 7 shows a high-level outline for the root controller (VideoLibraryController.cs) of our demo application. This root controller is the one attached to the NULL scope on Fig. 5. Binding handlers producing values for corresponding scopes are on lines 87-193. Names of these handler functions are chosen by the developer. On line 10 you see the SetTemplate() function - that's how we tell the controller which template to use. SetModel() function on line 15 is needed to assign binding handlers or child controllers to data scopes in the tree. Finally, lines 45-73 are action handlers invoked in response to user actions (think of these as a counterpart of events). SetTemplate() SetModel() 8 public class VideoLibraryController : ScopeController 9 { 10 public override void SetTemplate(SetTemplateArgs template) { ... } 14 15 public override void SetupModel(ControllerModelBuilder model) { ... } 43 44 45 private void Action_PageSizeChanged(ActionArgs args) { ... } 58 59 private void PlaylistPager_PageChanged(ActionArgs args) { ... } 65 66 private void VideoItemPager_PageChanged(ActionArgs args) { ... } 72 73 private void VideoItem_PlaylistUpdated(ActionArgs args) { ... } 85 86 87 private void ROOT_DataBind() { ... } 104 105 private void PageSizeRepeater_DataBind() { ... } 118 119 private void SiteThemeRepeater_DataBind() { ... } 130 131 private void PlaylistHeader_DataBind() { ... } 165 166 private void PlaylistRepeater_DataBind() { ... } 181 182 private void VideoItemGridInfo_DataBind() { ... } 192 193 private void VideoItemRepeater_DataBind() { ... } 208 } A huge advantage of data scope trees is that they allow for the most clear definition of partial page updates and the simplest usage of AJAX capabilities in web applications comparing to all other existing frameworks. The underlying idea of DaST Ajax is as simple as everything else in DaST -- every scope in data scope tree can be individually refreshed at any time during the async postback! When data scope is refreshed, all its child data scopes in the scope tree are refreshed too. In terms of data binding this means that the system re-invokes binding handlers corresponding to the refreshed scopes to regenerate data values, update parts of the template, and output them back to the client. Data scope tree traversal order is kept on the postback, maintaining the consistent order of binding handler invocation. Next, async postbacks do not occur randomly, but in response to some events in the browser i.g. button clicks, timer ticks, etc. DaST Rendering Engine provides a simple and lightweight mechanism allowing to raise events on the client side, and handle those events on the postback inside the controller classes. In DaST a counterpart of event is called action. Each action has a name and a string argument. This is not a limitation, because string argument can contain just any possible JSON-serializable object. When action occurs, async postback comes to the controller and appropriate action handler is executed (see lines 45-73 on Listing 7). Action handler is the place where we can do some processing and instruct the specific data scopes to refresh. OK, at this point you should have a clear top-level picture of what the DaST pattern and DaST Rendering Engine actually are and how they differ from other patterns and frameworks available to the developers today. Below I will summarize the most obvious benefits of using DaST pattern in your web applications. Main purpose of the current article is to give an overview of important changes in the new version of the framework. If you see this concept for the first time and want to learn in details how to create HTML templates and implement controllers, you'll have to read this article which is much more deep and detailed. Or you can wait until documentation and tutorial becomes available on DaST dev site at, but I can't promise any dates. In this section I'll quickly go through all the important syntax and design changes since the previous version of the framework. I'll not delve into much back-end details, because the entire mechanism has already been described in my previous article in November, I'll only highlight the differences for those who read that article and who is already familiar with the Scopes Framework. So, the following sub-sections is just a list of differences between 2 versions. Changes happened to the framework binary and namespace are the following: AspNetDaST.Web In Scopes Framework I used a temporary solution that we had to add a ScopesManagerControl to an ASPX page to make it work with the framework. Now this is gone. In the DaST Rendering Engine we inherit pages from DaSTPage class from AspNetDaST.Web namespace and implement only one ProvideController() method. You dont have to add any markup to the ASPX page -- DaSTPage parent class takes care of it. Listing 8 shows the listing of VideoLibrary.aspx.cs codebehind class. Everything should be clear: we instanciate the root controller on line 14 and enable partial updates on line 15. Note that currently, EnablePartialUpdates must always be set to TRUE. This is due to the fact that I did not decide yet if we need to support full postback or not. In Forms the reason to make async postbacks optional was that UpdatePanel controls add significant complexity and performance overhead. In DaST, partial refreshes are native and I don't see any reason to make them optional. ScopesManagerControl DaSTPage ProvideController() EnablePartialUpdates TRUE 8 using AspNetDaST.Web; 9 10 public partial class VideoLibrary : DaSTPage 11 { 12 protected override void ProvideController(PageSetup setup) 13 { 14 setup.RootController = new VideoLibraryController(); 15 setup.EnablePartialUpdates = true; 16 } 17 } As you may notice on Listing 7, arguments in binding handlers are eliminated. Handler argument was used to add placeholder replacements for the current scope. From now on, placeholder replacements are added directly to the scope instance which you can access using CurrentPath and ControlPath tree navigators. The meaning of these rendered scope tree navigators has also slightly changed: CurrentPath ControlPath Action(..) Just look at Listing 9 that shows one of binding handlers from DetailsPopupController.cs class. On lines 202-203 instead of calling Replace(..) on the binder object passed as a parameter like it was before, we call Replace(..) directly on the scope instance, using CurrentPath that points to the current ReviewsInfo scope. Replace(..) 195 private void ReviewsInfo_DataBind() 196 { 197 decimal rating = CurrentPath.Scope.Param<decimal>("Rating"); 198 int commCount = CurrentPath.Scope.Param<int>("CommCount"); 199 200 CurrentPath.Scope.ShowConditionArea("comm-empty:yes", commCount <= 0); 201 CurrentPath.Scope.ShowConditionArea("comm-empty:no", commCount > 0); 202 CurrentPath.Scope.Replace("{Rating}", rating.ToString("0.0")); 203 CurrentPath.Scope.Replace("{CommCount}", commCount); 204 205 CurrentPath.Rew(1).Fwd("ReviewsInfo2").Scope.ShowConditionArea("comm-empty:yes", commCount <= 0); 206 CurrentPath.Rew(1).Fwd("ReviewsInfo2").Scope.ShowConditionArea("comm-empty:no", commCount > 0); 207 CurrentPath.Rew(1).Fwd("ReviewsInfo2").Scope.Replace("{Rating}", rating.ToString("0.0")); 208 CurrentPath.Rew(1).Fwd("ReviewsInfo2").Scope.Replace("{CommCount}", commCount); 209 } At the first look it may seem that data binding syntax became more complex, but actually this design gives us a huge programming benefit, because now we are able to databind scopes from inside the binding handlers of other scopes. This is great, because if a scope is simple and contains just a couple of values, why would I flood my controller class creating a separate binding handler for it? This new feature is used on lines 207-208 of DetailsPopupController class (see Listing 9) where we use navigator to point at another ReviewsInfo2 scope and add same placeholder replacements to it. DetailsPopupController In the new version of DaST Rendering Engine all framework calls became more uniform. Now all methods and properties related to manipulation with the specific scope are accessible through the scope instance object. Data binding functions (some of them I already talked about in the previous section) is one group of such methods. Another group of methods provide operations on scope context parameters. Diagram on Fig. 10 shows public interface of RenderedScopeInstance class. RenderedScopeInstance Fig. 10: Public interface of RenderedScopeInstance class. Below is a brief explanation of all class members. Most of them should be well familiar to you from Scopes Framework. Even though the names are changed, the meaning is still the same. Members marked "(NEW)" are the ones that were added in the current version of the framework. In DaST framework content of each scope is output one time by default meaning that the resulting HTML fragment is just whatever this scope container has in the template. In order to repeat scope content, we should call Repeat(..) function on the target scope. We also have a RestartRepeater(..) method (see Fig. 10) that resets repeating count to 0. If this method is called and is not followed by calls to Repeat(..), the scope will not output any content. Listing 11 shows how PlaylistRepeater scope outputs its list of video packshots. First, on lines 168-170 we retrieve pager values from PlaylistPager scope to which PagerController is attached. Then we get list of video items from simulated data layer. Then, on line 173, we have a call to RestartRepeater(..) and, finally, on lines 174-179 we simply loop through the list of objects calling Repeat(..) on each run and passing the video item object to VideoItem scope with VideoItemController attached to it. Repeat(..) RestartRepeater(..) VideoItemController 166 private void PlaylistRepeater_DataBind() 167 { 168 int startItemIdx = CurrentPath.Rew(1).Fwd("PlaylistPager").Scope.Param<int>("StartItemIdx"); 169 int pageSize = CurrentPath.Rew(1).Fwd("PlaylistPager").Scope.Param<int>("PageSize"); 170 int itemTotalCount = CurrentPath.Rew(1).Fwd("PlaylistPager").Scope.Param<int>("ItemTotalCount"); 171 172 object[] videoItems = DataLayer.GetPlayItems(startItemIdx, pageSize); 173 CurrentPath.Scope.RestartRepeater(); 174 for (int i = 0; i < videoItems.Length; i++) 175 { 176 CurrentPath.Scope.Repeat(); 177 CurrentPath.Fwd(i, "VideoItem").Scope.SetParam("ItemIndex", startItemIdx + i); 178 CurrentPath.Fwd(i, "VideoItem").Scope.SetParam("VideoItemObject", videoItems[i]); 179 } 180 } One more new feature in this version of the framework is that we can save generic objects as scope parameters. On line 178 in listing on Listing 11 we set the entire video item object as a parameter for the VideoItem scope. The system accepts any object as scope parameter as long as this object is serializable to JSON i.e. can be saved to a simple string. In the previous version of the framework a data scope could be made invisible meaning that output of this scope was an empty string. In the current version each data scope has more visibility options and this is set using RenderType property of the scope instance (see Fig. 10). This property is of enumeration type and its possible values are summarized below: RenderType Normal Empty None Note that when scope is refreshed, its RenderType is automaticaly reset to Normal. Also, it's important to understand that if visibility is set to None, you will not be able to refresh this scope, simply because there is no HTML container that would be able to accept the new content. Finally, you have to plan which scopes in the scope tree should be used to save parameters, because when you set scope visiblity to Empty or None, all its child scope parameters are discarded. Let's look at the example how delayed loading effect is made on details dialog. Listing 12 shows the most important back-end functions participating in the delayed loading. On the client side, when you click "i" button on any video packshot, jQuery Dialog plugin is used to popup the dialog box. Initially dialog box has only animated loader icon and no other content, because in ROOT_DataBind() method we set DetailsContent scope render type to Empty. This means that none of binding handlers for child scopes of DetailsContent scope are invoked on the initial load. When dialog opens, "LoadContent" action is raised and handled on line 51. Inside this action handler we refresh the DetailsContent scope and set its "VideoID" param to the id passed as action argument from client side. Next, since DetailsContent scope is refreshed, the system re-invokes its binding handler as well as binding handlers of all its child scopes in traversal order. So, DetailsContent_DataBind() on line 170 gets invoked. "VideoID" populated in action handler is retrieved and used inside binding handler to retrieve actual video item and use its values to add placeholder replacements. So, after this binding handler is executed, the system carries updated ouput to the client and DetailsContent scope is updated with real video item info i.e. our delayed loading works exaclty as it should. Notice lines 174 and 175 where we hide CommentsContent and AddCommentScreen to apply the same delayed loading technique to them, but this time within the open dialog box. ROOT_DataBind() DetailsContent_DataBind() 51 private void Action_LoadContent(ActionArgs args) 52 { 53 string videoID = (string)args.ActionData; 54 55 ControlPath.Fwd("DetailsContent").Scope.Refresh(); 56 ControlPath.Fwd("DetailsContent").Scope.SetParam("VideoID", videoID); 57 } ... 160 private void ROOT_DataBind() 161 { 162 ControlPath.Fwd("DetailsContent").Scope.RenderType = ScopeRenderType.Empty; 163 164 CurrentPath.Scope.Replace("{DetailsContent_ScopeID}", CurrentPath.Fwd("DetailsContent").Scope.ScopeClientID); 165 CurrentPath.Scope.Replace("{CommentsContent_ScopeID}", CurrentPath.Fwd("DetailsContent", "CommentsContent").Scope.ScopeClientID); 166 CurrentPath.Scope.Replace("{AddCommentScreen_ScopeID}", CurrentPath.Fwd("DetailsContent", "AddCommentScreen").Scope.ScopeClientID); 167 CurrentPath.Scope.Replace("{ErrorDisplay_ScopeID}", CurrentPath.Fwd("DetailsContent", "AddCommentScreen", "ErrorDisplay").Scope.ScopeClientID); 168 } 169 170 private void DetailsContent_DataBind() 171 { 172 string videoID = CurrentPath.Scope.Param<string>("VideoID"); 173 174 CurrentPath.Fwd("CommentsContent").Scope.RenderType = ScopeRenderType.Empty; 175 CurrentPath.Fwd("AddCommentScreen").Scope.RenderType = ScopeRenderType.Empty; Sometimes ability to set scope parameters is not enough and we wish to call an actual method on the controller to execute certain activities. This feature was added to a new version of the framework. Listing 13 shows how UpdatePagerValues(..) method is registered for PagerController class. In the future I may come up with something more intelligent, but in the current version, a valid method has to take single object parameter and return object result. On line 110 we have the UpdatePagerValues(..) private method. It's not a problem that there is only one parameter allowed, because I can always pass a JSON object graph and get separate values from it. On line 25 the method handler is registered so that it becomes callable from other controllers. UpdatePagerValues(..) 18 public override void SetupModel(ControllerModelBuilder model) 19 { 20 model.SetDataBind(new DataBindHandler(ROOT_DataBind)); 21 22 model.HandleAction("NextPage", new ActionHandler(Action_NextPage)); 23 model.HandleAction("PrevPage", new ActionHandler(Action_PrevPage)); 24 25 model.RegisterMethod("UpdatePagerValues", new MethodHandler(UpdatePagerValues)); 26 } ... 110 private object UpdatePagerValues(object jsonData) 111 { 112 int startItemIdx, pageSize, itemTotalCount; 113 if (DaSTUtils.HasValue("StartItemIdx", jsonData)) startItemIdx = (int)DaSTUtils.GetValue("StartItemIdx", jsonData); 114 else startItemIdx = ControlPath.Scope.Param<int>("StartItemIdx", 0); 115 if (DaSTUtils.HasValue("PageSize", jsonData)) pageSize = (int)DaSTUtils.GetValue("PageSize", jsonData); 116 else pageSize = ControlPath.Scope.Param<int>("PageSize", 1); 117 if (DaSTUtils.HasValue("ItemTotalCount", jsonData)) itemTotalCount = (int)DaSTUtils.GetValue("ItemTotalCount", jsonData); 118 else itemTotalCount = ControlPath.Scope.Param<int>("ItemTotalCount", 0); 119 120 startItemIdx = Math.Min(startItemIdx, itemTotalCount - 1); 121 startItemIdx = ((int)(startItemIdx / pageSize)) * pageSize; 122 123 // set recalculated values 124 ControlPath.Scope.SetParam("StartItemIdx", startItemIdx); 125 ControlPath.Scope.SetParam("PageSize", pageSize); 126 ControlPath.Scope.SetParam("ItemTotalCount", itemTotalCount); 127 128 return null; 129 } Next, Listing 14 shows how the method is invoked from an action handler of VideoLibraryController. On line 77 we, first, point to the PlaylistPager scope which has a PagerController attached and call Method(..) function (see Fig. 10) to invoke previously registered method by name. Notice how I pass the generic object as method parameter. VideoLibraryController Method(..) 73 private void VideoItem_PlaylistUpdated(ActionArgs args) 74 { 75 // pass total items count to parent scope 76 int itemTotalCount = DataLayer.GetPlayItemCount(); 77 ControlPath.Fwd("PlaylistPager").Scope.Method( 78 "UpdatePagerValues", new { ItemTotalCount = itemTotalCount }); 79 80 ControlPath.Fwd("PlaylistHeader").Scope.Refresh(); 81 ControlPath.Fwd("PlaylistPager").Scope.Refresh(); 82 ControlPath.Fwd("PlaylistRepeater").Scope.Refresh(); 83 84 ControlPath.Fwd("VideoItemRepeater").Scope.Refresh(); 85 } The first question that rises here is why do we use all this method registering technique and dont just expose a public interface on the controller and call functions directly? Well, this should never be done in DaST, because, recall, that there is always a single instance of the controller per data scope which is reused for all repeated scope instances. So, calling controller methods through registration mechanism we simply allow the system to maintain the right context on the target controller instance. This is one of my favourite features in the new DaST framework. So far we modified scope content only by replacing placeholders with real values. If we needed to hide or show some areas depending on certain condition, we could enclose these areas into actual scopes and use RenderType property for hiding and showing these scopes. But the problem is that we might need multiple conditional areas and creating separate scopes for each of them would become messy in the template and would flood the back-end controller with tons of unwanted trivial code for hiding, showing, and refreshing these data scopes. And the solution here is to allow direct scope markup manipulation which beautifully complements already existing placeholder replacements. First manipulation that I've added is ShowConditionArea(..) function (see Fig. 10) to show or hide a part of the scope markup. ShowConditionArea(..) For example, ReviewsInfo scope (see Fig. 5) is responsible for the text displayed in the title of the second tab of the details dialog (see Fig. 2). When there are comments for the current video, the text should say "XX user review(s)". If there are no comments, the text will be "0 user reviews(s)". But what if I wish to display more user friendly message instead, something like "No user reviews yet"? Now the answer is simple - use the conditional area! Listing 15 shows part of the template with ReviewsInfo scope. To create a conditional area, markup must be enclosed between <!--showfrom:condition_name--> and <!--showstop:condition_name-->. This special format is recognized by the system during rendering and processed accordingly. On Listing 15 we have 2 conditional areas with conditions comm-empty:yes and comm-empty:no meaning that comments are empty and not empty respectively. <!--showfrom:condition_name--> <!--showstop:condition_name--> comm-empty:yes comm-empty:no 4 <div class="screenContent nested0" scope="DetailsContent"> 5 <div id="tabs"> 6 <ul> 7 <li><a href="#tabs-1">Video Details</a></li> 8 <li> 9 <a href="#tabs-2"><span> 10 <div style="display: inline;" scope="ReviewsInfo"> 11 <!--showfrom:comm-empty:yes--> 12 No user reviews yet 13 <!--showstop:comm-empty:yes--> 14 <!--showfrom:comm-empty:no--> 15 {CommCount} user review(s) 16 <!--showstop:comm-empty:no--> 17 </div></span> 18 </a> 19 </li> 20 </ul> After template is ready, we just need to call ShowConditionArea(..) on the ReviewsInfo scope to show or hide areas depending on the condition. Look how this is done at lines 200-201 in the code listing on Listing 9. On line 200 we instruct the rendering engine to show comm-empty:yes area only when commCount <= 0 i.e. when there are no comments. Now imagine how flexible your UI can be having this small tool. You can have multiple conditional areas, nest them into each other for conditional AND, or put them beside each other for conditional OR! Just like placeholder replacements, this manipulation can be applied to repeated content. Also remember, that DaST applies template transformations in the same order they were called in the controller class. I.e. if you first add some placeholder replacements and then apply conditional areas, the order of transformations will be kept during rendering. Using this amazing tool we must keep in mind that conditional areas, obviously, cannot have nested data scopes. In the next version of the framework I plan to add more useful direct template transformations. commCount <= 0 I've added DaSTUtils class containing a set of utility functions simplifying some common programming tasks. This utility was used in listing on Listing 13 to retrieve values from generic object passed as a parameter to UpdatePagerValues(..) function. DaSTUtils class diagram is shown on Fig. 16. DaSTUtils Fig. 16: DaSTUtils class. Brief summary of the functions is below: GetValue HasValue ParseJSON Although, current version of the DaST Rendering Engine is still Beta, it's pretty stable and you can start playing with it and using it in your projects (obvioulsly, no warranty -- see copyright). I can't promise anything about official documentation -- most likely we will have to wait for several months. Overall architecture of the platform is complete and I dont expect any major design changes; however, I'll be refactoring certain parts of the framework and adding more features to it. Most significant DaST developments that will take place in the near future are summarized below. First thing needed is clean and uniform exceptions handling with meaningful messages to help finding a problem. I'll create a new exception type thrown for all developer faults. We also need some way to view model scope tree information at any time. This is very useful for troubleshooting and testing. By design, the scope tree data structure is not exposed to outside and this is not going to change, but I'll add something like ToXml(..) method or similar so that the developer will always be able to see how his changes impact the internal data structures. ToXml(..) In addition to placeholder replacements and conditional areas I plan to add the ability to repeat parts of the resulting fragment. This means that right inside the data scope we will be able to create repeaters and mix them with conditional areas. This feature is extremely important and useful, because we might not want to create separate data scopes for repeaters and grids. I'm sure the developers will really appreciate outstanding flexibility allowed by direct template manipulation in DaST applications. I was planning to do this for the current version, but simply forgot. It happens Like standard Forms allow parametrizing controls by specifying their properties right inside the ASPX file, DaST framework will allow parametrizing data scopes. Inside the template you'll specify scope DIV tag with a set of attributes. All atributes starting from underscore "_" will become scope parameters and will be available to you through the scope instance. Underscore is needed so that scope params do not overlap with standard HTML attributes. I have to check everything first, but it seems to me that there is no problem to allow scope containers in the templates to be not just DIV tags, but all suitable container tags i.e. those that have innerHtml property. This is needed, because, some apps have to have strict W3C compliance meaning that, for example, DIVs cannot be put inside SPANs which creates certain limitations for placing DIV scopes in the templates. Allowing data scopes to use various containers solve this problem completely. innerHtml This, I think, is the most significant change that will involve major development. Current partial update implementation in DaST Rendering Engine is totally based on the standard ASP.NET Ajax Library. The implementation itself is very simple, partial update engine is quite stable, and I was able to merge DaST partial updates into the standard AJAX in a very elegant way, which sounds pretty good. The only problem is that Microsoft's client AJAX Library is huge and 90% of its code becomes useless if your application uses DaST framework. So, my opinion is that in a good production version such overhead is unacceptable and must be eliminated. This basically means that in the future the entire AJAX library will have to be rewritten to suite the needs of DaST developers. The solution that seems attractive to me is to use jQuery Ajax implementaion, but I'm not sure that this is the best solution. I might also end up with clear JavaScript implementation without any 3rd party libraries. And this is it. I invite everyone to visit DaST dev site frequently and watch for news and framework updates. We're still setting up an open-source project environment and I'll post the news about it whenever anything is ready. I apologize for the delays -- I was really busy during last several months with new interesting projects on my primary job. But since all architectural work is complete, from now on I'll be updating the framework very frequenly adding more features to it. The official release of the DaST Rendering Engine will be in a couple of months, but the current Beta version is fully functional and stable to be used in your projects. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) <ul class="productlist"> <% foreach (var product in ViewData) { %> <li> <img src="/Content/Images/<%=product.ProductID%>.jpg" alt="<%=product.ProductName %>" /> <a href="/Products/Detail/<%=product.ProductID %>"> <%=product.ProductName %> </a> Price: <%=String.Format("{0:C2}", product.UnitPrice)%> <span class="editlink""> (<%= Html.ActionLink("Edit", new { Action="Edit", ID=product.ProductID })%>) </span> </li> <% } %> </ul> [2{}]<+PageSizeRepeater>[2{}]<-1><+SiteThemeRepeater>[2{}]<-1><+PlaylistHeader>[2{}]<-1><+PlaylistPager>[56{"StartItemIdx":"0","PageSize":"5","ItemTotalCount":"3"}]<-1><+PlaylistRepeater>[2{}]<+VideoItem>[293{"ItemIndex":"0","VideoItemObject":"{\"ID\":\"VIDEO-4\",\"Name\":\"In lorem. Donec elementum,\",\"Category\":\"cyan\",\"Description\":\"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec\",\"CommCount\":4,\"Rating\":3.25}"}]<.1-1>.................... .... $(".addToPlayList").live("click", function() { AlterPlayList("add", this.videoId); $("." + this.videoId).removeClass("addToPlayList").addClass("removeFromPlayList").addClass("ui-state-highlight"); $("." + this.videoId).find("span").removeClass("ui-icon-circle-plus").addClass("ui-icon-circle-minus"); $("." + this.videoId).attr("title", "Remove from play list"); }); .... onchange rgubarenko wrote:If this is absolutely a must to use actual code rgubarenko wrote:I also attached source code to the article so everyone can just browse it using "Browse Code" feature. General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/176421/DaST-Concept-A-simpler-smarter-and-much-more-power?msg=3844494
CC-MAIN-2015-11
refinedweb
7,133
56.15
Revision history for Catalyst-Controller-POD 1.0.0 2011-01-25 - Using Google Prettify for Source Code Highlighting - Updated ExtJS to 3.3.1 - using Dist::Zilla 0.02008 2010-06-24 - using Static::Simple to deliver static files - Cleanup 0.02007 2010-03-07 - Added additional configuration options: expanded_module_tree, home_tab_content, initial_module, show_home_tab (Tristan Pratt) - Added permalinks (Tristan Pratt) - Update to ExtJS 3.1.1 (fixes memory leaks in browsers) 0.02006 2009-11-20 - fixed another warning (#51681) 0.02005 2009-11-20 - use next instead of NEXT - Added "not found" page for namespaces like DBIx 0.02004 2009-05-04 - JS cleanups - filtered results do not expand by default - moved to git repository 0.02003 2009-05-03 - Works with Catalyst 5.8 (reported by T. Hosaka) 0.02002 2008-08-16 - requires parent - ext cleanup 0.02001 2008-08-09 - removed Pod::TOC dependency 0.01_03 2008-07-30 - A lot of new feature - added some basic tests, more to come 0.01_01 Date/time First version, released on an unsuspecting world.
https://metacpan.org/changes/distribution/Catalyst-Controller-POD
CC-MAIN-2016-50
refinedweb
176
62.44
#include <rte_bbdev_op.h> Operation structure for LDPC decode. An operation can be performed on one CB at a time "CB-mode". An operation can also be performed on one or multiple CBs that logically belong to a TB "TB-mode" (Currently not supported). The input encoded CB data is the Virtual Circular Buffer data stream. Each byte in the input circular buffer is the LLR value of each bit of the original CB. Hard output is a mandatory capability that all BBDEV PMDs support. This is the decoded CBs (CRC24A/B is the last 24-bit in each decoded CB). Soft output is an optional capability for BBDEV PMDs. If supported, an LLR rate matched output is computed in the soft_output buffer structure. These are A Posteriori Probabilities (APP) LLR samples for coded bits. HARQ combined output is an optional capability for BBDEV PMDs. If supported, a LLR output is streamed to the harq_combined_output buffer. HARQ combined input is an optional capability for BBDEV PMDs. If supported, a LLR input is streamed from the harq_combined_input buffer. The output mbuf data structure is expected to be allocated by the application with enough room for the output data. Definition at line 431 of file rte_bbdev_op.h. The Virtual Circular Buffer for this code block, one LLR per bit of the original CB. Definition at line 435 of file rte_bbdev_op.h. The hard decisions buffer for the decoded output, size K for each CB Definition at line 439 of file rte_bbdev_op.h. The soft LLR output LLR stream buffer - optional Definition at line 441 of file rte_bbdev_op.h. The HARQ combined LLR stream input buffer - optional Definition at line 443 of file rte_bbdev_op.h. The HARQ combined LLR stream output buffer - optional Definition at line 445 of file rte_bbdev_op.h. Flags from rte_bbdev_op_ldpcdec_flag_bitmasks Definition at line 448 of file rte_bbdev_op.h. Rate matching redundancy version [3GPP TS38.212, section 5.4.2.1] Definition at line 453 of file rte_bbdev_op.h. The maximum number of iterations to perform in decoding CB in this operation - input Definition at line 457 of file rte_bbdev_op.h. The number of iterations that were performed in decoding CB in this decode operation - output Definition at line 461 of file rte_bbdev_op.h. 1: LDPC Base graph 1, 2: LDPC Base graph 2. [3GPP TS38.212, section 5.2.2] Definition at line 465 of file rte_bbdev_op.h. Zc, LDPC lifting size. [3GPP TS38.212, section 5.2.2] Definition at line 469 of file rte_bbdev_op.h. Ncb, length of the circular buffer in bits. [3GPP TS38.212, section 5.4.2.1] Definition at line 473 of file rte_bbdev_op.h. Qm, modulation order {1,2,4,6,8}. [3GPP TS38.212, section 5.4.2.2] Definition at line 477 of file rte_bbdev_op.h. Number of Filler bits, n_filler = K – K’ [3GPP TS38.212 section 5.2.2] Definition at line 481 of file rte_bbdev_op.h. [0 - TB : 1 - CB] Definition at line 483 of file rte_bbdev_op.h. Struct which stores Code Block specific parameters Definition at line 486 of file rte_bbdev_op.h. Struct which stores Transport Block specific parameters Definition at line 488 of file rte_bbdev_op.h.
https://doc.dpdk.org/api-19.11/structrte__bbdev__op__ldpc__dec.html
CC-MAIN-2022-27
refinedweb
529
52.36
Creating a DLL using Visual C# is piece of cake. Believe me its much easier than VC++. I have divided this tutorial in two parts. 1. Building a Class Library, and 2. Building a client application to test the DLL. Part 1: Creating a Class Library (DLL) Create an Empty Class Library Project Select File->New->Project->Visual C# Projects->Class Library. Select your project name and appropriate directory using Browse button and click OK. See Figure 1. Figure 1. Project and Its files The Solution Explorer adds two C# classes to your project. First is AssemblyInfo.cs and second is Class1.cs. We don't care about AssemblyInfo. We will be concentrating on Class1.cs. See Figure 2. Figure 2. The mcMath Namespace When you double click on Class1.cs, you see a namespace mcMath. We will be referencing this namespace in our clients to access this class library. using Now build this project to make sure every thing is going OK. After building this project, you will see mcMath.dll in your project's bin/debug directory. Adding Methods Open ClassView from your View menu. Right now it displays only Class1 with no methods and properties. Lets add one method and one property. See Figure 3. Figure 3. Right click on Class1->Add->Add Method... See Figure 4. Figure 4. C# Method Wizard pops up. Add your method name, access type, return type, parameters, and even comments. Use Add and Remove buttons to add and remove parameters from the parameter list respectively. I add one test method called mcTestMethod with no parameters. See Figure 5. Figure 5. I am adding one more method long Add( long val1, long val2 ). This method adds two numbers and returns the sum. Click Finish button when you're done. See Figure 6. Figure 6. The above action adds two method to the class and methods look like following listing: Adding Properties Open C# Property Wizard in same manner as you did in the case of method and add a property to your class. See Figure 7. Figure 7. This action launches C# Property Wizard. Here you can type your property name, type and access. You also have options to choose from get only, set only or get and set both. You can even select if a property is static or virtual. I add a property Extra with public access and bool type and get/set option set. See Figure 8. Figure 8. After adding a method and a property, our class looks like Figure 9 in Class View after expanding the class node. Figure 9. If you look your Class1 class carefully, Wizards have added two functions to your class. /// <summary> /// //This is a test property /// </summary> public bool Extra { get { return true; } set { } } Adding Code to the Class Add this code ( bold ) to the methods and property now. And now I want to change my Class1 to mcMathComp because Class1 is quite confusing and it will create problem when you will use this class in a client application. Make sure you change class name and its constructor both. Note: I'm not adding any code to mcTestMethod, You can add any thing if you want. Now build the DLL and see bin\debug directory of your project. You will see your DLL. Piece of cake? Huh? :). Part 2: Building a Client Application Calling methods and properties of a DLL from a C# client is also an easy task. Just follow these few simple steps and see how easy is to create and use a DLL in C#. Create a Console Application Select File->New->Project->Visual C# Projects->Console Application. I will test my DLL from this console application. See Figure 10. Figure 10. Add Reference of the Namespace Now next step is to add reference to the library. You can use Add Reference menu option to add a reference. Go to Project->Add reference. See Figure 11. Figure 11. Now on this page, click Browse button to browse your library. See Figure 12. Figure 12. Browse for your DLL, which we created in part 1 of this tutorial and click Ok. See Figure 13. Figure 13. Add Reference Wizard will add reference of your library to the current project. See Figure 14. Figure 14. After adding reference to mcMath library, you can see it as an available namespace references. See Figure 15. Figure 15. Call mcMath Namespace, Create Object of mcMathComp and call its methods and properties. You are only one step away to call methods and properties of your component. You follow these steps: 1. Use namespace Add using mcMath in the beginning for your project. 2. Create an Object of mcMathComp mcMathComp cls = new mcMathComp(); 3. Call Methods and Properties Now you can call the mcMathComp class method and properties as you can see I call Add method and return result in lRes and print out result on the console. The entire project is listed in the following Listing: Now build and run the project. The output looks like Figure 16. Figure.
http://www.c-sharpcorner.com/UploadFile/mahesh/dll12222005064058AM/dll.aspx
CC-MAIN-2015-18
refinedweb
844
77.53
- RK DocFarren + 0 comments Try this reasoning: I (PersonA) am one out of N people, so I need to shake hands with (N-1) people. This reasoning holds true for all of the N people, so the number of hand shakes is N * (N-1). Now that PersonA and PersonB shook hands, PersonB and PersonA (same people, but from PersonB's perspective) don't need to shake anymore. So we initially counted each combination twice. Therefore, the number of hand shakes is nShakes = (N * (N-1)) / 2 PPMBrouwers + 1 comment In an example of 4 people: The first person can shake hands with all the others (N-1)=3. The seconds person can shake hands with all the others, without 1: (N-1-1)=2, third = (N-1-1-1)=1, fourth = (N-1-1-1-1)=0. Hence we get exactly range(4) [at least in Python]. So if we do sum(range(N)) 0+1+2+3 == 6, we get the total number of handshakes. - SB stephen_berks056 + 0 comments That's brief, but it runs in linear time. You can do it in constant time with (N-1) * N // 2. - AF afando + 1 comment It is a standard combinatorics problem. You need to select a pair of people from N people. How many different pairs are there? N choose 2. N! / ((N-2)! * 2!) which simplifies to (N * (N-1)) / 2. amani_kilumanga + 1 comment I believe one of your exclamation points is misplaced. N! / (R!(N - R)!) = N! / (2!(N - 2)!) - A alayek + 1 comment I have a qualm with the sample test cases provided. Don't use 0 or 1, because most of the times they represent some boundary case or special case. Maybe you can include one example with a bigger number, like 4 or 5? - A aryaman_arora201 + 0 comments If you use the most efficient solution, 0 and 1 are not boundary cases (hint hint) Shadow_3115 + 1 comment int main(){ int T; cin >> T; for(int a0 = 0; a0 < T; a0++){ int N; cin >> N; int x=N*N/2; int y=N/2; cout<<(x-y)<<"\n"; } return 0; } - VS vikramsaraf3000 + 1 comment if you change to this then it will become shorter int x=(N-1)*N/2; cout<<(x)<<"\n"; - J jeetendra_sobre + 0 comments what about N=1? zac_c_petit + 2 comments You can generalize this using Binomial Coefficients - SS zac_c_petit + 1 comment[deleted] zac_c_petit + 0 comments No idea what you mean. This approached worked fine in my C# submission for 0 < N < 10^6 with each result in 20ms or less. - A aryaman_arora201 + 0 comments asbear + 2 comments This is adding from 1 to P-1 when P is number of person. so if you just use ((P-1)+1)*(P-1)/2 when P > 1 and 0 when P = 1 it will work. - DZ EvilCartman + 2 comments some how i've ended with (P * P - P) / 2 formula ;) developeransh + 1 comment can u solve this withouth formula..as i have another trick to do it withouth formula asbear + 2 comments it's not difficult even without the formula but the complexity would be too bad. what's the complexity of yours? trendsetter37 + 0 comments You can do it in O(n) def hs(num): total = 0 for i in range(num, 0, -1): total += i-1 return total Am I right? swhitlock410 + 0 comments @EvilCartman, you are still correct. (P * (P - 1))/2 = (P * P - P)/ 2 = (P^2 - P) /2 ^ is my way of representing exponents. - N Kiuru + 4 comments This probably soudns like a stupid question to you but how do you figure out such formulas? I solved this with a loop which is fine if the numbers aren't too big. In school I was neither very good nor very bad at maths. Is there some kind of "strategy" to find them? - CB ChristopheB + 0 comments The strategy that I used was that I visualized the problem as a square grid in which both the columns and rows represent the different persons. It is assumed that a person does not shake hands with him or herself so that means the diagonal is empty. If person 1 shakes hands with person 2, I can place a mark on the first row, second column. If person 2 shakes hands with person 3 I place a mark on the second row, third colummn and so on. In the end you will see that you have marked all elements of the grid above the diagonal. Unfortunately, I think that at this point you do need some background in mathematics to quickly see that there is a formula that will give you the number of these elements. If not, you can always try to get the solution for small numbers of N and hopefully discover a relationship before N gets too big :) mahiruinamichan + 0 comments - MP modyali_fox + 0 comments return n / 2; - D www_dbasak + 0 comments include include using namespace std; int main() { long long int t,n,a; cin>>t; while(t--) { cin>>n; a=n/2; cout< } this code gave the wrong answer in test case 11. how can i fix this? Sort 92 Discussions, By: Please Login in order to post a comment
https://www.hackerrank.com/challenges/handshake/forum
CC-MAIN-2018-26
refinedweb
873
77.98
/* * <ctype.h> #include <string.h> #include "curses.h" /* * overwrite -- * Writes win1 on win2 destructively. */ int overwrite(win1, win2) register WINDOW *win1, *win2; { register int x, y, endy, endx, starty, startx; #ifdef DEBUG __CTRACE("overwrite: (%0.2o, %0.2o);\n", win1, win2); #endif starty = max(win1->begy, win2->begy); startx = max(win1->begx, win2->begx); endy = min(win1->maxy + win1->begy, win2->maxy + win2->begx); endx = min(win1->maxx + win1->begx, win2->maxx + win2->begx); if (starty >= endy || startx >= endx) return (OK); #ifdef DEBUG __CTRACE("overwrite: from (%d, %d) to (%d, %d)\n", starty, startx, endy, endx); #endif x = endx - startx; for (y = starty; y < endy; y++) { (void)memcpy( &win2->lines[y - win2->begy]->line[startx - win2->begx], &win1->lines[y - win1->begy]->line[startx - win1->begx], x * __LDATASIZE); __touchline(win2, y, startx - win2->begx, endx - win2->begx, 0); } return (OK); }
http://opensource.apple.com//source/Libcurses/Libcurses-24/overwrite.c
CC-MAIN-2016-44
refinedweb
140
51.58
6.1. Numpy and Arrays¶ This section provides a very cursory introduction to Numpy, enough to set up some of the basic concepts used in pandas. Numpy is a vast toolbox with a host of powerful mathematical features. In this section we have the modest goal of introducing arrays and array operations, trying to present some basic methods for creating and accessing arrays. For more advanced students a very useful introduction to the capabilities of numpy is provided in Nicholas Rougier’s github tutorial, which mixes code and prose. For students already familiar with Matlab, there are a number of strong similarities, but there are also some important differences. This article Numpy for Matlab users does a good explaining the relationship. The gist of the discussion is that it is possible to do things the Matlab way using the Python matrix class, but there is a price to be paid, especially when using a non standard Python module (third party software, often indispensable), and it may be worth it to do things the Python way (using arrays). 6.1.1. Making ranges¶ We first introduce the range function, which is useful on its own as a Python programming tool; its relevance here is its strong connection with list and array splices. x = range(15) x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] range(1,5) [1, 2, 3, 4] range(5,100) [5, 6, 7, 8, 9, 10, .... 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] range(5,100,5) This time we create a sequence that counts up from 5 by 5. The third argument specifies the size of the counting steps [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] The counting steps may also be negative, in which case we count down from the index specified by the first argument, up to but not including the second index. So in the case the second argument must be less than the first. range(10,0,-1) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] To get to 0 the last argument must be one further counting down, that is, -1. range(10,-1,-1) Which gives: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] The result of range is always a list. type(x) list The way range works is the same as the way splices work. First, second, and third arguments of a splice all do the same things as the corresponding arguments of splices. L = range(10,-1,-1) L[2:8] [8, 7, 6, 5, 4, 3] In particular splices also take a third “step” argument. L[8:2:-1] gives [2, 3, 4, 5, 6, 7] >>> L [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] So an efficient Pythonic way to reverse a list is: >>> L[::-1] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 6.1.2. Numpy arrays¶ We import the numpy module to demonstrate the use of arrays: >>> import numpy as np Arrays are columns of numbers. Actually they dont have to be numbers; they can also be strings; but all the items are generally of the same data type. Conceptually, there is nothing more to the idea of arrays than there is to the idea of lists. They are data structures containing items in sequence, like the following: >>> x = np.array([1.0,2.,3.1]) Like lists you can access them by index: >>> x[2] 3.1 So why do we need arrays in addition to lists? One reasin reason is space. We can save a great deal of space storing sequences if we know that all the items in the sequence are of the same data type. Another reason is time; mathematical operations can be made much more efficient if they are performed on sequences of uniform type. So the one-type restriction on arrays is quite helpful, in light of the fact that there are people out there doing massive amounts of number crunching involving very large arrays. A large part of why arrays provide such massive gains in efficiency is vectorization of operations. The fancy mathematical term for a column of numbers is a vector. To vectorize an operation means to generalize it from an operation on numbers to an operation on vectors. When you load numpy, vectorized versions of all the basic arithmetic operations are defined. For example, consider addition: >>> x = np.array([1.0,2.,3.1]) >>> y = np.array([-1.0,-2.,2.9]) >>> x + y array([ 0., 0., 6.]) The result of adding array x and array y is a new array whose $i$th element is the sum of $x[i]$ and $y[i]$. Similar generalizations apply to all the 2-place arithmetic operations. So why should ordinary working data scientists care about arrays? One answer of course is that efficiency usually ends up mattering, even when you think it won’t. But there is a simpler answer that has immediate consequences even for beginners. Vectorization provides us with a lot of programming conveniences that make for clearer, more concise code. We return to vectorization and the conveniences it offers below and in the visualization chapter. For now let us consider some more methods of making arrays. The simplest way to create an array is just to pass a list to the np.array function, as we did in our first example above. >>> b = np.array([6, 7, 8]) >>> b array([6 7 8]) >>> type(b) <type 'numpy.ndarray'> Then there is arange, a close cousin of range. import numpy as np a = np.arange(15) a Instead of returning a list, arange returns an array. Another example with arange, using integers, and a step argument. >>> arange( 10, 30, 5 ) array([10, 15, 20, 25]) An important feature of arange, distinguishing it from range, is that none of the arguments, including the step argument, need to be integers: >>> x = np.arange(0, 10, 0.01), .... 9.54, 9.55, 9.56, 9.57, 9.58, 9.59, 9.6 , 9.61, 9.62, 9.63, 9.64, 9.65, 9.66, 9.67, 9.68, 9.69, 9.7 , 9.71, 9.72, 9.73, 9.74, 9.75, 9.76, 9.77, 9.78, 9.79, 9.8 , 9.81, 9.82, 9.83, 9.84, 9.85, 9.86, 9.87, 9.88, 9.89, 9.9 , 9.91, 9.92, 9.93, 9.94, 9.95, 9.96, 9.97, 9.98, 9.99]) Some other differences between arrays and lists are demonstrated with the folowing attributes. >>> a.shape (3, 5) >>> a.ndim 2 >>> a.dtype.name int64 >>> a.itemsize 8 >>> a.size 15 >>> type(a) <type 'numpy.ndarray'> >>> np.ndarray 6.1.3. Two-dimensional arrays¶ The real power of arrays emerges when we look at more complicated examples representing tabular information. Lists are always 1-dimensional; they are simple sequences, with only one direction to go when looking for the next item. Arrays can have more than one dimension. We start with a simple sequence of length 15; we now reshape it into a 3 by 5 table (3 rows, 5 columns): a = np.arange(15).reshape(3, 5) print a b = np.arange(15).reshape(5, 3) a = np.arange(15).reshape(3, 5) print b print b.transpose() This results in [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14]] [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11] [12 13 14]] [[ 0 3 6 9 12] [ 1 4 7 10 13] [ 2 5 8 11 14]] To create a table ( or 2-dimensional array), we pass np.array a list of lists. Each of the embedded lists specifies one row of the table: >>> b = np.array( [ (1.5,2,3), (4,5,6) ] ) >>> b array([[ 1.5, 2. , 3. ], [ 4. , 5. , 6. ]]) An important feature of arrays, distinguishing them from lists, is that all the data items is generally of the same data type. The data type is often deduced from the arguments passed in, or it can overtly be specified with the optional dtype argument, which must specify a legal numpy data type. That includes all the basic Python number types. >>> c = np.array( [ [1,2], [3,4] ], dtype=complex ) >>> c array([[ 1.+0.j, 2.+0.j], [ 3.+0.j, 4.+0.j]]) Two other important ways of creating arrays are the ones and zeros functions. We create a 3 by 4 array containing only the float 0. >>> np.zeros( (3,4) ) array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]) We create a 3 by 4 array containing all 1’s. >>> A =np.ones( (3,4)) >>> np.zeros( (3,4) ) array([[ 1., 1., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.]]) 6.1.4. Indexing into arrays¶ We create an array using arange and an elementwise application of cubing, to get a array with the first ten perfect cubes (starting from 0). >>> a = np.arange(10)**3 >>> a array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]) This is a one-dimensional array whose data can be accessed just like a list: >>> a[2] 8 >>> a[2:5] array([ 8, 27, 64]) Note that the way this array was created is peculiar to arrays. You “cube” an array, but you can’t cube a list: >>> L = range(10) >>> L**3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int' We can also make assignments to array positions, just as we do with lists. In this example, we use a splice with a step to affect to affect every other position in a slice. >>> a[:6:2] = -1000 # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000 >>> a array([-1000, 1, -1000, 27, -1000, 125, 216, 343, 512, 729]) array([ 729, 512, 343, 216, 125, -1000, 27, -1000, 1, -1000]) Again what is happening here is peculiar to arrays. You can’t assign a non sequence in a splice assignment to a list: >>> L[::2] = 3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must assign iterable to extended slice One can use loop through arrays, as one loops through lists: for i in a: print i**(1/3.), 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 But this is often unnecessary. One can often perform mathematical operations on arrays as if they were numbers: a ** (1/3.,) 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 In fact, performing the arithmetic operation directly on the array is much more efficient than using the loop. We discuss some of the possibilities opened up by this fact in the next section. 6.1.5. Efficient array creation¶ The following way of making a 2D array is very general and much faster than using a loop. Just write a function of two arguments which for any i and j returns the value you want to place at (i,j) in the array. You can also specify a type for the elements of the array, using a known Python type or special numpy types for numbers. For example, numpy has the following types for integers, providing data elements of different memory sizes: np.int,np.int16,np.int32,np.int64 import numpy as np def f(i,j): return 10*i+j # make a 5x4 array [20 elements] `b` using the function `f` # where b[i,j] = f(i,j) b = np.fromfunction(f,(5,4),dtype=int) b array([[ 0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]]) print b[2,3] print b[2,:] 23 [20 21 22]])
https://gawron.sdsu.edu/python_for_ss/course_core/book_draft/data/arrays.html
CC-MAIN-2018-09
refinedweb
2,025
69.31
Compiling Java classes, building jar files and running the code Compile and run single class If you program consists of one single class, compile it: $ javac Program.java Run main method: $ java -cp . Program or even shorter: $ java Program Compiling and building jar Build following directory structure: + - HelloWorld (project name - base directory (./)) + - src (source files) + - abcd (package name - .java files) + - build + - classes (compiled files - .class files) This is a test class: package abcd; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello Java world."); } } Save this file in ./src/abcd as 'HelloWorld.java'. Compiling Now you can compile the java file: $ javac -sourcepath ./src/ -d ./build/classes/ ./src/abcd/HelloWorld.java This should create 'HelloWorld.class' file in ./build/classes directory Running Run compiled class: $ java -cp ./build/classes/ abcd.HelloWorld This should result in displaying a message in console window: Hello Java world. Building jar Manifest Before building jar, you must create Manifest file. This file tells the jar file in which class the main method is. On unix you can simply create manifest file like this: $ echo Main-Class: abcd.HelloWorld>myManifest This creates new document called 'myManifest' with following line Main-Class: abcd.HelloWorld Build jar $ jar cfm ./build/jar/HelloWorld.jar myManifest -C ./build/classes/ . Don't forget white_space and . at the end of line. This means all the class files inside ./build/classes Run jar When jar is successfully created, you can run it with: $ java -jar ./build/jar/HelloWorld.jar
http://www.matjazcerkvenik.si/developer/java-compiling.php
CC-MAIN-2019-09
refinedweb
250
62.14
I am trying to create a program that has a class with a method that accepts a charge account number as an argument. Then the method should determine if the account number is valid by comparing it to the list of accounts in a text file (Accounts.txt). Then method should return a boolean value of true if the account is found. The method should use sequential search of ArrayList to find the target account. I am instructed to use the following as the header to the method : public static boolean isValid(ArrayList AccountList, String target) and the logic should follow as : Read the Accounts.txt file into an ArrayList object. Loop through the ArrayList and display all accounts. Prompt user for target Account to search for. Display Account number Valid or not Valid message. Test for both conditions. I have completed a large portion of the code but keep getting errors no matter what I edit. This is my first java course and I'm still trying to fully learn how to trace errors and such. Any help will be greatly appreciated. Thanks in advance. Code thus far: (with general comment tags. Errors will be typed in comment tags within brackets. i.e. // [ error message ] ) package accountNumber; import java.util.Scanner; import java.io.*; import java.util.ArrayList; public class AccountNumber{ public static void main(String[] args) throws IOException { ArrayList<String> accountList = new ArrayList<String>(); Scanner keyboard = new Scanner(System.in); System.out.print("Enter the filename: "); String filename = keyboard.nextLine(); File file = new File(filename); Scanner inputFile = new Scanner(file); while (inputFile.hasNext()) { String account = inputFile.nextLine(); accountList.add(account); } inputFile.close(); for (int index = 1; index < accountList.size(); index++) { System.out.println("Index: " + index + " Account: " + accountList.get(index)); } /** [ - Syntax error on token ")", ; expected - Syntax error on token "(", ; expected - Illegal modifier for parameter isValid; only final is permitted - Syntax error on token ",", ; expected - ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized ] */ public static boolean isValid(ArrayList AccountList, String target) { String test = filename; /** [ - The method sequentialSearch(Scanner, String) is undefined for the type AccountNumber - Duplicate local variable target ] */ int target = sequentialSearch(inputFile, filename); if (target == -1) { System.out.println("Invalid account number."); } else { System.out.println("Account number is valid." + (target + 1)); } } /** The sequentialSearch method searches an array for a value. @param array The array to search. @param value The value to search for. @return The subscript of the value if found in the array, otherwise -1. */ **/ [- Syntax error on token ",", ; expected - Syntax error on token ")", delete this token - Duplicate local variable filename - Illegal modifier for parameter sequentialSearch; only final is permitted - Duplicate local variable inputFile - Syntax error on token "(", ; expected ] */ public static int sequentialSearch(int[] inputFile,int filename); { int index; // Loop control variable int element; // Element the value is found at boolean found; // Flag indicating search results // Element 0 is the starting point of the search. index = 0; // Store the default values element and found. element = -1; found = false; // Search the array. while (!found && index <inputFile.length) { if (inputFile[index] == filename) { found = true; } index++; } } } }
https://www.daniweb.com/programming/software-development/threads/234580/search-array-for-account-number
CC-MAIN-2018-13
refinedweb
512
50.53
Troubleshooting The following sections contain workarounds for issues that you might encounter when using Codewind. If you don’t see your issue here, please check our GitHub repository. If you still don’t see your issue, you can open a new issue in the repository. - Installing Codewind - Upgrading Codewind - Creating a project - Importing a project - Understanding Application Metrics - Troubleshooting project application and build statuses - Editing your project - Disabling development on specific projects - Appsody with Codewind - OpenShift Do (odo) with Codewind - OKD and OpenShift - Codewind and Tekton pipelines - OpenAPI tools - Setting Codewind server log levels - Collecting log files and environment data IDE Troubleshooting The following sections contain workarounds for issues that you might encounter when using Codewind in a particular IDE. Installing Codewind Installer fails with mount issues on Windows If you try to install Codewind on Windows 10 and use Docker, you might see the following error: ERROR: for codewind-performance Cannot start service codewind-performance: b"error while creating mount source path '/host_mnt/c/codewind-data': mkdir /host_mnt/c: file exists" ERROR: for codewind-performance Cannot start service codewind-performance: b"error while creating mount source path '/host_mnt/c/codewind-data': mkdir /host_mnt/c: file exists" Encountered errors while bringing up the project. Workaround: Enter the following command and install again: - Enter the docker volume rm -f /host_mnt/ccommand. - Restart Docker and run the installer again. If the command and another installation attempt don’t succeed, complete the following steps instead: - Uninstall Codewind and remove all the images with the docker system prune -acommand. - From the Docker settings dialog box, reset Docker to the factory default to resolve the mount issues. For more information, see this issue about Docker mounts on Windows. Docker Shared Drive not accepting OS credentials for Windows When using OS authentication setups (for example, AzureAD), Docker Shared Drive might not accept your OS credentials. Workaround: Create a new user account. - Navigate to Settings -> Accounts -> Family & other people -> Add someone else to this PC -> I don’t have this person’s sign-in information -> Add a user without a Microsoft account. - Create the new account with the same username but without the prefix (for example, if your AzureAD account is AzureAD/BobSmith, your new local account should be BobSmith). Use the same password as your other account. - Select your new local account and click Change account type. Select the dropdown menu and select Administrator. Share the drive again in Docker. Error appears after installing or updating Codewind After you install or update Codewind, an error might appear when you try to start Codewind. Workaround: Remove the Codewind Docker images with your IDE: - Stop Codewind. - Remove the Codewind Docker images. - In VS Code, use the Remove Codewind Imagescommand. - In Eclipse, use the Uninstallaction. If removing the images with the IDE fails, remove them with the Docker command line instead: - Stop Codewind. - Use docker image lsto identify the Codewind images. - Then, enter docker image rmto remove them. If installing and starting Codewind still fails, you can use Docker system prune: Caution: Docker system prune removes more than just the Codewind Docker images. It can potentially remove all of your images. - Stop Codewind. -. Cannot find Codewind in Marketplace when attempting to install in IntelliJ When attempting to install Codewind in IntelliJ, you cannot locate the Codewind plug-in in Marketplace, and if you verify the custom plug-in repository link, you get a Connection failed error message: This error occurs because the custom plug-in repository link contains an additional space. Workaround: Remove the extra space from the custom plug-in repository link. Without a keychain or keyring, Codewind fails to run certain commands Local and remote Codewind need to use a keychain, also called a keyring, when certain commands are used. The following error messages appear on Linux: dbus: invalid bus address (invalid or unsupported transport) The name org.freedesktop.secrets was not provided by any .service files Workaround: Including compatible keychains Use any keyring compatible with go-keyring, which is what Codewind uses internally. These compatible keychains are included with macOS and Windows 10, and some Linux systems include the gnome-keyring package. If your Linux computer doesn’t have the gnome-keyring package, you can install GNOME/Keyring. Enabling insecure keychain mode If you cannot install a keychain, enable insecure keychain mode. If you enable this mode, your credentials are stored in a JSON text file in the .codewind directory in your user home directory. The credentials are base64 encoded, and anyone who has access to that file can decode the credentials. If you use cwctl directly, use the --insecure-keyring command line argument or set INSECURE_KEYRING=true in the environment. To get the IDE plug-ins to use the insecure keyring, set INSECURE_KEYRING=true in the environment before launching the IDE from that same environment. Operator install failed to connect to remote Codewind instance When installing Codewind remotely, you get a Account is not fully set up error message. Workaround If you have set a temporary password by clicking the Temporary check box to On, log in to Keycloak to set a new one. For more information, see Add a new user to Keycloak. Upgrading Codewind Error upgrading Codewind to the latest When upgrading Codewind from any version older than 0.9 to the latest, you see the following error: ==> Run cwctl --json remove -t 0.8.1 Removing Codewind docker images.. System architecture is: amd64 Host operating system is: darwin Please wait whilst images are removed... .FileNotFoundError: [Errno 2] No such file or directory: '/Users/<username>/.codewind/docker-compose.yaml' {"error":"IMAGE_REMOVE_ERROR","error_description":"exit status 1"} Workaround: 1. Remove the Codewind images by hand. On macOS or Linux, you can remove the images with the following command: $ docker rmi $(docker images | grep eclipse/codewind | awk '{ print $3 }') 2. Remove the Codewind network: $ docker network rm <codewind_network> 3. Go to your IDE and click Start Local Codewind. Codewind starts. 4. If Codewind fails to start, you can use Docker system prune. Caution: Docker system prune removes more than just the Codewind Docker images. It can potentially remove all of your images. -. Creating a project Project creation on macOS fails, and Codewind reports an error If creating a Codewind project on macOS fails, Codewind might report the net/http: TLS handshake timeout error. For a similar issue, see the report Error “net/http: TLS handshake timeout”. Workaround As noted in the report Error “net/http: TLS handshake timeout”, go to Applications>Utilities>Keychain Access and delete from the keychain the certificates that you no longer need. You might notice that some certificates are redundant. Then, restart Codewind. Project creation fails if a persistent volume (PV) is unavailable If you try to create a project on Codewind for Eclipse Che, errors might occur if a PV is unavailable for your cluster. Workaround: Run the kubectl get pv command to check that a PV is available for each project that you want to create. Codewind unable to deploy projects on IBM Cloud Kubernetes Service (IKS) with Kubernetes 1.15 and earlier Codewind cannot deploy Codewind style projects with remote Codewind on IKS and Kubernetes 1.15 and earlier. The projects fail to deploy, and you see the following error: Failed to pull image "<image>": rpc error: code = Unknown desc = failed to pull and unpack image "<image>": failed to unpack image on snapshotter overlayfs: failed to extract layer sha256:<hash>: mount callback failed on /var/lib/containerd/tmpmounts/containerd-mount799987480: archive/tar: invalid tar header: unknown Workaround: Upgrade to the latest version of IKS. IKS clusters that run Kubernetes 1.16 and later run a later version of containerd and are not affected by this issue. Codewind Che extension loses connectivity to the Codewind pod The Codewind Che extension might lose connectivity to the Codewind pod during a Lagom or Swift project build if you have multiple projects in the workspace for each runtime type. When this issue occurs, the project tree says Disconnected. Workaround: Refresh the projects list to have the tree repopulate. If the issue persists, refresh the webpage. Importing a project Imported project never builds or starts To view the status of the imported project, enter the following command: docker logs codewind-pfe Workaround: If you see the following messages, the imported project is likely not a valid Codewind project. build-log requested, no build log found for project <project name> build-log requested, no build log found for project <project name> build-log requested, no build log found for project <project name> build-log requested, no build log found for project <project name> No containerId for running project <project name> Adding an existing Open Liberty project fails to build because of missing files An Open Liberty project fails to build after it is added into Codewind with the Add Existing Project action, and the project fails to build because of missing files. Workaround: Bind the existing project again but this time for the project type, do not accept the detected type, but instead select Other (Codewind Basic Container). Understanding Application Metrics Application Monitoring unavailable after Project Import After importing an application, when you click App Monitor, the dashboard is not displayed and results in a Cannot GET /appmetrics-dash/ error. If this error appears, the application was not created by Codewind or previously had AppMetrics integration. Workaround: Enable AppMetrics for your application. You can enable AppMetrics for Node.js, Swift, and SpringBoot projects. Profiling markers do not appear If you have the Codewind Language Server for Node.js Profiling extension enabled and have run a load test, profiling markers still might not appear. Ensure that your project and load run conform to the following requirements to use profiling: - Your project exists in Theia or VS Code. Profiling is available only in Theia and VS Code. - Your project is a Node.js project that was created through Codewind. - Your project has Run Loadexecuted on it. - The load run successfully completed. Profiling data is written to the load-test/<datestamp>/profiling.jsonfile in your Codewind project only on a successfully completed load run. If the load run was cancelled, it won’t be written to the workspace. - The load run ran for a minimum of 45 seconds to gather enough profiling data to generate the profiling.jsonfile. - If a function runs quickly, in less than 5 milliseconds with the default configuration, then the function might not run during any of the samples, so it might not be included in the profiling data for that load run. - Profiling is not disabled. To enable profiling, access the profiling in one of the following ways: - Right-click in the editor and select Toggle Profiling. - Open the command palette with cmd+shift+pon a Mac or ctrl+shift+pon Windows. Then, select Codewind: Profiling: Toggle Profiling. - Toggle the Codewind Profiling: Show Profilingsetting in the extensions settings. Workaround: Review the preceding list and ensure that your project conforms to all of the items in the list. Troubleshooting project application and build statuses Troubleshooting general application status problems If your application goes into the Stopped state unexpectedly or stays in the Starting state longer than expected, check the project logs to see whether something went wrong. Open the build and application logs from the project’s context menu. Problems with the build or project configuration can cause the application to fail to start. There are usually errors in the log files in this case. Even without errors, the Stopped state can occur if: - The health check endpoint of the application is unreachable. Ensure it is set to an endpoint that is reachable. - The internal application port is not correct. - Your application uses HTTPS but the HTTPS setting is not set. - The time required for your application to start is longer than the Project status ping timeout. Increase the timeout to a more sufficient time. Troubleshooting general build status problems If your build fails, try the following: - Inspect the build logs. Open the build logs from the project’s context menu. In the build logs, you can view error messages that describe the type and cause of failure. - If the build failure is related to the image build, then view the docker build log and correct any errors in the project’s Dockerfile. Projects stuck in starting or stopped state You might occasionally see projects stuck in the Starting or Stopped state even though the container logs say the projects are up and running. This behavior can occur when you create a number of projects, for example, using the default and Appsody templates with Codewind 0.5.0. Workaround Manually rebuild the projects that are stuck in Starting or Stopped state. To do this: - In the Codewind Explorer view, right-click your project and select Build. - Wait for the project state to return to Running or Debugging in the Codewind Explorer view. Application stuck in Starting state Some project templates come with no server configured by default, like Appsody Node.js. The application status cannot be determined for these types of projects because Codewind relies on application endpoints for status. Codewind determines the port of the application by inspecting the project’s container information. The container may have a port exposed but since no server is available to ping on that port, the status check times out, and the state is stuck on Starting. Workaround The constant state is not inherently a problem; nonetheless, you can disable the status check for the project by taking the following steps: - Edit the .cw-settingsfile under the application, and set the key internalPortto -1. - This forces the project state to Stopped, stops pinging the project’s health check endpoint, and ignores the timeout error. - Once you implement the project’s server, revert the setting by setting internalPortto ""to allow Codewind to use the default port of the container. Alternatively, choose a specific port if your container exposes multiple ports. How to create a .cw-settings file if it does not exist Prior to the 0.9.0 release, some Appsody and OpenShift Do (odo) templates did not come with a .cw-settings. The .cw-settings file is usually created automatically and tells Codewind how to interact with a project. Things like application and build status are tied to these settings. If you have a project from those stacks from a previous release, you must manually create the .cw-settings file. The file must reside under the project root directory. Workaround Create a template .cw-settings file with the following contents: { "contextRoot": "", "internalPort": "", "healthCheck": "", "isHttps": false, "ignoredPaths": [ "" ] } Adjusting the maximum number of concurrent builds It is not recommended to alter this value because there can be a significant impact on performance but in some cases it may be necessary. For example, if there aren’t enough resources to run 3 builds concurrently, you can reduce the maximum number to 1 or 2. If you must adjust the maximum number of concurrent builds, you can set the MC_MAX_BUILDS environmental variable in the codewind-pfe container. Projects build twice upon creation If you use Codewind on Eclipse and VS Code at the same time, projects build twice during project creation, resulting in longer project creation time. Workaround: To reduce project creation time, do not use Codewind on Eclipse and on VS Code at the same time. Close either Eclipse or VS Code, then create your project. MicroProfile project gets updated twice upon file change If you modify files in MicroProfile projects, sometimes the project gets double updates. You might see the application status changed from Running to Stopped twice. If you notice this status change, the default polling rate, which is 500 ms, is too short for the application monitor. Workaround: Increase the polling rate in the server.xml file to 1000 ms or longer. <applicationMonitor pollingRate="1000ms" /> Editing your project Che editor might not work correctly in Microsoft Edge Theia, the open source code editor used by Che, currently has limited support for Microsoft Edge. The Theia team is aware of the issue and is working to fix it. Workaround: Use a different web browser. New projects sometimes do not show in Che hierarchy view Sometimes when a new project is created, it doesn’t show up in the hierarchy view within Eclipse Che. Workaround: Refresh the page in the browser. Context Root / Application Endpoint not correct If you create or bind a project that has a context root set in .cw-settings, such as a project using the Lagom template, the context root is not picked up initially. This also happens after restarting Codewind. Workaround For a permanent fix, edit and save the .cw-settings file, and the context root updates. For a temporary workaround, add the context root to the URL in your browser. For example, the browser might open with localhost:34567 instead of localhost:34567/mycontextroot, so type mycontextroot. Disabling development on specific projects Turning off auto build has no effect for Node.js projects when you run Codewind locally If you turn off auto build for a Node.js project when you run Codewind locally, it has no effect. Changes you make to your code automatically start or restart a build even though auto build is disabled. Appsody with Codewind Projects created never start after installing Codewind Intermittently, after installing Codewind on Windows, projects can be created, but they never start and instead remain in the Starting state. A Docker issue for Windows exists where, although it shows a volume is mounted, it does not allow any writing to the volume. To check if this issue is present, verify that a codewind-data directory exists in the root of your C: drive on Windows and verify you can see your Appsody project folders created within. Workaround: This issue can appear for many reasons, so you have many possible workarounds. First, open the Docker\Settings\Shared Drives directory to confirm that your C: drive is selected. If it is not selected, select it, click Apply, and then try creating projects again. If you’re still noticing the problem, and you’re using an ID for the shared drive that is not your current user, check that the ID being used doesn’t have an expired password that requires a password reset. Reset the password if necessary. Appsody and Docker Desktop on Windows 10 When you use Appsody, configure Docker Desktop to access your C: drive that contains your codewind-data directory. In most cases, you can configure Docker with the same user as the user who develops applications with Appsody. However, if you use Windows 10 Enterprise secured with Azure Active Directory (AAD), the AAD user does not reside in the localhost and might not be accepted in the Shared Drives tab of the Docker Desktop Settings page, especially if the organization configured AAD to issue only PIN codes instead of user passwords. Workaround Complete the instructions in Special notes about Appsody and Docker Desktop on Windows 10. Node.js and Swift templates remain in the starting state The templates Appsody Node.js template and Appsody Swift template remain in the starting state by default because these templates do not have a server implemented, and therefore, their statuses cannot be detected. These templates do not have a server and are intended to help you implement your own server. Workaround To get the application into a Started state, use a server for the application. After the application has a server, Codewind monitors the server, and the status turns to Started if the server is running. Alternatively, you can also temporarily stop Codewind from continuously pinging the application. Kafka templates remain in the starting state The Kafka templates for the Appsody Quarkus and Spring Boot application stacks remain in the starting state when you create a project using them. These projects require users to configure a Kafka instance to connect to in order to run correctly. Additionally, these projects do not expose an endpoint at the / path that Codewind attempts to ping because these projects are not meant to be REST-style applications. Workaround Refer to the documentation for the respective stacks to find out how to configure a Kafka instance to work with the applications: You should also configure the project’s health check endpoint for Codewind to ping instead of the / path. Alternatively, you can also temporarily stop Codewind from continuously pinging the application. An Unknown error appears on line one of the pom.xml file If you use an Eclipse IDE for Enterprise Developer EPP prior to version 2019.06, you might see an Unknown validation error in the pom.xml file. Workaround Switch to version 2019.06 or later, or see Cannot import any project into Eclipse with maven-jar-plugin 3.1.2. Classpath warnings appear or the application classes are not on the classpath If you work with Appsody projects in Codewind for VS Code, you might encounter Classpath is incomplete warnings or notifications that application classes are not on the classpath. Workaround Add the project’s parent folder to the VS Code workspace. - After you create an Appsody Java MicroProfile project, right-click and Add Project to Workspaceif it is not already added. - Right-click on the project from the workspace view and select Add Folder to Workspace… and choose the parent folder of the project. Click Add. - Choose the project folder and click Add. Starting in debug mode results in failure to attach the debugger If you work with Appsody projects in Codewind, and if you restart the project in debug mode, the first attempt to attach the debugger might fail. Workaround Run the Attach Debugger action manually. The following sample steps show instructions for VS Code. The steps to manually attach the debugger in other IDEs is similar: - After you create a project, wait for VS Code to display the project’s state as Running. - Then, right-click the project and select Restart in Debug Mode. - Allow the process to finish. It fails, and a connection exception window appears. - The Restarting <my_project> into debug modemessage is displayed. Wait for this restart notification to disappear. - To manually set the debugger, click the Debug tab and then Play. The debugger is successfully attached to the project if Debug <my_project>is displayed in the message bar or if the project’s state shows Debugging. Appsody binds fail If an Appsody repository is already added in your local Appsody CLI, the Appsody bind might fail. These steps create the issue: - The Appsody repository was added to your local Appsody CLI. The same Appsody repository was then added to Codewind from your IDE by right-clicking Projects (Local) and then clicking Manage Template Sources. - Later, a project was bound to a stack from the added Appsody repository. The project appears in the Codewind Explorer view, and the appsody.logdisplays this error: [Error] The current directory is not a valid appsody project. Run `appsody init <stack>` to create one. Run `appsody list` to see the available stacks. Codewind displays an error. In VS Code, the error appears in the Codewind log: 2019/11/08 11:07:29 Please wait while the command runs... 2019/11/08 11:07:31 [Error] Repository 77b94c9b-0daf-5426-98b8-83eb8ee63e3c is not in configured list of repositories Workaround - Remove the repository from the local Appsody CLI. For example, run the appsody repo removecommand. - Remove and add the repository back into Codewind with Manage Template Sources. - Rebind the project to Codewind. Using Appsody stacks images from private Docker registries Local scenario For Codewind to work with an Appsody stack image on a private Docker registry, the stack must fully qualify the image name in the .appsody-config.yaml configuration of its template, for example: hostname[:port]/username/reponame[:tag]. Also, before you work with the stack, on the local system, enter docker login to the private registry. - Note: When you view the application log, you might see failures to pull the image during a rebuild. However, Codewind is taking the cached container image from your local machine. If you ever delete that image, you need to pull the image again. You can either create another project from the same stack or manually call a docker pullwith the required image. Remote scenario Follow the instructions in Adding a container registry in Codewind. Open Liberty projects do not start within the default timeout Occasionally, Appsody Open Liberty projects do not start, and you see the following entries in the appsody.log: [Container] [INFO] CWWKM2010I: Searching for CWWKF0011I: in /opt/ol/wlp/usr/servers/defaultServer/logs/messages.log. This search will timeout after 120 seconds. [Container] [INFO] CWWKM2013I: The file /opt/ol/wlp/usr/servers/defaultServer/logs/messages.log being validated does not exist. ... [Container] [INFO] CWWKM2011E: Timed out searching for CWWKF0011I: in /opt/ol/wlp/usr/servers/defaultServer/logs/messages.log. ... [Container] [ERROR] Failed to execute goal io.openliberty.tools:liberty-maven-plugin:3.2:dev (default-cli) on project starter-app: Unable to verify if the server was started after 120 seconds. Consider increasing the serverStartTimeout value if this continues to occur. -> [Help 1] By default, Open Liberty projects are configured to wait 2 minutes (120 seconds) for the server to start. These messages are an indication that the server did not start within the default timeout period. Workaround Increase the timeout value in the project’s pom.xml file. Look for the following element and increase the value: <serverStartTimeout>120</serverStartTimeout> OpenShift Do (odo) with Codewind For more information about the OpenShift Do (odo) extension in Codewind, see the README file in the codewind-odo-extension repository. Building an odo project fails because of an existing image stream If you try to create an image stream that already exists in your cluster and then build an odo project, you might receive error messages in the build log: Failed to create component with name <component name>. Please use odo config view to view settings used to create component. Error: imagestreams.image.openshift.io "<image stream name>" already exists unable to create ImageStream for <image stream name> Workaround: - Run kubectl get isto get the existing image stream. - Run kubectl delete is <existing image stream name>to manually delete the existing image stream. OKD and OpenShift Plugin runtime crashes unexpectedly and all plugins are not working With the latest Eclipse Che Version 7.2, you might see the following error when your user session expires for the Eclipse Che workspace: Plugin runtime crashed unexpectedly, all plugins are not working, please reload ... These steps reproduce the issue: - Install Eclipse Che on an OKD cluster. - Create your Codewind workspace from this devfile. - After your session expires, you see a Crashmessage in the Codewind workspace. Workaround Go to the Che workspacedashboard, log out of the Che workspace, and then log back in to the Che workspace. Access the Codewind workspace. Che sometimes fails to reinstall successfully on Red Hat OpenShift on IBM Cloud Sometimes when Che is reinstalled on Red Hat OpenShift on IBM Cloud, the installation might fail with the following error: ✔ Create Che Cluster eclipse-che in namespace che...done. ❯ ✅ Post installation checklist ❯ PostgreSQL pod bootstrap ✔ scheduling...done. ✔ downloading images...done. ✖ starting → ERR_TIMEOUT: Timeout set to pod ready timeout 130000 This error appears because of permissions issues in the namespace. Workaround: To resolve the error, install Che into a namespace other than che with the --chenamespace flag when running chectl server:start. Codewind and Tekton Pipelines Codewind cannot access the Tekton dashboard URL If you install Codewind before you install Tekton, Codewind cannot access the Tekton dashboard URL. In the logs, you see the following error message: Tekton dashboard does not appear to be installed on this cluster. Please install Tekton dashboard on your cluster, and restart your Codewind Che workspace. These steps reproduce the issue: - Install Codewind on OpenShift. - Install Tekton Pipelines. - Click Open Tekton dashboard URL. Codewind does not access the Tekton dashboard URL. Workaround: - Go to the Eclipse Che workspace console. - Select your workspace and stop it. - After 2 minutes, start your workspace again. - Now, access the Tekton dashboard URL from the Codewind palette. OpenAPI tools OpenAPI generation fails in Eclipse if the output path does not exist In Eclipse, OpenAPI generation fails if a path does not exist, and the wizard doesn’t automatically create the folder tree hierarchy if the hierarchy doesn’t already exist. These steps reproduce the issue: - Install the latest version of Codewind. - Add a sample OpenAPI .yamlfile. - From the Project or Package Explorer views, right-click the project and select one of the generator actions in OpenAPI Generate. A dialog window appears. - In the dialog window, if necessary, select the OpenAPI definition file by clicking the Browse… button. - In the Output folder field, copy and paste a path or edit the path directly. - Click Finish. The OpenAPI generator fails if the folder doesn’t already exist. Workaround: For the VS Code extension, manually create the output folder before you start the OpenAPI generator wizard. In the wizard, you can also create the Output folder in the browse dialog. Ensure that the path points to a valid folder in the project. For post-client or post-server stub generation, use a separate output folder for code generation. Depending on the language and the generator type, the OpenAPI generator generates both source code files and build-related files. Some refactoring might be necessary. For example, move the generated source code to the proper source folder that already exists in the project. However, if your project is empty, the target output folder can be the root of the project, and you don’t need to do as much refactoring and merging. For Eclipse, for Java-based code generators, the Open API wizards provide additional support to configure the project. It is recommended that the project’s root folder is selected as the output folder of the generator so that .java files will be generated into the existing src/main/java and src/test/java folders. The wizard’s default value of the output folder is the project’s root folder. The wizard also performs some automatic configuration, including pom.xml file merging, and necessary updates to the project’s classpath. Plugin execution validation error in the pom.xml file When generating a Java client or server stub into an existing Appsody or Codewind Liberty Microprofile project, you might see a plugin execution validation error in the pom.xml file: Plugin execution not covered by lifecycle configuration: org.codehaus.mojo:aspectj-maven-plugin:1.0:compile (execution: default, phase: process-classes) The build is successful even though the validator reports this issue. Workaround: To resolve this in Eclipse, surround the plugins element under the build element of the pom.xml file with the pluginManagement element. <build> <pluginManagement> <plugins> ... The following workaround applies to Eclipse. Add the configuration element to the pom.xml file: <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>org.openapitools.OpenAPI2SpringBoot</mainClass> </configuration> .... Setting Codewind server log levels Assisting with problem determination by raising the default Codewind server log level To assist with problem determination, raise the default Codewind server log level to Debug or Trace. Use the cwctl loglevels command or follow the instructions for an IDE: - In Eclipse, enable support features in the Codewind preferences, then right-click the connection in the Codewind Explorer view and click Codewind server log level. - In IntelliJ, go to the Debug Log Settings dialog and enable the org.eclipse.codewindcategory so Codewind diagnostic debug and trace messages are written to the log. The #org.eclipse.codewindmethod turns on debug level messages, and the #org.eclipse.codewind:tracemethod turns on trace level messages. - In VS Code, use the Codewind: Set Codewind Server Logging Level command in the Command Palette. Collecting log files and environment data You can capture diagnostics from your installation by using the cwctl diagnostics CLI command to collect all available log files and environment information. You can find the cwctl CLI in your HOME directory under the ~/.codewind/<version> path. The format of the command is: cwctl diagnostics [command options] [arguments...] Command options are: --conid <value>- Triggers diagnostics collection for the remote codewind instance (must have currently configured Kubectl connection, default:”local”) --eclipseWorkspaceDir/-e <value>- The location of your Eclipse workspace directory if using the Eclipse IDE, default:””) --intellijLogsDir/-i <value>- The location of your IntelliJ logs directory if using the IntelliJ IDE (default: “”) --quiet/-q- Turn off console messages --projects/-p- Collect project containers information --nozip/-n- Does not create collection zip and leaves individual collected files in place --clean- Removes the diagnosticsdirectory and all its contents from the Codewind home directory After you run the command, you can find the captured diagnostics files under your HOME directory in the ~/.codewind/diagnostics/<timestamp> folder. For more information about the cwctl diagnostics command, type cwctl help diagnostics, or see the diagnosticsCli documentation. Eclipse troubleshooting For Codewind specific problem solving tips when using Eclipse, see the following information. Check the Eclipse logs The logs are found in your Eclipse workspace under .metadata/.log. Solving common Eclipse problems The following list describes common problems that might affect Codewind. - Open application fails - Debugger fails to connect - Application stuck in Starting state - Application does not rebuild after making a change - Correct project list is not being shown - Application is not showing the correct status Open application fails The default browser in Eclipse might not be able to handle the content of your application. Try using a different browser by clicking on Window > Web Browser. Select a browser from the list and try to open the application again. Debugger fails to connect If the debugger fails to connect, you might need to increase the connection timeout: - Open the Eclipse preferences and select Codewind. - Increase the debug connection timeout value and click Apply and Close. Application stuck in Starting state in Eclipse The application might be waiting for the debugger to connect. You can resolve this by right-clicking on the project in the Codewind Explorer view and selecting Attach Debugger. If the problem occurred because the debugger failed to connect when restarting in debug mode, make sure to increase the debug connection timeout in the Codewind preferences before trying to debug again. For more information see Debugger fails to connect. If the debugger is connected but stopped on a ClassNotFoundException, click on the run button to get past the exception. You might need to click run several times as the exception occurs more than once. To avoid stopping on the exception in the future, open the Eclipse preferences and navigate to Java > Debug. Uncheck Suspend execution on uncaught exceptions and click Apply and Close. If the application is not waiting for the debugger to connect, try restarting the application again. If this does not work, use Codewind to disable the application and then re-enable it. Application does not rebuild after making a change To start a build manually, right click on the application in the Codewind Explorer view, and selecting Build. Correct project list is not being shown Refresh the project list by right-clicking the connection in the Codewind Explorer view and selecting Refresh. Application is not showing the correct status Refresh the application by right-clicking it in the Codewind Explorer view and selecting Refresh. VS Code troubleshooting For Codewind specific problem solving tips when using VS Code, see the following information. Solving common VS Code problems The following list describes common problems that might affect Codewind. - Codewind output stream - Finding the extension logs - Executable file not found on PATH in VS Code - No ESLint warnings or errors - Debug Codewind output stream The Codewind output stream is available in the VS Code editor. It logs cwctl commands together with their output. Check the Codewind output stream first when troubleshooting because it is particularly useful in helping you to debug unusual problems especially when starting Codewind. Some errors will also provide you with a button to open the Codewind output stream, for example: Finding the extension logs If you report an issue, you will be asked to upload your logs. - In VS Code, open Help > Toggle Developer Tools. - Go to the Console tab. - Enter codewind.log in the Filter box: - Upload the contents of the log file with your issue report. Executable file not found on PATH in VS Code Codewind will not work if it cannot find the docker executable in any of the paths specified in the PATH environment variable. The error message is similar to the following: exec: "docker": executable file not found in $PATH First, make sure docker is installed and that you can run it from the command line. The terminal used does not have to be a terminal within VS Code. Run the following command: $ docker --version Docker version 19.03.8, build afacb8b Make sure the output is similar to this example. If you can run docker from the command line, but Codewind still fails to find docker, it’s possible that VS Code is using a different PATH than the terminal you used. To make sure the terminal and VS Code are using the same PATH, perform the following steps: - Make sure you can run VS Code from the command line. The executable is code. - On Windows and Linux, you can run VS Code from the command line immediately after installation by running code. - For macOS, follow the additional step, Launching from the command line. - Close all instances of VS Code. - Open the terminal you ran dockerfrom and run code. - Now, the new VS Code instance shares the terminal’s PATH. Start Codewind again. No ESLint warnings or errors You see no ESLint warning or errors for Node.js projects. Install the ESLint extension and follow the instructions to activate the extension. Debug Debugger attach fails with the message “Configured debug type “java” is not supported” Install and enable the Java Extension Pack. Debugger fails to attach after restarting project into Debug mode Run the attach debugger command again. If the issue persists after a few attempts, restart the project in Debug mode a second time.
https://www.eclipse.org/codewind/troubleshooting.html
CC-MAIN-2020-24
refinedweb
6,344
54.52
A package to return the health status of a flask application Project description Installation pip3.7 install --user FlaskHealthCheck #use whatever pip version you have, but this is built for python3+ Requirements This package relies on a couple of things: Your Flask application has a file called 'appversion.txt' in its root directory with a line at the top that looks like: version: x.x.x (check the flask-template for clarification) You've got Python 3+ installed as well as Flask and all of your necessary dependencies (obviously, including the package we install here) Use Within your routes file that will contain the health check endpoint do the following: import FlaskHealthCheck #Add your endpoint like so: @app.route('/api/healthcheck') @cross_origin() @swag_from('../swags/healthcheck/healthcheck.yml') #or wherever your swagger file may be for this endpoint def health_check(): return jsonify(FlaskHealthCheck.healthcheck()) Example Return Value When the endpoint is called from your API, an expected 200 response would look like the following: { "HealthCheckResponse": { "AppVersion": "1.0.0", //The app version "Config": { "CurDir": "/opt/apps/MyWebAPI", //Root directory of your API "IsSuccess": "true", //API is reachable (this is a 'to-be-configured' state) "MachineName": "MyMachineName", //The hostname of the box it's being run on "PyVersion": "3.7.0 (default, Sep 24 2018, 12:47:32) \n[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]", "Uptime": 126.47574424743652, //How long (in seconds) the service has been up for "User": "WebAPIUser" //The user which is running the service } } } Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/flask-otpp-healthcheck/
CC-MAIN-2022-05
refinedweb
279
52.39
{-# LANGUAGE GeneralizedNewtypeDeriving, TypeSynonymInstances, TemplateHaskell, RecordWildCards, FlexibleInstances #-} module Cake.Core ( -- * Patterns and rules. Rule, P, (==>), -- * High-level interface Act, cake, need, needs, list, -- * Mid-level interface produce, produces, cut, independently, -- * Low-level interface debug, distill, fileStamp, shielded, use, updates, Question(..), Answer(..), Failure(..), -- * Re-exports module Control.Applicative, throwError, ) where import Data.Digest.Pure.MD5 import qualified Data.ByteString.Lazy as B import System.Directory import System.FilePath import Control.Applicative import Control.Monad (when) import Control.Monad.RWS hiding (put,get) import qualified Control.Monad.RWS as RWS import Control.Monad.Error Failure = CakeError String | Panic | ProcessError ExitCode deriving (Eq) instance Show Failure where show (CakeError x) = x show (ProcessError code) = "Process returned exit code " ++ show code show (Panic) = "PANIC" $( derive makeBinary ''ExitCode ) $( derive makeBinary ''Failure ) data Answer = Stamp (Maybe MD5Digest) | Text [String] | Failed Failure (ErrorT Failure (RWST Context Written State IO) a) deriving (Functor, Applicative, Monad, MonadIO, MonadState State, MonadWriter Written, MonadReader Context, MonadError Failure) data Status = Clean | Dirty deriving (Eq,Ord) instance Error Failure where noMsg = Panic strMsg = CakeError instance Applicative P where (<*>) = ap pure = return instance Alternative P where (<|>) = (Parsek.<|>) empty = Parsek.pzero -- | Primitve for rule construction. The given action must produce -- files matched by the pattern. (==>) ::Answers <- runAct rule oldDB action let newDB = newAnswers <> oldDB -- new answers overwrite old ones putStrLn $ "Database is:" forM_ (M.assocs newDB) $ \(k,v) -> putStrLn $ (show k) ++ " => " ++ (show v) encodeFile databaseFile newDB -- | Was the file already produced? produced :: FilePath -> Act Bool produced f = do (ps,_) <- RWS.get return $ f `S.member` ps modCx q (Context {..}) = Context {ctxProducing = q:ctxProducing,..} -- | Answer a question using the action given. distill :: Question -> Act Answer -> Act Answer distill q act = local (modCx q) $ do debug $ "Starting to answer: " ++ show q db <- ctxDB <$> ask a1 <- refresh q $ noClobber act let same = Just a1 == M.lookup q db debug $ "Old answer: " ++ show (M.lookup q db) debug $ "New answer: " ++ show a1 when (not same) clobber debug $ "Same? " ++ show same return a1 -- | Answer a question using the action given. -- The result is not compared to the -- previous run, so it is the caller responsibility that the new -- answer is properly taken into account. refresh :: Question -> Act Answer -> Act Answer refresh q act = do a <- act tell (Dual $ M.singleton q a) return a `catchError` \ e -> do -- on error tell (Dual $ M.singleton q $ Failed e) -- Answering the question failed... throwError e -- and questions depending on it will also fail produce x = produces [x] -- | Produce a file, using the given action. produces :: [FilePath] -> Act () -> Act () produces fs a = do ps <- mapM produced fs -- Do nothing if the file is already produced. when (not $ and ps) $ updates fs a -- | Produce a file, using with the given action. BUT: no problem to -- produce the same file multiple times. updates :: [FilePath] -> Act () -> Act () updates [] a = a updates (f:fs) a = distill (FileContents f) (do e <- liftIO $ doesFileExist f updates fs (when (not e) clobber >> a) -- force running the action if the file is not present, even if in a clean state. modify $ first $ S.insert f -- remember that the file has been produced already fileStamp f) >> return () -- |. (To be used eg. if a command uses an optional file). use f = distill (FileContents f) (fileStamp f) -- | File was modified by some command, but in a way that does not -- invalidate previous computations. (This is probably only useful for -- latex processing). overwrote :: FilePath -> Act Answer.modify (second (const s)) return x -- | Run the action, but do not clobber the state. noClobber :: Act a -> Act a noClobber a = do s <- snd <$> RWS.get x <- a RWS.modify (second (const s)) return x independently :: [Act a] -> Act () independently as = do (ps,s) <- RWS.get ds <- forM as $ \a -> do RWS.modify (second (const s)) a snd <$> RWS.get RWS.modify (second (const (maximum $ s:ds))) runAct :: Rule -> DB -> Act () -> IO DB runAct r db (Act act) = do h <- openFile logFile WriteMode (a,Dual db) <- evalRWST (runErrorT act) (Context h r db []) (S.empty,Clean) case a of Right _ -> putStrLn "Success!" Left e -> putStrLn $ "cake: " ++ show e hClose h return db findRule :: FilePath -> Act (Maybe (Act ())) findRule f = do r <- ctxRule <$> ask let rs = parse r completeResults f case rs of Right [x] -> return (Just x) Right _ -> throwError $ CakeError $ $ st ++ " "++ concat (map (++": ") $ reverse $ map show ps) ++ x -- | Return a stamp (hash) for a file fileStamp :: FilePath -> Act Answer fileStamp f = liftIO $ do e <- doesFileExist f Stamp <$> if e then Just <$> md5 <$> B.readFile f else return Nothing clobber = RWS.modify $ second $ (const Dirty) -- | Run the action in only in a clobbered state cut :: Act () -> Act ()) $ throwError $ CakeError $ "No rule to create " ++ f debug $ "using existing file" use f return () Just a -> a needs = independently . map need
http://hackage.haskell.org/package/cake-1.0.0/docs/src/Cake-Core.html
CC-MAIN-2014-52
refinedweb
780
57.77
On Sun, May 11, 2008 at 11:46:24AM +0200, Luca Abeni wrote: > Hi, > > Carl Eugen Hoyos wrote: > [...] >> dest_addr_len in udp.c is defined as size_t which is unsigned (if I >> googled that correctly). Attached patch removes a comparison of >> dest_addr_len with zero (fixes a warning when compiling with icc). > [...] > As I wrote in the previous email, I do not think that removing the error > check is a good idea. > I have never seen this warning (even gcc 4.1 does not complain), but I > think the attached patches are a better solution (I have no opinions about > which one is better, so I attach all the three patches). > > > Luca [...] > Index: libavformat/udp.c > =================================================================== > --- libavformat/udp.c (revision 13104) > +++ libavformat/udp.c (working copy) > @@ -51,7 +51,7 @@ > #else > struct sockaddr_storage dest_addr; > #endif > - size_t dest_addr_len; > + int dest_addr_len; > } UDPContext; > > #define UDP_TX_BUF_SIZE 327: <>
http://ffmpeg.org/pipermail/ffmpeg-devel/2008-May/053311.html
CC-MAIN-2015-06
refinedweb
141
65.42
Technote (FAQ) Question The WSDL automatically generated by the MTDS is not always what you expect or you may want to modify the binding. Since the WSDL is generated automatically at runtime, you cannot modify directly the WSDL in Rule Studio or Eclipse. Then, how to do it? Cause JRules leverages Java API for XML Web Services Annotations (JAX-WS) to get the WSDL generated from the java XOM Answer You will have to add annotations in your java XOM. The annotations will be processed when the WSDL generation API (JAX-WS) parse the java XOM. But first, you will have to upgrade the version of the JAXWS libraries, as the version provided in JRules 7.0.x and 7.1.x (JAX-WS v2.1.1) is not compatible with annotations. You can download the newer library (v2.1.7) from the JAX-WS reference implementation's web site: You will thus need to update the build script accordingly, so that it picks up the JAX-WS jar files from the newer version. This means modifying the <path id="jaxws.classpath"> definition in the build.xml file (in the MTDS project). Then, in your java XOM, add for instance the annotation @XmlElement(required=true) for the attributes that musts have a minoccur="1" in the XSD so that they are no longer tagged as Optional in the WSDL generated. For xml binding java annotations, refer to the java doc If you want to have an attribute that is required and not nullable, you will annotate it : public class Foo { @XmlElement(nillable=true, required=true) public int bar; } The XML generated will be : <xs:complexType <xs:sequence> <xs:element </sequence> </xs:complexType>
http://www-01.ibm.com/support/docview.wss?uid=swg21594789
CC-MAIN-2014-52
refinedweb
282
55.34
Conference DEVOXX UK. Choose a framework: Docker Swarm, Kubernetes or Mesos. Part 2 - Local development. - Deployment Features - Multicontainer applications. - Service discovery service discovery. - Scaling service. - Run-once assignments. - Integration with Maven. - A “rolling” update. - Creating a Couchbase database cluster. As a result, you will get a clear idea of what each orchestration instrument has to offer, and learn how to use these platforms effectively. Arun Gupta is Amazon Web Services’ premier open-source product technologist who has been developing Sun, Oracle, Red Hat, and Couchbase developer communities for over 10 years. He has extensive experience working in leading cross-functional teams involved in the development and implementation of marketing campaigns and programs. He led the Sun engineering team, is one of the founders of the Java EE team and the creator of the American branch of Devoxx4Kids. Arun Gupta is the author of more than 2 thousand posts in IT blogs and has made presentations in more than 40 countries. Conference DEVOXX UK. Choose a framework: Docker Swarm, Kubernetes or Mesos. Part 1 Scale scaling concept means the ability to control the number of replicas by increasing or decreasing the number of application instances. For example: if you want to scale the system to 6 replicas, use the docker service scale web = 6 command. Along with the Replicated Service concept in Docker, there is the concept of shared services Global Service. Let’s say I want to run an instance of the same container on each node of the cluster, in this case it is a container of the Prometheus web monitoring application. This application is used when you need to collect metrics about the operation of hosts. In this case, you use the subcommand – – mode = global – – name = prom prom / Prometheus. As a result, the Prometheus application will be launched on all nodes of the cluster, without exception, and if new nodes are added to the cluster, it will automatically start in the container and in these nodes. I hope you understand the difference between Replicated Service and Global Service. Usually the Replicated Service is where you start. So, we have examined the basic concepts, or basic entities of Docker, and now we will consider the entities of Kubernetes. Kubernetes is also a kind of planner, a platform for container orchestration. It must be remembered that the main concept of the scheduler is knowing how to schedule containers on different hosts. If you go to a higher level, we can say that orchestration means expanding your capabilities to manage clusters, obtain certificates, etc. In this sense, both Docker and Kubernetes are orchestration platforms, both of which have a built-in scheduler. Orchestration is an automated management of related entities – clusters of virtual machines or containers. Kubernetes is a collection of services that implement a container cluster and its orchestration. It does not replace Docker, but significantly expands its capabilities, simplifying the management of deployment, network routing, resource consumption, load balancing and fault tolerance of running applications. Compared to Kubernetes, Docker is focused on working with containers, creating their images using a docker file. If we compare the Docker and Kubernetes objects, we can say that Docker manages the containers, while Kubernetes manages the Docker itself. How many of you have dealt with Rocket containers? Does anyone use Rocket in production? Only one person raised his hand in the hall, this is a typical picture. This is an alternative to Docker, which still has not taken root in the developer community. So, the main essence of Kubernetes is Pod. It is a related group of containers that use a common namespace, shared storage, and shared IP address. All containers in the hearth communicate with each other through the local host. This means that you will not be able to place the application and the database in the same hearth. They must be placed in different pods, because they have different scaling requirements. Thus, you can place in one pod, for example, a WildFly container, login container, proxy container, or cache container, and you must responsibly approach the composition of the container components that you are going to scale. Usually you wrap your container in the Replica Set, because you want to run a certain number of instances in the hearth. Replica Set tells you to start as many replicas as the Docker scaling service requires, and tells you when and how to do it. Pods are similar to containers in the sense that if a pod fails on one host, it restarts on a different pod with a different IP address. As a Java developer, you know that when you create a java application and it communicates with the database, you cannot rely on a dynamic IP address. In this case, Kubernetes uses Service – this component publishes the application as a network service, creating a static permanent network name for a set of hearths, while simultaneously balancing the load between the hearths. It can be said that this is the service name of the database, and the java application does not rely on the IP address, but only interacts with the database constant name. This is achieved by the fact that each Pod is supplied with a specific Label, which is stored in the distributed storage etcd, and Service monitors these labels, providing a link between the components. That is, pods and services stably interact with each other using these labels. Now let’s look at how to create a Kubernetes cluster. For this, as in Docker, we need a master node and a working node. A node in a cluster is usually represented by a physical or virtual machine. Here, as in Docker, the wizard is a central control structure that allows you to control the entire cluster through the scheduler and controller manager. By default, a master node exists in the singular, but there are many new tools that allow you to create multiple master nodes. Master-node provides user interaction using the API server and contains the distributed storage etcd, which contains the configuration of the cluster, the status of its objects and metadata. Worker-node work nodes are designed exclusively for running containers, for this they have two Kubernetes services installed – a proxy service network router and a kubelet scheduler agent. While these nodes are running, Docker monitors them using systemd (CentOS) or monit (Debian), depending on which operating system you are using. Consider the Kubernetes architecture more broadly. We have a Master, which includes an API server (pods, services, etc.), managed using the CLI kubectl. Kubectl allows you to create Kubernetes resources. It sends commands to the API server such as “create under”, “create service”, “create a set of replicas”. Further here is the Scheduler, the Controller Manager, and the etcd repository. The controller manager, having received the instructions of the API server, maps replica labels to hearth labels, ensuring stable interaction between components. The scheduler, having received the task of creating under, scans the working nodes and creates it where it is provided. Naturally, he gets this information from etcd. Next, we have several working nodes, and the API server communicates with the Kubelet agents contained in them, telling them how the pods should be created. Here is the proxy that gives you access to an application that uses these pods. My client is shown on the right on the slide – this is an Internet request that goes to the load balancer, that one turns to the proxy, which distributes the request among the submissions and sends the response back. You see the final slide, which depicts the Kubernetes cluster and how all its components work. Let’s talk more about Service Discovery and the Docker load balancer. When you launch your Java application, this usually happens in multiple containers on multiple hosts. There is a component of Docker Compose, which makes it easy to run multi-container applications. It describes multicontainer applications and launches them using one or more yaml configuration files. By default, these are docker-compose.yaml and docker-compose.override.yaml files, with multiple files specified using – f. In the first file you write the service, images, replicas, tags, etc. The second file is used to overwrite the configuration. After creating docker-compose.yaml, it deploys to the multi-host cluster that Docker Swarm previously created. You can create one basic configuration file docker-compose.yaml, in which you will add specific configuration files for different tasks, indicating specific ports, images, etc., we will talk about this later. On this slide, you see a simple example of a Service Discovery file. The first line indicates the version, and line 2 indicates that it concerns the db and web services. I want my web-service to communicate with the db-service after “raising”. These are simple java applications deployed in WildFly containers. In line 11, I write the environment couchbase_URI = db. This means that my db service uses this database. In line 4, the couchbase image is indicated, and in lines 5-9 and 15-16, respectively, the ports necessary to ensure the operation of my services. The key to understanding the service discovery process is that you create some kind of dependency. You indicate that the web container should start before the db container, but this is only at the container level. How your application reacts, how it starts – these are completely different things. For example, usually the container “rises” in 3-4 seconds, however, the launch of the database container takes much longer. So the logic of launching your application should be “baked” in your java application. That is, the application must ping the database to make sure it is ready. Since the couchbase database is a REST API, you should call this API and ask, “Hey, are you ready? If so, then I am ready to send you inquiries! ” Thus, dependencies at the container level are determined using the docker-compose service, but at the application level, dependencies and viability are determined based on responsibility surveys. Then you take the docker-compose.yaml file and deploy it in the multi-host Docker using the docker stack deploy command and the subcommand – – compose-file = docker-compose.yaml webapp. So, you have a large stack in which there are several services that solve several problems. Basically, these are the tasks of launching containers. Consider how the load balancer works. In the above example, using the docker service create command, I created a service – the WildFly container, specifying the port number in the form 8080: 8080. This means that port 8080 on the host – the local machine – will be linked to port 8080 inside the container, so you can access the application through localhost: 8080. This will be the access port to all work nodes. Remember that the load balancer is host oriented, not container oriented. It uses ports 8080 of each host, regardless of whether the containers are running on the host or not, because now the container works on one host, and after the task is completed, it can be transferred to another host. So, client requests are received by the load balancer, he redirects them to any of the hosts, and if, using the IP address table, he gets to the host with an container not running, he automatically redirects the request to the host on which the container is running. A single hop is not expensive, but it is completely “seamless” in terms of scaling your services up or down. Thanks to this, you can be sure that your request will go exactly to the host where the container is running. Now let’s look at how Service Discovery in Kubernetes works. As I said, a service is an abstraction in the form of a set of hearths with the same IP address and port number and a simple TCP / UDP load balancer. The following slide shows the Service Discovery configuration file. Creating resources such as pods, services, replicas, etc. happens based on the configuration file. You see that it is divided into 3 parts using lines 17 and 37, which consist only of – – -. Let’s look at line 39 first – it says kind: ReplicaSet, that is, what we are creating. Lines 40-43 contain metadata, with lines 44 specifying the specification for our replica set. Line 45 indicates that I have 1 replica, its Labels are listed below, in this case the name is wildfly. Even lower, starting from line 50, it is indicated in which containers this replica should be launched – this is wildfly-rs-pod, and lines 53-58 contain the specification of this container. 23:05 min To be continued very soon … A bit of advertising 🙂 c using Dell R730xd E5-2650 v4 servers costing 9,000 euros for a penny?
https://prog.world/conference-devoxx-uk-choose-a-framework-docker-swarm-kubernetes-or-mesos-part-2/
CC-MAIN-2021-49
refinedweb
2,127
54.83
I am just starting to learn C++ and took the advice of this site on which book to start with, namely C++ without fear. So far I am doing well and understanding what the writer is teaching but then I ran into the card dealer. Nothing to hard to understand until he adds in the array to ensure that no card was picked twice. I know that it works but I am unclear on HOW and WHY it works. As far as I can understand, the code simply passes a location in the array and thats all. I cannot figure out where the program is told what to do at the location, that is, check for 1's and skip them. Can someone please help me understand how this works. I do not want to continue on with the book without understanding this. Thank you. Code:#include "stdafx.h" #include <iostream> #include <stdlib.h> #include <time.h> #include <math.h> using namespace std; int rand_0toN1(int n); void draw_a_card(); int select_next_available(int n); char *suits[4] = {"Hearts", "Spades", "Clubs", "Diamonds"}; char *ranks[13] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}; int card_drawn[52]; int cards_remaining = 52; int main() { int n, i; srand(time(NULL)); while(1) { cout << "Enter number of cards to draw (0 to Exit)"; cin >> n; if (n == 0) break; for (i =1; i <= n; i++) draw_a_card(); } return 0; } void draw_a_card() { int r, s, n, card; n = rand_0toN1(cards_remaining--); card = select_next_available(n); r = card % 13; s = card / 13; cout << ranks[r] << " of " << suits[s] << endl; } int select_next_available(int n) { int i = 0; while (card_drawn[i]) i++; while (n-- > 0){ i++; while (card_drawn[i]) i++; } card_drawn[i] = true; return i; } int rand_0toN1(int n) { return rand() % n; }
http://cboard.cprogramming.com/cplusplus-programming/141138-cplusplus-without-fear-card-dealer-question.html
CC-MAIN-2014-15
refinedweb
294
73.92
Tiles client¶ OWM provides tiles for a few map layers displaying world-wide features such as global temperature, pressure, wind speed, and precipitation amount. Each tile is a PNG image that is referenced by a triplet: the (x, y) coordinates and a zoom level The zoom level might depend on the type of layers: 0 means no zoom (full globe covered), while usually you can get up to a zoom level of 18. Available map layers are specified by the pyowm.tiles.enums.MapLayerEnum values. OWM website technical reference¶ Usage examples¶ Tiles can be fetched this way: from pyowm import OWM from pyowm.tiles.enums import MapLayerEnum owm = OWM('my-API-key') # Choose the map layer you want tiles for (eg. temeperature layer_name = MapLayerEnum.TEMPERATURE # Obtain an instance to a tile manager object tm = owm.tile_manager(layer_name) # Now say you want tile at coordinate x=5 y=2 at a zoom level of 6 tile = tm.get_tile(5, 2, 6) # You can now save the tile to disk tile.persist('/path/to/file.png') # Wait! but now I need the pressure layer tile at the very same coordinates and zoom level! No worries... # Just change the map layer name on the TileManager and off you go! tm.map_layer = MapLayerEnum.PRESSURE tile = tm.get_tile(5, 2, 6) Tile object¶ A pyowm.commons.tile.Tile object is a wrapper for the tile coordinates and the image data, which is a pyowm.commons.image.Image object instance. You can save a tile to disk by specifying a target file: tile.persist('/path/to/file.png') Use cases¶ I have the lon/lat of a point and I want to get the tile that contains that point at a given zoom level¶ Turn the lon/lat couple to a pyowm.utils.geo.Point object and pass it from pyowm.utils.geo import Point from pyowm.commons.tile import Tile geopoint = Point(lon, lat) x_tile, y_tile = Tile.tile_coords_for_point(geopoint, zoom_level): I have a tile and I want to know its bounding box in lon/lat coordinates¶ Easy! You’ll get back a pyowm.utils.geo.Polygon object, from which you can extract lon/lat coordinates this way polygon = tile.bounding_polygon() geopoints = polygon.points geocoordinates = [(p.lon, p.lat) for p in geopoints] # this gives you tuples with lon/lat
https://pyowm.readthedocs.io/en/latest/v3/map-tiles-client-usage-examples.html
CC-MAIN-2022-33
refinedweb
384
58.79
Test::Functional - Perl tests in a functional style. use Test::Functional; # make sure the bomb goes off sub explode { die "BOOM" } test { explode() } dies, "test-3"; # implicit and explicit equivalence test { 2 * 2 } 4, "test-1"; test { 2 * 2 } eqv 4, "test-1"; # test blocks can be as simple or as involved as you want test { 3 > 0 } true, "test-4"; test { my $total = 0; foreach my $person ($car->occupants) { $total += $person->weight } $total < 600 } true, "test-5"; # after the test runs, you also get the result. my $horse = test { Horse->new } typeqv "Horse", "test-6"; # you can make your own comparator functions, or use existing ones. use Test::More import => [qw(like)]; sub islike { my ($other) = @_; return sub { my ($got, $testname) = @_; like($got, $other, $testname); }; } test { 'caterpillar' } islike(qr/cat/), 'is cat?'; This modules uses (abuses?) the ability to create new syntax via perl prototypes to create a testing system focused on functions rather than values. Tests run blocks of Perl, and use comparator functions to test the output. Despite being a different way of thinking about tests, it plays well with Test::More and friends. Since this module is going to be used for test scripts, its methods all export by default. You can choose which you want using the standard directives: # import only eqv use Test::Functional tests => 23, import => ['eqv']; # import all but notest use Test::Functional tests => 23, import => ['!notest']; This package has two settings which can be altered to change performance: unstable - run tests which are normally skipped fastout - cause the entire test to end after the first failure This package can be configured via Test::Functional::Conf or the configure() function. Changes configuration values at run-time. This is the basic building block of Test::Functional. Each test function contains an anonymous code block (which is expected to return a scalar result), a name for the test, and a condition (an optional subroutine to check the result). In most cases, a test passes if the code block doesn't die, and if the condition is true (or absent). There is a special condition dies which expects the code block to die, and fails unless it does so. Whether the test passes or fails, test returns the value generated by BLOCK. This works like test except that if it fails, it will short-circuit all testing at the current level. This means that top-level pretest calls will halt the entire test if they fail. One obvious example for this is: BEGIN { pretest { use Foo::Bar } "test-use" } test { Foo::Bar::double(2) } eqv(4), "double(2)"; test { Foo::Bar::double(3) } eqv(6), "double(3)"; test { Foo::Bar::double(4) } eqv(8), "double(4)"; If the use Foo::Bar fails, the information that all the other tests are failing is less useful. pretest can also be combined with group (described later) to short-circuit a small set of related tests. This is has exactly the same semantics as test; the only difference is that it normally doesn't run. If Test::Functional::Conf->unstable is true, then this test will run, otherwise it won't, and will just return undef. For test-driven development, it is useful to create failing tests using notest blocks; this prevents test regression. Once the implementation starts working notest can be switched to test. Groups are blocks which wrap associated tests. Groups can be used to namespace tests as well as to allow groups of tests to fail together. Here is a short example: group { my $a = coretest { Adder->new } typeqv 'Adder', "new"; test { $a->add(4, 6) } 10, "4 + 6"; test { $a->add("cat", "dog") } dies, "mass hysteria"; test { $a->add() } isundef, "not a number"; } "adder"; If Adder->new fails, the rest of the tests aren't producing useful results, so they will be skipped. See the ETHOS section for a more in-depth discussion of the package in general, and the implications of test short-circuiting in particular. Creates a function which tests that the result is exactly equivalent (eqv) to OBJECT (using Test::More::is_deeply). It works for both simple values and nested data structures. See Test::More for more details. If test receives a condition which isn't a code-ref, it will be wrapped in an eqv call, since this is the most common case (testing that a result is the expected value). Tests whether the result differs from (is inequivalent to) OBJECT according to Data::Compare. This is expected (hoped?) to be inverse of eqv. Creates a function which tests that the result is of (or inhereits from) the provided TYPE (that the result's type is equivalent to TYPE). For unblessed references, it checks that ref($result) eq $type. For blessed references it checks that $result->isa($type). Results which are not references will always be false. Verifies that the test's code block died. It is unique amongst test conditions in that it doesn't test the result, but rather tests $@. Any result other than a die succeeds. This is the "default" condition; if no condition is given to a test then this condition is used. As long as the code block does not die, the test passes. Verifies that the result is a true value. Verifies that the result is a false value. Checks that the result is defined (not undef). Checks that the result is undefined. Anonymous subroutines can be used in place of the provided test conditions. These functions take two arguments: the test result and the test's name. Here are some examples: use Test::More; sub over21 { my ($result, $name) = @_; return cmp_ok($result, '>=', 21, $name); } test { $alice->age } \&over21, 'can alice drink?'; test { $bob->age } \&over21, 'can bob drink?'; These examples are kind of clunky, but you get the idea. Using anything complicated will probably require reading the source, and/or learning how to use Test::Builder. In particular, it's important to make sure builder->level is set correctly. This package exists to address some specific concerns I've had while writing tests using other frameworks. As such, it has some pretty major differences from the other testing frameworks out there. Most Perl tests are written as perl scripts which test Perl code by calling functions or methods, and then using various Test packages to look at the result. This approach has some problems: $@tests, as well as effectively doubling the number of tests that are "run" without meaningfully doubling the test coverage. Test::Functional addresses these concerns: it enables the programmer to write all the "meat" of the test script inside anonymous subs which are tests [1]. Since each test checks both that the code did not die and that the result was what was expected, the tester doesn't have to worry about what kind of failure might occur, just about the expected outcome [2]. Especially when trying to test other people's code (gray box testing?) this feature is invaluable. The various features to prematurely end the test (using pretest() and/or $Test::Functional::Conf->fastout) can help the developer to focus on the problem at hand, rather than having to filter through spew [3]. This is especially nice during test-driven development, or when trying to increase coverage for an old and crufty module. Erik Osheim <erik at osheim.org> The syntax takes some getting used to. I should create default wrappers for things such as like and compare from Test::More. Currently I mostly use true but that gives less debugging information. I wrote these tests to suit my needs, so I am sure there are cases I haven't thought of or encountered. Also, I'm sure I have a lot to learn about the intricacies of Test::Harness and Test::Module. Please contact me (via email or) with any comments, advice, or problems. This module is based on Test::Builder::Module, and relies heavily on the work done by Michael Schwern. It also uses Data::Compare by David Cantrell. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/dist/Test-Functional/lib/Test/Functional.pm
CC-MAIN-2014-52
refinedweb
1,355
63.19
structure and pattern for events When we use robotlegs we necessary end with a lot of classes, and many of then event classes. I'm really bad for organizing things (not only in code, you should see my room/house/garden/life ). So I was looking for a good structure folder, pattern, and conventions for names, classes, etc. I found this for folder structure:... and I'm using that, with some modifications, but after seeing some of the robotlegs examples I saw that structure is not always respected, I see very different structures too (something like modules I guess, with a MVC triad inside each principal component, I don't know). I'm afraid I will end changing a lot of things or with a big mess, but for now I'm intrigued in how you organize your events. I saw you often put an events folder inside "view", "model" and "service", I think you are putting events dispatched for those classes there. But I see there's an event folder in the root too, at the same level that "view" "model" etc. What are the events saved there? that folder it's not present in the above recommended structure. Are these events dispatched by many classes? Also, what is the reason for having different events folders? I think you have a reason for that, because for example flash is grouping all the events inside "flash.events" Thanks! Comments are currently closed for this discussion. You can start a new one. Keyboard shortcuts Generic Comment Form You can use Command ⌘ instead of Control ^ on Mac Support Staff 1 Posted by Stray on 06 Jun, 2011 06:46 PM Hi Enrique, I tend to ask the question "who owns this event?" and then use the answer to determine where I want to put the event. Sometimes an event is specific to a type of service - in which case putting that event inside the services package (or the services package within that feature package) seems like a good idea. However - if you have cross-feature events, and you're using the structure, then you need any events which are going to be used within another feature to be inside the api package and not the restricted package. I tend to use this set up, so my events generally end up in the api package by feature, and if there is much in that package then I'll sub package them however I think best describes the dichotomy. Perhaps just in an eventspackage, or perhaps in `events / flow' etc. In the end, the first function of packages is to help the developer understand the relationships between the classes in the application. Any method that makes sense is viable IMO. Stray 2 Posted by Enrique on 10 Jun, 2011 04:27 PM Hi @Stray, I was thinking in your suggestion, but I think I can't get it :( I feel that I'm duplicating classes, or making a real spaghetti, maybe with an example is easier: I have an event ProductEventwith a type GET, this event is saved in root / [events] folder. When I dispatch ProductEvent.GETa command is executed and get productos from a service. Then the command updates the model, and the model dispatch another event: ProductModelEvent.UPDATED, I'm saving ProductModelEvent inside [model] / [events]. Then the user can change something in the view, and I need to update the model too. I need to dispatch an event from my mediator with the ProductVO, and that event should execute a command which updates the model. But what is this event?. a ViewEvent? [view] / [events] because is dispatched from mediator... a ModelEvent? [model] / [events] because is updating the model, and my ModelEvent has a "ProductVO" in it (as load). a CommandEvent? [events] because it executes a command and is similar to GET data. If I choose ViewEvent I feel that I'm messing the things, because I'm using ViewEvents for events dispatched from the view to the mediator. If I choose ModelEvent I feel that I'm messing the things, because I'm using the ModelEvents for events dispatched from the model. If I choose CommandEvent ( ProductEvent) then I need to add a load data to that event, that is not needed for example in ProductEvent.GET. So it feels like those events are not of the same class... And the data load that I need to add is the same data load that have my ModelEvent ( ProductModelEvent). So it feels like I'm repeating myself. And if I create a new CommandEvent, I feel that I will end with thousands of event classes with probably just one type. Even more, I don't know what name to use for that "new" event, ProductEvent2 ? Can you help to clear this mess? :( Support Staff 3 Posted by Stray on 10 Jun, 2011 08:25 PM Hi Enrique, I think first of all it would help to be more descriptive in naming your events. eg: Not ProductModelEvent, but ProductUpdateEvent Then I would choose names such as ProductRequestEvent(has no payload) and ProductCreatedEvent(when the data comes back from the service - containing the payload of the data.) It's ok to have a lot of different events. And the package you end up putting them in doesn't really matter. For myself - unless an Event is very clearly only for use in/by the view, or is very specific to the model or service that fires it, I just stick them in my controller package - not within model, view or service. If the nature of the Event is really different then I think it's better to have a new event than to make one event serve two purposes. The flash.events events are all messed up IMO. Stray 4 Posted by Enrique on 10 Jun, 2011 10:24 PM really? it's OK if I have a lot of different Event classes? I mean, do you have a lot of Event classes with just one string constant inside that class? I don't know, maybe there's nothing wrong with having a different class for each type of event. But I don't know, DRY is surrounding my mine... this is what I have now: ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// src / events / ProductEvent types: GET: dispatched by mediator executes command for retrieving data from the service (I'm listening the result in my command with a promise). EDIT: dispatched by mediator executes command for editing model with local data. data load: Array (used only in EDIT) src / model / ProductModelEventtypes: UPDATED: dispatched by model when data is setted EDITED: dispatched by model when data is edited data load: Array is your suggestion to change that to this?: ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// src / events / ProductRequestEventtype: REQUEST dispatched from mediator, executes command and retrieve data from service data load: none src / events / ProductEditEventtype: EDIT dispatched from mediator, executes command and edit model data load: Array // this is not changed: src / model / ProductModelEventtypes: UPDATED: dispatched by model when data is setted EDITED: dispatched by model when data is edited data load: Array ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// I just one to find some type of pattern or convention, so I don't need to think everytime if I need to write a new event, and how should it be called, and where should I save it (package), etc. And also if in a few days I need to find an Event I know where to search, and what name to search (approximately at least). More if I need to work in a team. Support Staff 5 Posted by Stray on 11 Jun, 2011 09:40 AM Hi Enrique, I have hundreds of events in my larger projects. An event represents a change in state / user action / application incident etc. Adobe gave us the rather rubbish String based event system. Many of us don't really trust this approach (where you can accidentally have two events with the same name) and so the Robotlegs event system is built on strong typed events. This means that the event class is the most important indicator of the purpose of an event, and then the String Event.SOMETHING_HAPPENEDconstants are sub-divisions of that event class. Naming events is hard - it will never be easy, so I'd just go with the most descriptive names you can think of, and make sure you have good refactoring tools :) My own naming-refactoring policy is that if I accidentally type or think something different from what I've currently named the variable, class or function, often this is a good indicator to change its name. For example - yesterday I was writing some code for a mosaic application. I had TileViewand one of the parameters was dimensions:Number. Then in my tests I automatically started writing tileSizeinstead of dimensionsand I realised that this was a better description. I would still rename ProductModelEventto ProductUpdateEvent- and also there's a convention that your type constants should be in past tense, so I would go with: Because these read like real conversation and less like code. But that's just my preference. In terms of where to put them, if you are worried about it then I would just put all your events in packages like this: This way if someone is looking for them then they are only going to be moving between one layer of folders. HTH Stray 6 Posted by Enrique on 11 Jun, 2011 03:11 PM Well, maybe I need to be less paranoid and to lose my fear about having hundreds of classes with just one type of event inside it. About using Past Tense, I was using irregular verbs for noting that an action is not made yet, if I follow your Past Tense rule the I have two events with the same name: I need to convert this: ProductEvent.EDIT(execute command for editing model) ProductModelEvent.EDITED(dispatched by model after edition) to just this? ProductEditEvent.PRODUCT_EDITED I think to have the events in the same folder is better (and make the separation with subfolders there). I just started in the other way because this article:... Maybe we need to change that :( Thanks @Stray ! 7 Posted by krasimir on 04 Sep, 2011 06:12 PM Hello, I think that it is better to put all the events in one folder. I mean, of course, you can create sub-directories for better organization but to store them in one place. For me, the good named event is better then the good file path (i.e. ProductsActionsEvent looks better then com.project.services.products.events.ActionEvent). Of course we can't generalize and just say what is right or wrong. It's more like a personal choice and project specifics. Usually my events are stored in com.project.controllers.events. Sometimes I prefer to add an additional parameter to the constructor of the class. For example: public class ProductEvent(type:String, data:* = null) { ... So if you have an event ProductEvent.GET you will discard the data parameter. If you have an event ProductEvent.UPDATED then you will use the "data" to send the updated information. Using that method you will not need to create a new event for every action. It just depends on your project. The workflow described above is not always useful. Sometimes is really wrong. Especially if you mix the responsibilities of your classes ;) Support Staff 8 Posted by Joel Hooks on 04 Sep, 2011 10:55 PM I disagree with this. I've seen what this approach leads to, and it is never pretty in a non-trivial app. I want my events (and all of my classes really) as close to their owner as possible. Events that are part of the model (announcing changes to the model) BELONG to the model, and not to the feature. The length of the package/namespace is completely aesthetic. If it is long because it is descriptive of where the event is owned, I favor clarity of looks every time. I'm a strident single TYPE event class user. Allowing arbitrary/optional arguments leads to conditional logic leads to muddled code and complete disregard for SRP. Event classes become dumping grounds for any marginally related behavior. I don't have a problem with many classes as much as I have a problem with classes that have too much responsibility or are not easily describable in terms of the behaviors they express. I don't want "this event is dispatch when something happens to x" - I want "this event is dispatched when z happens to x" - specificity. mmm So I end up putting the events package in the model/view/controller/service packages and evaluate where the event should be owned. It prevents the MONOLITHIC event packages that are hard to understand and provides clear cognitive separation between the events in a given functional area. 9 Posted by krasimir on 07 Sep, 2011 06:53 AM Hi Joel, good points. I'll use your advice in my next project ;) 10 Posted by visnik on 09 Sep, 2011 01:44 AM I jumped back and forth between placing all events in one package and placing them with their owner. After reading Stray's and Joel's book, I am fully convinced they should be placed with their owners. I am currently planning the package structure for a very large project, I will be using a events to their owner approach. My 2 cents Ondina D.F. closed this discussion on 16 Nov, 2011 09:19 AM.
http://robotlegs.tenderapp.com/discussions/problems/329-structure-and-pattern-for-events
CC-MAIN-2019-13
refinedweb
2,248
69.72
- Author: - yeago - Posted: - September 27, 2008 - Language: - Python - Version: - 1.0 - templatetag markdown wiki photologue - Score: - 2 (after 2 ratings) updated 12/16/08 I run several blogs by visual-artists and web-designers who want a quick way to insert images into their blog without the awkwardness of WSYIWYG and without the technicality of code (eww...). Thanks in advance for your input. #Syntax in a blog goes: [[thumb:the-image-slug]] # Gives you a thumbnail [[image:the-image-slug]] # Presents full-size-image Then of course: {% blog.post|yeagowiki %} You will also need to create some templates (see snippet). Here's a sample: <!-- /templates/photologue/image_snippet.html --> <div class="photologue-image"> <a href="{% if url %}{{ url }}{% else %}/media/{{ image.image }}{% endif %}"> <img src="{{ image.get_display_url }}" /> </a> <p class="photologue-image-caption">{{ image.caption }}</p> </div> More like this - load m2m fields objects by dirol 4 years, 10 months ago - really spaceless (trim spaces at line start) by wolfram 7 years, 3 months ago - Page numbers with ... like in Digg by Ciantic 6 years ago - Pagination Alphabetically compatible with paginator_class by vascop 2 years, 12 months ago - Paginator TemplateTag by trbs 7 years ago Please login first before commenting.
https://djangosnippets.org/snippets/1088/
CC-MAIN-2015-18
refinedweb
199
55.64
#include <stdio.h> #include <string.h> //| //| Exploit Title: [linux x86_64 Subtle Probing Reverse Shell, Timer, Burst, Password, multi-Terminal (84, 122, 172 bytes)] //| Date: [07/20/2016] //| Exploit Author: [CripSlick] //| Tested on: [Kali 2.0 Linux x86_64] //| Version: [No program being used or exploited; I only relied syscalls] //| //|================================================================================================================ //|===================== Why use Cripslick's Subtle Probing Reverse Shell?? ===================================== //| //| This is a very big upgrade sense my last probing reverse shell, so if you thought the last //| one was good for convenience, you will really like this one. The 3 main upgrades are. . . //| //| 1. There is a TIMER (VERY IMPORTANT!!!) //| This means that you won't be flooding yourself with a thousand probes a second. This is //| good because it is less CPU strain on the victim so the victim will less likly know something //| is up but MUCH more importantly it will more likely bypass the IDS. The last one would be //| sure to pop it (have a look at it in WireShark to know what I mean). //| //| 2. The byte count is lower. Upgrades such as not using Push+Pop or inc when moving one byte. //| //| 3. No Multi-Port because most of you won't be hacking your victim with multiple computers behind //| a NAT; this helps you because it will lower the byte count. Also note that you will still get //| a multi-terminal connection (every time your TIMER resets). //| //| 4. You can get a burst of Z probes up front (if you are ready beforehand) and then lower it to //| X probes later, at intervals of Y time so you don't awaken the IDS. Now you will have many claws //| on the victim without waiting hours (if set that long) for your new probes (backups) to come in . //| (A subtle scout makes for a silent killer) //| //| //| NOTE on Daemon: If you are using my Daemon C Skeleton, your shellcode will become a daemon //| and continue to run until you kill the PIDs or restart the victim's computer. //| //| //| Why can't you use a timer for the bind shell and keep it to one port? //| The reason is because the bind shell won't loose the process if you don't connect. Because //| of that, you would be placing more and more processes on the victim machine until you //| would DoS their system. With the reverse shell, the process dies as soon as you don't //| answer and that makes this an entirly different animal. //| //| ps. The bind-shell indentation was skewed for exploit-db. today. For all of you coders here is //| what you should know. exploit-db uses the notpad++ sytel indentation. If you send them a gedit //| formated document your indentation will be off for your comments. //| If you want a nice indented format of my multi-terminal bind shell plesae go to my website, //| and thanks for looking. //| //|================================================================================================================ //| //| ShepherdDowling@gmail.com //| OffSec ID: OS-20614 //| //| //| 10.1.1.4 = "\x0a\x01\x01\x04" #define IPv4 "\x0a\x01\x01\x04" // in forward-byte-order //| #define PORT "\x15\xb5" // in forward-byte-order //| #define PASSWORD "\x6c\x61\x20\x63\x72\x69\x70\x73" // in forward-byte-order //| python + 'la crips'[::1].encode('hex') //| #define TIMER "\x02\x01" //| in Reverse-Byte-Order //| convert hex to integer (not hex to ascii integer) //| Remmeber to comment out the TIMER sizes below that you are not using //| this example byte size \x10 = 16 seconds while word size \x02\x01 ~ 4 min //| #define BURST "\x05" //| BURST happens on the first cycle. This is how many probs you will get initially //| //| The BURST happens before the first long timer kicks in (the other is a set sec) //| If I didn't have the sec long timer (in the code) you wouldn't be able to accept //| all the incomming traffic and would loose probs. //| #define RESET "\x01" //| This applised to CODE3. The idea is to use the reset to stay in control without //| allarming the IDS (Burst to get what you need and then soft hits thereafter) //| example: Burst 5, reset 2, timer 3hrs //| 5 probs (3hrs) 2 probs (3hrs) 2 probs (3hrs) etc. //| This lets you get 5 terminals off the bat and if you loose connection you won't //| need to wait very long until the next backup probes come your way. //| This lets you connect even after your victim has the reverse shell launched //| The reason for the RESET is not be as aggressive as with the initial BURST. //| You don't want to trip any alarms, so good luck //|================================================================================================================ //|**************************************************************************************************************** //|================================================================================================================ //|=====================!!!CHOSE ONLY ONE SHELLCODE!!!========================= //| =========================================================================== //| CODE1 Single Probe Reverse Shell & no PASSWORD (84 bytes) //| =========================================================================== //| I'm sure that this is not the shortest reverse shell you have seen but it //| will pass my, "fill all registers test." If you don't know what I mean, //| look below at my C code. unsigned char CODE1[] = //| copy CODE2 Single Probe Reverse Shell with PASSWORD (122 bytes) //| ============================================================================= //| You may think, I know why I want a password on a bind shell but why a revrse //| shell? The answer is because you never know who may have access to your //| computer. This is is mainly for safty for that and from probe theft. unsigned char CODE2[] = //| copy CODE3 Subtle Probing Reverse Shell + BURST + TIMER + RESET + Pass (172 bytes) //| ============================================================================= //| You can only use a byte, word (2 bytes) or dword (4byte) timer. It doesn't //| matter what you use but you must comment out what you don't use. In most //| cases you will use the word size going from 4 min to 18 hrs. //| The defaul is \x02\x01 (in reverse byte order) translate = 102 in hex //| Thats ~ 4mins in hex (F0 = 4min exact) unsigned char CODE3[] = //| copy CODE3 and use it below <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< "\x48\x31\xdb\xb3"BURST"\x48\x31\xff\x48\xf7\xe7\x48\x31\xf6\xb0\x39\x0f\x05\x40\x38" "\xf8\x74\x77\x48\x31\xf6\x48\xf7\x\x48\xff\xcb\x38\xc3\x74\x05\x50\x6a\x01\xeb" //| ATTENTION!!! COMMENT OUT THE TIMERS YOU ARE NOT GOING TO USE //| BYTE size Timer // "\x05\xb3"RESET"\x50\x6a"TIMER"\x54\x5f\xb0\x23\x0f\x05\xe9\x5b\xff\xff\xff" //| WORD Size Timer "\x07\xb3"RESET"\x50\x66\x68"TIMER"\x54\x5f\xb0\x23\x0f\x05\xe9\x59\xff\xff\xff" //| DWORD Size Timer (It can't go above "\x77\x77\x77\x77") // "\x08\xb3"RESET"\x50\x68"TIMER"\x54\x5f\xb0\x23\x0f\x05\xe9\x58\xff\xff\xff ; //|================================ VOID SHELLCODE ===================================== void SHELLCODE() { // This part floods the registers to make sure the shellcode will always run __asm__("mov $0xAAAAAAAAAAAAAAAA, %rax\n\t" "mov %rax, %rbx\n\t" "mov %rax, %rcx\n\t" "mov %rax, %rdx\n\t" "mov %rax, %rsi\n\t" "mov %rax, %rdi\n\t" "mov %rax, %rbp\n\t" "mov %rax, %r10\n\t" "mov %rax, %r11\n\t" "mov %rax, %r12\n\t" "mov %rax, %r13\n\t" "mov %rax, %r14\n\t" "mov %rax, %r15\n\t" "call CODE3"); //1st paste CODEX<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> } //|================================ VOID printBytes ==================================== void printBytes() { printf("The CripSlick's code is %d Bytes Long\n", strlen(CODE3)); //2nd paste CODEX<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> } //|================================ Int main =========================================== int main () { int pid = fork(); // fork start if(pid == 0){ // pid always starts at 0 SHELLCODE(); // launch void SHELLCODE // this is to represent a scenario where you bind to a good program // you always want your shellcode to run first }else if(pid > 0){ // pid will always be greater than 0 after the 1st process // this argument will always be satisfied printBytes(); // launch printBYTES // pretend that this is the one the victim thinks he is only using } return 0; // satisfy int main system("exit"); // keeps our shellcode a daemon }
https://www.exploit-db.com/exploits/40139/
CC-MAIN-2016-50
refinedweb
1,269
72.5
I. Packages A. What they are: Packages provide a way of grouping together a set of related classes as one unit 1. Packages act like a module in that they provide access control mechanisms (more on this in a moment) 2. Packages help partition the name space so that names can be re-used within different packages B. Defining a package a. Use the package keyword to indicate that a class belongs to a certain package b. The package statement must be the first executable statement in a file c. Packages can be nested. If they are nested, then you separate a package name from the one above it by a period. Example: package silhouette; package silhouette.shapes; package silhouette.shapes.boxobjects; C. Importing Packages 1. Use the import keyword to access a public class from another package. a. Specifying the name of a class will import that class only b. Specifying an asterisk (*) after a package name will import all public classes from that package example: import java.util.LinkedList -- makes the LinkedList class accessible import java.util.* -- makes all public classes in java.util accessible c. The import statement places the classes returned by the statement into the namespace of the current file. A namespace is the set of names that are defined in the current scope. A scope is a block of code within which a set of names are valid. A scope can be a file, a class, a method or a block. d. You can also access a class in a different package without importing it. To do so you provide the fully qualified package name for the class. For example: java.util.LinkedList myList = new java.util.LinkedList(); You might decide to use the fully qualified name if importing the name would cause a conflict with either a name declared by your class or with a name imported from another package. 2. import statements should go immediately after a package statement and should precede other executable statements in your file. 3. Java's libraries are contained in packages. a. In C++ you use #include's to include system-defined libraries in your program b. In Java you use import statements to include system-defined libraries in your program Example: C++ Java #include <stdio.h> import java.io.*; C. How Java finds classes and CLASSPATH a. The directory containing a package must have the same name as the package b. All classes belonging to the package must be placed in the package's directory c. How Java locates class files i. By looking at directories beneath the current directory ii. By examining the set of directories specified by the classpath flag to the java interpreter or compilerjavac -classpath .:..:/Users/bvz/silhouette chess.java java -classpath .:..:/Users/bvz/silhouette games.chessUsing this classpath flag, Java will search the current directory, the directory above the current directory, and /Users/bvz/silhouette for the names of package directories. When I execute games.chess, then games must be a subdirectory in one of the current directory, the current directory's parent, or /Users/bvz/silhouette. iii. By examining the set of directories specified by the CLASSPATH environment variable Example: setenv CLASSPATH .:..:/Users/bvz/silhouette The advantage of the CLASSPATH environment variable is that I don't have to specify the -classpath flag every time I compile or execute a java file. d. When executing a java class, the class must be prefixed by its full package name Example: java silhouette.shapes.boxobjects.rectangle D. Member Access Private Package Protected Public Member Member Member Member Visible within same class Yes Yes Yes Yes Visible within same package No Yes Yes Yes by subclass Visible within same package No Yes Yes Yes by non-subclass Visible within different No No Yes Yes package by subclass Visible within different No No No Yes package by non-subclass
http://web.eecs.utk.edu/~bvz/teaching/cs365Sp15/notes/java-packages.html
CC-MAIN-2017-51
refinedweb
645
57.77
My Python Toolbox After a recent Christchurch Python meetup, I was asked to create a list of Python libraries and tools that I tend to gravitate towards when working on Python projects. The request was aimed at helping newer Pythonistas find a way through the massive Python ecosystem that exists today. This is my attempt at such a list. It's highly subjective, being coloured by my personal journey. I've done a lot of Python in my career but that doesn't mean that I've necessarily picked the best tool for each task. Still, I hope it's useful as a starting point (I don't think there's any big surprises here). Black Many programming language communities are waking up to the fact that having a tool which takes care of code formatting for you is a productivity booster and avoids pointless arguments within teams. Go can take much of the credit for the recent interest in code formatters with the gofmt tool that ships with the standard Go toolchain. Rust has rustfmt, most JavaScript projects seem to prefer prettier and an automatic formatter seems to now be de rigueur for any new language. A few formatters exist for Python but Black seems to be fast becoming the default choice, and rightly so. It makes sensible formatting decisions (the way it handles line length is particularly smart) and has few configuration options so everyone's code ends up looking the same across projects. All Python projects should all be using Black! argparse Python has a number of options for processing command line arguments but I prefer good old argparse which has been in the standard library since Python 3.2 (and 2.7). It has a logical API and is capable enough for the needs of most programs. pytest The standard library has a perfectly fine xUnit style testing package in the form of unittest but pytest requires less ceremony and is just more fun. I really like the detailed failure output when tests fail and the fixtures mechanism which provides a more powerful and clearer way of reusing test common functionality than the classic setup and teardown approach. It also encourages composition in tests over inheritance. pytest's extension mechanisms are great too. We have a handy custom test report hook for for the API server tests at The Cacophony Project which includes recent API server logs in the output when tests fail. csv So much data ends up being available in CSV or similarly formatted files and I've done my fair share of extracting data out of them or producing CSV files for consumption by other software. The csv package in the standard library is well designed and flexible workhorse that deserves more praise. Dates and times The standard datetime package from the standard library is excellent and ends up getting used in almost every Python program I work on. It provides convenient ways to represent and manipulate timestamps, time intervals and time zones. I frequently pop open a Python shell just to do some quick ad hoc date calculations. datetime intentionally doesn't try to get too involved with the vagaries of time zones. If you need to represent timestamps in specific timezones or convert between them, the pytz package is your friend. There are times where you need to do more complicated things with timestamps and that's where dateutil comes in. It supports generic date parsing, complex recurrence rules and relative delta calculations (e.g. "what is next Monday?"). It also has a complete timezone database built in so you don't need pytz if you're using dateutil. plumbum Shell scripts are great for what they are but there are also real benefits to using a more rigorous programming language for the tasks that shell scripts are typically used for, especially once a script get beyond a certain size or complexity. One way forward is to use Python for its expressiveness and cleanliness and the plumbum package to provide the shell-like ease of running and chaining commands together that Python lacks on it's own. Here's a somewhat contrived example showing plumbum's command chaining capabilities combined with some Python to extract the first 5 lines: from plumbum.cmd import find, grep, sort output = (find['-name', '*.py'] | grep['-v', 'python2.7'] | sort)() for line in output.splitlines()[:5] print(line) In case you're wondering, the name is Latin for lead, which is what pipes used to be made from (and also why we also have plumbers). attrs Python class creation with a lot less boilerplate. attrs turns up all over the place and with good reason - you end up with classes that require fewer lines to define and behave correctly in terms of Python's comparison operators. Here's a quick example of some of the things that attrs gives you: >>> import attr >>> @attr.s ... class Point: ... x = attr.ib(default=0) ... y = attr.ib(default=0) ... >>> p0 = Point() # using default values >>> p1 = Point(0, 0) # specifying attribute values # equality implemented by comparing attributes >>> p0 == p1 True >>> p2 = Point(3, 4) >>> p0 == p2 False >>> repr(p2) # nice repr values 'Point(x=3, y=4)' There's a lot more to attrs than this example covers, and most default behaviour is customisable. It's worth nothing that data classes in Python 3.7 and later offer some of the features of attrs, so you could use those if you want to stick to the standard library. attrs offers a richer feature set though. requests If you're making HTTP 1.0/1.1 requests with Python then you should almost certainly be using requests. It can do everything you need and then some, and has a lovely API. As far as HTTP 2.0 goes, it seems that requests 3 will have that covered, but it's a work in progress at time of writing. pew Effective use of virtual environments is crucial for a happy Python development experience. After trying out a few approaches for managing virtualenvs, I've settled on pew as my preferred tool of choice. It feels clean and fits the way I work. That's what is in my Python toolbox. What's in yours? I'd love to hear your thoughts in the comments.
https://menno.io/posts/my-python-toolbox/
CC-MAIN-2021-21
refinedweb
1,052
70.33
Originally posted by Saritha ventrapragada: My problem is I am not sure how to define and use these namespaces. Dose it has got something to do with location where my schema reside. How both are linked?. Originally posted by Saritha ventrapragada: My doubt is schemaLocation attribute. I guess validator look for the schema file using the namespace URI and schema URI that I give in schemaLocation attribute. Please correct me if I am wrong. I am guessing that the errors are due to validator not being able to locate the schema file. As the validator I am using is on the web. I am uploading xml and xsd file into the this site I guess that validator is looking for report.xsd file in localhost which it can never find. Please let me know if my understanding is wrong. I really appreciate all your patience with me and thank you very much for helping me saritha Originally posted by Saritha ventrapragada: when elementFormDefault=unqualified, then all the elements are localized and there is will be no requirement to explicitly qualify them, hence I thought I am good with not declaring that element. Not really. While your understanding is correct, what you missed here is the concept of default namespace. When you don't qualify an element with a prefix, it is considered to be in the default namespace. Hence, based on your original code you had Report xmlns="" This becomes your default namespace. Hence, all unqualified elements are assumed to belong to this namespace. But based on the way you defined the schema and the targetNamespace, they are not part of the namespace. Hence the problems. Why do the local elements do not come under targetnamespace when their parent element is? That's by definition of the XML Schema recommentations. Even when i gave value of highlight="yes" than "true" i was getting same error. The errors were because of the namespace. Once, the element was properly defined, then it looked at the definition of the attributes for the element in that namespace and so the attribute highlight was then validated to be wrong according to the definition given in the schema. I would really appreciate if you could suggest me some good URL's to understand all these concepts correctly. I think you need to understand two concepts really to solve this. 1. Namespaces in XML. 2. Namespaces in XML Schema. Not sure how useful this link is. Another article in Namespaces. There was another link on namespace Faq, can't locate it at the moment. Also, Definitive XML Schema by Priscilla Walmsley, book talk a lot about this topic. Thanks. - m Error at (38,14): The 'hightlight' attribute is not declared. An error occurred at , (38, 14). <ReportData hightlight = "true"> <Data>123456</Data> <Data>12/04/2004</Data> <Data>KSDF</Data> <Data>CSDK</Data> <Data>10000</Data> </ReportData> Schema declaration <?xml version="1.0" encoding="iso-8859-1"?> <xs:schema xmlns: <xs:element <xs:complexType <xs:attribute <xs:attribute <xs:attribute <xs:attribute <:complexType> <xs:complexType <xs:sequence> <xs:element </xs:sequence> </xs:complexType> <xs:complexType </xs:complexType> <xs:complexType <xs:sequence> <xs:element <xs:element <xs:element <xs:element <xs:element <xs:element <xs:element <xs:element <xs:element </xs:sequence> </xs:complexType> </xs:schema>
http://www.coderanch.com/t/127102/XML/namespace
CC-MAIN-2014-10
refinedweb
548
57.16
#include <sw_types.h> #include <sw_debug.h> #include <sw_list.h> #include <sw_buddy.h> #include <sw_mem_functions.h> Returnd the ID of the current task.. Gets the pointer size of the allocated block of memory. function to get the size of a pointer. This is needed during realloc allocates memory at the requested heap index for size bytes Prints the state of the heap allocations Whether heap is found for this task Heap size, no. of free and allocated blocks. Gets the task_id and frees the heap memory corresponding to the task_id. Frees the privately allocated memory pointing to the heap_id and the address pointer. Heap memory initialization. Gets the task id and allocates memory in the heap memory corresponding to the task. Allocates memory privately for size bytes at the memory related to heap_id passed.
http://www.openvirtualization.org/documentation/sw__buddy_8c.html
CC-MAIN-2018-39
refinedweb
133
62.24
Working at a bank, I get to play with an iSeries a lot. I've been trying to build a data warehouse that uses day old data from the iseries and importing the data into a MS SQL database. I was able to do a data import using SSIS but I started to think about about how to do this in code. It was pretty easy! First getting the data out of the iSeries/AS400. You have to install the latest IBM data provider. You get this when you install IBM's programmers toolkit. After you install the toolkit, add the reference to your project; IBM.Data.DB2.iSeries. using IBM.Data.DB2.iSeries; To read data out of IBM is almost the same as any other SQL statment with the expection of the table name. IBM uses libraries so your select statment has to have the library name in the from line - not a big deal; The select statement is the same but your from statement has to point to the library and the table. The rest is the same, make a connection object, comman object and a data adapter. string sql = "SELECT * FROM LIBRARY.TABLE "; iDB2Connection conn = new iDB2Connection("DataSource=ibmserver.mydomain.com;userid=user;password=xxx"); iDB2Command cmd = new iDB2Command(sql, conn); cmd.CommandType = System.Data.CommandType.Text; iDB2DataAdapter myCommand = new iDB2DataAdapter(cmd); myCommand.Fill(TempDS, "SQLStatement"); TempDS.DataSetName = "SQLStatement"; Creating a table using SMO is pretty easy, You make a server object, a database object and a Table object. Then read through the columns to make the data types. In this example I make all of them VarChar(50). You should send the data column to an object and set the datatype in the object. SqlConnection connection = new SqlConnection(connectionString); Server server = new Server(new ServerConnection(connection)); Database db = server.Databases["MyDataBase"]; Table table = new Table(db, "MyTable"); for (int i = 0; i < DT.Columns.Count; i++) { Column c = new Column(table, DT.Columns[i].ColumnName); c.DataType = DataType.VarChar(50); table.Columns.Add(c); } table.Create(); That is it - pretty simple. Now just read through your data table and insert the data to your new table.
http://geekswithblogs.net/kenl/archive/2008/11/23/iseriesas400-db2.aspx
crawl-002
refinedweb
361
58.69
Fun with URL Encodings. Uri.EscapeUriString- 99 out of 100 developers agree you should pretty much never use this method. Use EscapeDataStringinstead. Uri.EscapeDataString- This method is the jam for encoding a full URL or the path portions of the URL. HttpUtility.UrlPathEncode- The docs literally say “Do not use; intended only for browser compatibility.” UrlEncoder- This class has methods for reading and writing from text writers and spans for high performance low allocation scenarios. Programming is so easy, isn’t it! How did we get in such a situation? I think XKCD summarized it best, Just replace “Standards” with “Ways to encode a URL.” To be fair, some of these options are there because of different scenarios in which you need to encode some or all parts of a URL. And I believe the last option is a result of progress! I assume UrlEncoder is a result of the .NET Core team’s war on allocations and extreme focus on the performance of the stack. How to choose A while back, Leon Bambrick (aka the SecretGeek) wrote a post with at table of the various encoding methods and the result of the method. It does not include UrlEncoder.Default.Encode which didn’t exist at the time, so maybe get on that Leon. My scenario This might not be obvious, but I don’t randomly write about coding minutiae out of a deep seated desire to be pedantic. Ok, that might not be entirely true, but this time, it is. I’m covering this, of course, because my lack of understanding of these nuances lead to a bug in my code. IN MY CODE! Yeah, I know, it defies imagination. My scenario involves file uploads, markdown rendering, and a lot of whiskey for debugging purposes. It’s a “fun” one. The asp.net core app I’m building allows user to drag and drop an image over a textarea in order to upload the image. In response, the textarea renders a markdown image reference to the uploaded image. If you’ve used GitHub issues, you’ve seen this interaction before. I wrote the code, shipped it, and celebrated by high-fiving my coworker, which is awkward, because I work alone and high-fiving myself is not as cool as it may sound at first. Everything was hunky dory until a beta-tester friend of mine noticed her images weren’t rendering properly. After some digging, I realized it was because her images have spaces in them. An obvious PEBKAC issue, case closed. But I like this friend and people have a right to have spaces in their image filenames. So I decided not to be so user hostile and dig into it. Markdown rendering The first issue has to do with Markdown rendering. Say you upload an image named cool image.png ( uncool image.png works as well, but is not as cool). The resulting markdown might look like (xyzver5 is a random sequence to prevent collisions): Unfortunately, Markdig doesn’t render that as an image. That’s because Markdig is a goody two-shoes and accurately follows the CommonMark Spec. The spec specifically which does not allow spaces for link destinations. No problem, I naively thought, I’ll just use my old standby, HttpUtility.UrlEncode for the filename. Now it renders fine. On the back end though, I don’t allow direct access to these images for security reasons. Instead, I route them through a controller with a wildcard route. [Route("[controller]")] [Authorize] public class ImagesController { [HttpGet("{**name}")] public async Task<ActionResult> Get(string name) { // name will be `xyzver5/cool+image.png` // Some beautiful code to retrieve the image by name from the // back-end store which could be S3, Azure Blob Storage, or a // junk drawer under your bed. } } Note that I’m using wildcard routing here because I want the entire path after the /images/ part of the image URL. I tested it locally, it worked like a charm. Shipped it! I deployed it to Azure App Service and called it a day, spiked my laptop in the endzone, and celebrated another successful deployment. Works locally, not in production Until I later tested it myself in production and realized it was still not working. I was dumbfounded because my code passed the “Works on My Machine” certification program. I dug into it, ruled out possible differences, and discovered that my code wasn’t even being called in production for this image, but worked fine for others. So what was the difference between the two environments? Ah! On my local machine, I’m running on Kestrel. But when I deploy, Azure App Service runs my site on IIS in front of Kestrel. It turns out that the culprit was IIS Request filtering. By default, request filtering blocks URLs with plus signs + in the non-query portion of the URL (query string is fine). Why? Because it could result in a security issue: Some standards, e.g. the CGI standard require +’s to be converted into spaces. This can become a problem if you have code that implements name-based rules, for example urlauthorization rules that base their decisions on some part of the url. Probably not an issue for my scenario and I could just modify this rule, but one of my coding philosophies is to try and not work against the system as much as possible. In my younger days, I’d customize the heck out of everything. Now I don’t have time for all that malarkey. The solution was simple, I needed a url encoding method that used %20 instead of + to encode spaces. After some research, I used Uri.EscapeDataString and that did the trick! But first, I had to make sure to avoid using its evil sibling, Uri.EscapeUriString which by most accounts is pretty useless in comparison to its smarter and better looking sibling. And now it works correctly! Yay me! What about UrlEncoder? I just learned about this class and I bet it would work great too. The place where I’m doing the encoding isn’t a hot spot so it’s not a big concern for me to optimize that path at the moment. The Moral of the Story There’s probably a lot of lessons I could learn from this experience if I paid attention. - Test in production after deployment. Even better, minimize differences between dev and production environments. Containers might be useful here. - Being a developer requires being a bit of an anthropologist and realizing the libraries you use evolve as everyone gains experience. So it helps to understand why there are six or more ways to url encode a string. - Coding is tricky, but still fun when you learn something. Happy coding! 4 responses
https://haacked.com/archive/2019/12/09/fun-with-url-encodings/
CC-MAIN-2021-21
refinedweb
1,129
65.93
Since. Background. Languages. Requirements and installation Deployment options. Caching. Setting up a project. Adding models. Interaction with the Database. Projects and Applications. Controllers and URLs. Templating. Administration and User management. So which is right for you?. 61 Responses to “A comparison of Django with Rails” Python is already mimicking Ruby Gems, in the form of “Python Eggs”: Good post. I’ll be familiarizing myself with Django next. [snip]If you are developing a simple (in a domain model sense) application where you want to use Ajax to deliver a great UI, Rails is probably for you.[/snip] Huh? So if I’m developing a complex (in a domain model sense) application, django is the way to go? You make this assertion, but offer nothing in the article to back it up. Are you spreading FUD or making a valid comment? Regarding FCGI and lighttpd: there are already descriptions online how to use django with FCGI and lighttpd and various other WSGI hosts (FCGI+Apache, Twisted, TooFPy) at the server arrangements page in the wiki. Thanks for the excellent, fair writeup. Clearly I’m biased, as I’m a Django developer, but I’d say Django is equally suited for “simple (in a domain model sense) applications” as it is for “an entire site with different types of applications within it.” For instance, I’m using Django to power chicagocrime.org, which is “simple” in that it’s a single application, and the system works equally well there as it does on Lawrence.com, which is *very* complex. Also, adding support for other databases in Django is as easy as adding a single Python module in a directory. (Granted, Oracle has some peculiarities that make it more complex than that, but other RDBMSes have fit into this quite nicely.) We’ll certainly be adding support for more databases as soon as we can. > The only minor annoyance is that there is > no equivalent of a model-specific SQL > refresh – something that could drop > a specific model’s tables and regenerate > the needed SQL automatically. For this, use “django-admin.py sqlreset [appname]“, and pipe that output into your database system, like so: django-admin.py sqlreset polls | psql myproject It’s intentional that there isn’t a command that does this automatically. My thinking was that Django *shouldn’t make it easy to delete data*. Adding something such as “django-admin.py reset [appname]” would be stupidly easy, but I’ve hesitated because I’m very protective of data. That said, we’re open to ideas on how to solve both problems. Thanks again. Adrian Thanks for the great article; I’ve put my feedback “on my site”: . Over the entire comparison I felt a spin in favor of Django, and it becomes a poor favor to it, ends up sounding like “don’t look at rails doooon’t.” maybe is just me but the frameworks appear to reflect the underlying language “way” and this leads to some of the framework’s approaches,lastly, no doubt Django will be able to retain many pythonists from goin Ruby, but I doubt it’ll atract Rubyists. yes I’m biased, but I think so are You. Wouldn’t a link to both “Django”: and “Rails”: have been appropriate ? Disappointed Wrote: bq. Huh? So if I’m developing a complex (in a domain model sense) application, django is the way to go? You make this assertion, but offer nothing in the article to back it up. Are you spreading FUD or making a valid comment? Well I do touch on this – management of your domain model is easier with Django as it doesn’t split up you domain model definition between code and DB schema like Ruby – therefore making it easier to manage. To be honest neither approach (Django or Rails) is going to manage a complex domain too well as the coupling to the DB is perhaps a little to tight. One problem with Django is that it is more difficult to handle customization. For example, I released a hospital scheduling system to my customers. Some customers need to add a custom column to one of the form.. biased wrote: bq. yes I’m biased, but I think so are You. Erm, not really. I say at the end: bq. Personally, given my own current projects I’ll be spending some more time with Django – but all that means is that it is one more tool that will sit alongside Ruby, Rails and J2EE in my particular toolbox. Meaning that it’s a classic case of right tool for the job. I think there are some things Rails is good at due to the place it came from (good UI, simple domain web applications) and some things django is good at (more passive UI, portal-type apps). I’ve actually spent more time working with Rails (at Ruby) as you’d know if you’d read much of the rest of my posts. This article was sent to both Django developers and Rails developers for feedback, and none of them complained of any apparent bias. The only bais that I have to Django right now is because the stuff I’m working on fits Django better than Rails. François – good call on the links, I’ve added them in. Chong wrote: bq.. I’m not sure why it should be any different. If you add the column to the DB in Rails, unless you are using the scafolding you won’t get the view for free (e.g. the new field won’t appear on your forms unless you specifically code for it). I’d be suprised if _anyone_ would use the scaffolding view for a production application – it’s not really what they’re designed for. With Django, you’d have to change your domain model (which _is_ correct in my mind – if a domain model has a new attribute you need to change your code). Then you’ll have to migrate/refresh your DB schema. Then you’ll have to build your view code for the new field (assuming this field is visible to more than just the admin interface). With Rails the change is virtually the same – update the DB schema, migrate/refresh the DB, update the view. The difference is that with Rails you edit the DB schema by hand, in Django you edit the model file by hand and have it generate the schema. I prefer schema generation for reasons given above (and there is no reason why Rails can’t support it to, didn’t it used to?) – although once you have your DB in production every schema change needs to be carefully thought about. I don’t think schema generation was or will be a part of Rails, it goes against DRY — at least that’s how I recall a discussion about it long ago on the list ending up. I think this split (diff approaches to model tier) might actually be a deciding factor for some people between the 2 frameworks, depending on if they’re mostly dealing with legacy DBs or can create their own Rails-ish ones, or vastly prefer one approach over the other. I’m interested in your comments about Django’s ability to reverse-engineer models from existing schemata. What’s your source for this? I am keen to understand more. I would love to only deal with fresh green field developments but life’s not always like that… ’ve regressed to the bad old days of Perl.” I’m guessing that by “third type of parenthesis” you mean the different block syntax(?). Funny, most people seem to like Ruby’s block syntax. Or I’m missing something. As for cleaner syntax, well, I guess it depends on if you prefer a few ampersands or a lot of underscores. Dan Chris: See for information on how to create a model dynamically by introspecting a pre-existing database table. Rails does indeed support other caching backends: “”: Memory, File, DRb and Memcached This is one of the most objective review I’ve ever read. The author clearly is not talking out of the blue. He dissected the pros and cons appropriately. Heck, I even agree with most of his cons on Python (I just wish the link to the term “closure” is working because I’m itching to know what the author meant by Python not having as strong a language feature than Ruby. But this is minor because this language is not comparing Python and Ruby). To me, if RoR doesn’t offer the generated Admin web pages a’la Django (plus the user/group management to boot), then RoR is not for me (at least not for my current project). But I am *very* intrigued that RoR provides Ajax support. One thing about django, that users or potential users need to know especially if you guys are using Postgresql. Django produces SQL code that create tables that consumes OIDS. In most cases, this is not the desired effect because OIDS are unique per installation and *will* wrap around. Although django applications will not use these OIDS, every insert will unnecessarily consume an OID. Remember OIDS are used by Postgresql’s system tables (it still irks the heck out of me that they made WITH OID the default behavior with no way to change it). To counter this, I had to insert the string WITHOUT OIDS at the end of each CREATE TABLE. I fixed the link to “closure”:. Todd wrote: bq. I don’t think schema generation was or will be a part of Rails, it goes against DRY I’m not sure how this goes against DRY – the python model source is the single source of information for the domain model. Chris Esther wrote: bq. I’m interested in your comments about Django’s ability to reverse-engineer models from existing schemata. What’s your source for this? “Matt Croydon”: has a good overview on this. “Jacobs”: post also touches on this. Michael Schubert wrote: bq. Rails does indeed support other caching backends Great links – thanks Michael. Anoyed Obie and Jon didn’t pick that up when they reviewed the article Jondom wrote: bq. I fixed the link to closure. Fixed in the main article – thanks Jomdom and Dmitry for picking this up Both Django and Rails seem to be really nice framworks to develop with. And really a pleasure to use compared to the java MVC frameworks for which development time is skyhigh. At the moment Rails seems more mature in that it supports filters (like Servlet filters) and has a very easy way to make it impossible to not accept POST data to populate certain fields of an object. (For example if a User has the flag isAdmin, in Rails you could mark the Field isAdmin to be only settable through direct assignment, and not automagically populated by provided POST data) Django has the advantage that it is written in Python, for which alot more custom libraries are available. At the moment i prefer Rails, for the reasons mentioned above, plus DOCUMENTATION.. Django has decent documentation, bt Rails has a very nice book, explaining everything. This makes working with rails a lot easier compared to using Django, while i’m a ruby newbie, and have some expertise with python. Now i don’t need a book, but a complete manual for Django, with the explantaion of an example apllication would sure be nice) But as Django is under heavy development, and i’m sure they’re learning from Rails (and probably the other way around) I think in half a year from now both frameworks might share the same usefull (and less usefull) features (Or atleast the features i mentioned, maybe they’re even already there in Django, but undocumented as of yet) bq. I fixed the link to closure. This is slightly off-topic, but the mention of closures in this comparison led me to post an “invitation for practical closure examples”: and I mention a few links on the subject. I’m still looking for a practical closure examples that do something that “list comprehensions”: can’t. Sam, re: schema generation and DRY and Rails, as I mentioned, my recollection was hazy. Here’s the thread: Generating SQL from model and not vice versa I guess it was sort of an inconclusive discussion… the general approach (model derived from DB) seems to have been what DHH found worked best in his experience. He mentions future code in that thread which became Migrations, which might be workable for this issue, I’m not sure: “I don’t think schema generation was or will be a part of Rails, it goes against DRY, at least that’s how I recall a discussion about it long ago on the list ending up.” Rails currently offers ‘migrations’, code that helps you create DB schema using Ruby. It is intended, I believe, mainly as a helper tool to get identical tables created across multiple databases. “Nitro”: is another Ruby Web framework that, as with Django, derives the database schema from Ruby class definitions, an approach that is often a better mach for my deveopement style. There is work being done to allow mixing and matching of MVC libs from both Nitro and Rails, so people can have more options. ToddG wrote: bq. Sam, re: schema generation and DRY and Rails, as I mentioned, my recollection was hazy. Here’s the thread: Thanks for that. Interesting that in that thread someone else claims it violates DRY, when in fact I think the reverse is true, especially if you need to support multiple DBs. James Britt wrote: bq. Nitro is another Ruby Web framework that, as with Django, derives the database schema from Ruby class definitions, an approach that is often a better mach for my deveopement style. Had a quick look at Nitro, but didn’t see that it also generated the DB schema. And thanks to both of you for the links to Migrations… bq.. bq. It would be nice to think that one day a language will come along which manages to add powerful features without making the code look like it’s been rendered with the wrong character encoding. Careful. You are asking for Lisp. Aristotle Wrote: bq. I never understood why companies hire technologies instead of people. I agree, but it happens. It’s also important to note that development in dynamic languages probably requires a more mature development process than statically typed languages – if you want to tie yourself in knots, it’s _much_ easier to do it with a dynamic language like Ruby Python – so testing becomes more important. Put another way, if your developers have trouble writing easy to understand, clean maintainable statically typed Java/.NET code, don’t expect the situation to be any better with Python on Ruby – in fact I’d expect the reverse to be true! bq. Careful. You are asking for Lisp. I really hope that was a joke bq. if your developers have trouble writing easy to understand, clean maintainable statically typed Java/.NET code, don’t expect the situation to be any better with Python on Ruby That’s true — but if they’re _incapable_ of writing clean code rather than just not experienced enough to do so, you have more serious problems… And if they’re only inexperienced, you hopefully have a few senior developers to take them in for apprenticeship, or you’ll _still_ have more serious problems… Their code may not _look_ unreadable in Java, but it will still be incomprehensible and unmaintainable. You can’t abstract human understanding out of the process. Bottom line as I see it, hiring a technology, particularly the “industry standard,” is at best a recipe for languishing in mediocrity. It won’t make you sink, by any stretch, but it certainly won’t get you to any top either. bq. I really hope that was a joke It was… _mostly_. >). This whole paragraph is completely useless and very poor on details to the point of being misleading and clearly wrong. A closure is just a function that has access to the enclosing namespace. There’s no way you can have more powerful or less powerful ones. If you refer to being able to pass a block/lambda to a function or stuff like this you are clearly wrong. While functions/methods in ruby are not first class citizens they are in python. This loosens quite a lot the need for anonymous blocks since you can easily use named functions passed. I can’t get how python is missing mixins. Do we all agree on what a mixin is? The real thing is Ruby that lacks multiple inheritance (that permits all the mixins you might ever need and even more) and replaced this lack with “mixin”s. And I would also like to know how ruby object oriented support is cleaner. Everything is an object in python, you can do whatever you want with anything (also subclassing builtin types directly). Really… It is not like that these 2 languages are any different in terms of potential. You could have talked about the fact that ruby allows you to change the behaviour of built-in types, while python doesn’t. That ruby has a full implementation of blocks, while python has a limited (intentionally) implementation of lambdas and many other differences, but you didn’t. BTW: my aim is not to start a flamewar. I’m just fed up with people repeating this stuff each day… Can’t you just avoid comparing python and ruby? They are pretty much equivalent as you state as well. Valentino wrote: bq. A closure is just a function that has access to the enclosing namespace. There’s no way you can have more powerful or less powerful ones I have clearly over simplified. Here is some constructive feedback I was given on this very point (although not on this blog): bq. Python does have support for full closures (see Ivan Moore’s articles here: and here: ) but it has broken lambdas which can only be used for expressions and can’t contain a return. As Ivan points out in the second of the articles I mentioned you can get around this by defining a function inline and using that. But it’s not as neat as the usual one-line examples of closures that everybody else uses. It’s one of the reasons why I’d like to see lambdas either fixed or removed. bq. The real thing is Ruby that lacks multiple inheritance (that permits all the mixins you might ever need and even more) and replaced this lack with mixin’s. So you claim that multiple-inheritence is _more_ powerful than mixins. I disagree. On balance, I actually disagree with my point about mixins being _more_ powerful than multiple-inheritence. Functionlly, they are two different ways of accomplishing the same thing. I prefer mixin’s because (to quote the “c2wiki”:) “no semantics will be implied about the child “being a kind of” the parent”. Of interest, what can you do with multiple inheritence that can’t be done with mixins? bq. And I would also like to know how ruby object oriented support is cleaner. Err – can you name another language which claims to be OO and then requires you to pass @self@ in everywhere? OO was an afterthought with Python. Clearly it hasn’t been tacked on as badly as in Perl, but in a language which so badly wants to be seen as being cruft free with a nice syntax, this sticks out like a sore thumb. That and the underscores. I find it interesting that you comment on a single part of the fuller article, of which I myself said: bq.. Do you have any comments on the rest of the piece? I’m all for constructive criticism – that’s why these comments are here. > I have clearly over simplified. Here is some constructive > feedback I was given on this very point (although not on > this blog): [snip] > But it’s not as neat as the usual one-line examples of > closures that everybody else uses. It’s one of the reasons > why I’d like to see lambdas either fixed or removed. This is exactly what’s wrong in what you said. The concept of closures has NOTHING to do with lambdas and anonymous functions. A closure is a function (named or not) that has access to the enclosing namespace. lambdas, blocks or whatever are functions that can be used to define closures. The capability of defining closures using lambdas or anonymous blocks or ‘named’ functions is completely unrelated to the powerfulness of closures implementation. Actually the overhead of creating a ‘named’ function (I say ‘named’ because the name is actually _ [underscore]) in python instead of using a lambda/block is 1 line. Stating that one implementation is less powerful than the other because you need one more line is, at least, misleading. > So you claim that multiple-inheritence is more powerful > than mixins. I disagree. On balance, I actually disagree > with my point about mixins being more powerful than > multiple-inheritence. Functionlly, they are two different > ways of accomplishing the same thing. I prefer mixinâs > because (to quote the c2wiki) âno semantics will be > implied about the child âbeing a kind ofâ? the parentâ?. Of > interest, what can you do with multiple inheritence that > canât be done with mixins? Being is-a Plane and Toy is actually a feature that you get for free with multiple inheritance that you are not forced to use if you don’t need. But yes, they are functionally equivalent, yet python doesn’t force multiple inheritance upon you and you can easily provide an alternative algorithm (in 5 lines or so) to use composition. > Err – can you name another language which claims to > be OO and then requires you to pass self in everywhere? How does this makes ruby OO implementation cleaner? I would say the opposite. Python implementation of this particular aspect is cleaner. Because self is not always the instance, it might be the class or the metaclass or, if you are in a static method, it wouldn’t exist. Apart from this: The word cleaner means that there’s something wrong with the python implementation (not just that you don’t like the API but that there’s some incoherence in it and I can’t really see it). > OO was an afterthought with Python. In what way? We are talking about recent versions of python (> 2.2 which is 5 years old more or less and all the production code out there is mostly written in this version) > Clearly it hasnât been tacked on as badly as in Perl, but > in a language which so badly wants to be seen as being > cruft free with a nice syntax, this sticks out like a sore > thumb. That and the underscores. You seem quite a bit confused on this stuff. Underscores are a symptom of being an afterthought? > I find it interesting that you comment on a single part of > the fuller article, of which I myself said: Why should I comment on something that I agree with? That is what I’ve been saying since the beginning of my answer. But I have never said anything about ruby being slightly more broken than python because it isn’t true (and neither is the opposite). Nice article. I have been interested of RoR for some time and recently found information about Django. Both look promising but Im not sure which way to take. I have no previous programming experience so question is more like what would be better for beginner. In general, it looks like Python much larger number of users and that also means there should be more documentation (about programming language). My concern with Ruby is that if there is enough (English) documentation but looks like its improving fast when more and more users start using it. And back to the main subject of article, currently Rails really has much better documentation. But that of Django is probably going to get better in time. Anyway, there is room for both in the world. Regarding Rails schema generation. Rails has a feature called “Migrations”:1 which is a powerful tool to keep several databases up-to-date. It will give each DB a version number so a simple “rake migrate” will run all migrations left to make the DB the latest version. Migrations are run inside a transaction so if a migration fails it will rollback, giving you a chance to fix it. A common use for migrations is to have the first version create the whole initial DB-structure so running “rake migrate” on an empty DB will give you a fresh up-to-date DB. [1] Have a look at to see how Nitro’s ORM library works. Like django, it generates the sql schema from standard objects. Sam Newman: “Err – can you name another language which claims to be OO and then requires you to pass self in everywhere?” The Modula family of languages also have the notion of self parameters. But then objection to such things as if advocating some kind of notion of “OO purity” is a phenomenon we’ve come to expect from adherents of the Perl family of languages and, of course, the Ruby peanut gallery. It’s a shame that you’ve chosen to undermine an otherwise informative article with such flawed observations. Since when do you need to “pass in” ‘self’ in Python? You don’t — you simply call the (bound) method. The only thing you _do_ is to explicitly _name_ the ‘self’ parameter – if you want to call it “foo” because your method actually gets a ‘self’ from somewhere else which it then uses, that’s perfectly valid. Of course, if you have an unbound method, you do pass ‘self’ as the first parameter, but that’s hardly unusual — the method must get its object from *somewhere*. Matthias Wrote: > Of course, if you have an unbound method, you > do pass ‘self’ as the first parameter, but > that’s hardly unusual – the method must get > its object from somewhere. But Python is the only language which calls itself OO which has these sorts of issues, all because OO was factored in after the original language was created. In Java there is no need to talk about self (well, ‘this’) as Java knows that all instance methods have a ‘this’, and that static methods don’t. It may seem simply to be an added convenience to some, but when moving from other languages which have cleaner OO implementations it can grate a little. Could you *PLEASE* tell me what is *SO* wrong about the Python self thing? I thought it was strange, but I decided to try Python and I realized I was not annoyed about it at all. One thing that turns me down about RoR is the )(*@!# arrogant “Ruby is the best and Python and Java and anything else sucks” attitude. First off, *it’s annoying*. I don’t have to do it in any other OO language, why Python? Sure, other languages have their quirks and annoyances – I’ve mentioned Ruby’s occasional syntax in the article above – self just happens to be one of Pythons. As for thinking I’m an arrogant Rails fanboy, you obviously didn’t read the whole article, or anything else I’ve written if you think that A wonderful flamefest you got here if you ask me. I think you should mention one more thing which makes Django special in one very specific way. It has a notion of “meta” – that is, information about the object which is used, for example, for forms. This is something which is not really MVC-like but it works rather well,and Rails doesn’t have this (there is no way to quickly describe a form with a DSL along with all relationships). Granted, it has form helpers but they are nowhere near Django’t meta automagic. But in general you are right – Django seems to have emerged from the need to rig up portal sites quickly and incrementally, Rails is more fit for an application without the dreaded “/admin” url and iterative development. I still love Ruby more as a language though. What I would really love to have would be Rails with some pieces of Django I hope that will come once. The notion of mediators is nice. And – what is important for me – I see many non-English names on the Django mailing lists and I see that i18n and l10n actually are core features and are being taken care of. This is what I would love to see in Rails ASAP (and it’s coming). As regards the use of “self” in python methods, I know this is personal taste but I really like having to use it. It makes reading other peoples code much easier because it is very clear when a variable being referred to is a class variable and when not. For example, in java code, when working in a team I always recommend the use of the “this” qualifyer as it makes the code clearer. Python just enforces the use of it. I think the complaints were more about the inclusion of “self” as an argument in method declarations, and again I believe it makes clearer which functions are true methods and which are just static functions. In java you would use the “static” keyword which is 2 more characters Ah yes, but most OO Java code has few class methods, so you don’t find yourself using static that much as a method-level keyword. Here’s a techical nitpick about this page itself: some of the characters are not displaying correctly on Windows XP Pro. Firefox 1.0.7 displays them as black diamonds with question marks in them and Internet Explorer 6.0.2900 displays them just as question marks. The character set of this page is not UTF-8. It appears to contain MacRoman characters. They appear to be intended to appear as apostrophes (should be ') and em dashes (should be —). This is likely the fault of your blog client software. If the encoding is set to MacRoman on the page, most browsers should render it properly. Better yet your client software should send the valid UTF-8 characters and HTML entities as necessary. dag nabbit – when I switched over to wordpress I didn’t check the character encoding. I can sort that easily enough when I have a spare ten minutes I like python’s use of “self.” It effectively tags methods as bound or not and makes the OO machinery more plain. Python could simply pass in a self parameter silently and have it always be available within the method–apparently that would silence Ruby users’ complaints. But “magic” like that is syntactic sugar that python has always worked hard to avoid–witness the grudging inclusion of a ternary logic operator in 2.5. On a related note, the Django 0.95 “post-magic-removal” code is superb. It wasn’t hard to port my old code, and the changes were all good. I agree that the explicit nature of declaring “self” is desirable. Code is read more times than it is written and the more explicit things are the better, even for the author. When you invoke a method on an object, the syntax doesn’t require an extra argument – the variable provides it. The regularity of syntax to invoke methods on the instance using the self variable is a big improvement. It removes confusion about whether this is a global function or a method. One of the big challenges in a large C++ project is knowing “what is going to happen, exactly, when I invoke this operator?” C++ takes to the extreme the ability to indirectly override behaviors at any level of inheritance. You end up having know everything.. Excellent post. I’ve been using Rails for a month now but switching to Django as I find it so much more powerful since their is so much extra support offered. Django is clearly the way forward for me and especially since Python is migrating much faster to the more powerful x64 architecture. Python also is much closer to Java than to Ruby and for me, a Java Servlets oke, this is the weapon of choice. Thanks!
http://blog.magpiebrain.com/2005/08/14/a-comparison-of-django-with-rails/comment-page-1/
CC-MAIN-2013-48
refinedweb
5,438
70.43
A project that I carried out for a client took an unexpected turn which left me, a software engineer whose main experience is coding JAVA, facing the challenge to make an application that would focus on C++, C# and COM Interop. I have some experience in C++ and C#, but COM Interop was uncharted terrain, and I was at the time thus blissfully unaware of terms such as 'DLL hell' and definitions with similar connotations. Glancing the various COM blogs on the Internet didn't prepare me for the issues I was to face only days later, for yeah, there were some issues you'd have to take in account, but hey.. just work with this great bit of code and your Office automation would work like a charm! The example code provided with the stories looked simple enough, so the promise of exploiting the power of office automation seemed appealing. I am now three months further and wiser and no, I do not regret the choice to plunge into a project that would require a connection between unmanaged and managed code, speckled with COM calls not only to Microsoft Office applications, but also with proprietary software. However, I would have liked to know all the things I know now before I started and, considering the many forums and newsgroups I have had to work through in order to find answers to the many vague errors and exceptions I had to deal with, I have decided to write this article that may help others to circumvent all the pits I happily jumped into. I did COM Interop the hard way and hopefully this article may prevent other newbies following in my stead. The project I was hired for, aimed to provide simple reporting functionality in Microsoft Word for an existing proprietary application. The application is a mathematical modelling tool (a bit like Mat lab), but my client missed functionality to export the graphs, tables and bitmaps to a Word processor. The application supported a plug-in structure that consisted of a subdirectory with a number of DLLs that conformed to a certain structure. My reporting tool would therefore be implemented as an additional plug-in that would add a menu item to the application which, upon clicking would open a form that allowed the user to prepare the report and export the required graphs and tables to Microsoft Word. As an additional advantage, the application provided a type library that allowed it work as a COM server. This server was quite extended and so this would allow me fine-grained control over the information that was contained in the application. Of course COM Interop was also the preferred choice on the side of Office automation, so the global architecture was quickly determined: Figure 1: Global Architecture of the Reporting Tool The first setback in this simple plan dawned when I couldn't get the plug-in to work in managed C++. The plugin required a number of libraries that caused all kinds of alien compiler and linker errors, so it became clear that this would have to done in unmanaged (i.e. old-fashioned C++) code. As I didn't want to opt out on the neat functionality that is provided in .NET, I decided that I would implement an interface between the unmanaged plug-in and the actual reporting functionality, which would be coded in (managed) .NET, using C#. The interface would be as simple as possible and would consist of a command structure (strings) that would make requests to the reporting tool. This tool would itself be implemented as a COM object that would coordinate the calls to Microsoft Office and the application COM server. The application therefore would consist of a unmanaged DLL (the plugin) and a managed DLL (assembly) that provided the actual reporting functionality. The following sections describes the various issues that I have dealt with in order to make this work, including all the vague errors and exceptions that are related to connecting the various parts together. This includes deployment issues on the client's target computer that ran on a different Windows version and used a different version of Microsoft Office. The first step of my project would be to implement a very simple interface that would pass the menu event to the managed environment in order to open a slick form. The first potential pitfall I managed to circumvent by buying a good book on COM Interoperability, that included a good discussion on combining managed and unmanaged code. Andrew Troelsen's "COM and .NET Interoperability", was generally highly recommended and indeed proved to be a valuable aid, especially since the forum articles on the Internet (for instance in the Code Project) were usually targeted for very specific applications. The general tendency of these articles were very optimistic; do this, do that and 'It Just Works'. The first issue that one needs to grasp is that developing an interface between managed and unmanaged domains starts in the managed domain. This is easy enough, as this means defining an interface IMyInterface in .NET (using, say C#) and adding attributes that allow the methods to be registered with COM: IMyInterface namespace MyNamespace { [Guid("D4660088-308E-49fb-AB1A-72724F3F8F51")] [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMyInterface { /// <summary> /// Open the form /// </summary> void openForm(); } [ClassInterface(ClassInterfaceType.None)] [Guid("46A951AC-C2D9-48e0-97BE-9F13C9E70B65")] [ComVisible(true)] public class MyImplementingClass : IMyInterface { ManagedForm form; // Need a public default constructor for COM Interop. public MyImplementingClass () { } /// <summary> /// open the form /// </summary> public void openForm() { if (this.form != null) return; try{ this.form = new ManagedForm(); this.form.Disposed += new EventHandler(form_Disposed); this.form.Show(); } catch(Exception ex ){ MessageBox.Show( ex.Message + "\n" + ex.StackTrace ); } } /// <summary> /// Clear the form if it is no longer used /// </summary> void form_Disposed(object sender, EventArgs e) { this.form.Disposed -= new EventHandler(form_Disposed); this.form = null; } } } As I am focusing on the pitfalls, I will not explain the code or the various COM attributes, as there are loads of articles on COM Interop on the Internet. The most important attribute is the so-called 'guid', which has to be a unique id that is used to register the interface (and its implementations) in the Windows registry. These are usually copied and pasted from the example code you base your implementation on. I usually swap four random digits in order to prevent the unlikely chance that existing DLLs are also based on the same sample code I use. There also used to be a tool provided by Microsoft (I believe it was shipped with older versions of Visual Studio), called something like guid.exe that created a unique GUID, but I found it difficult to find it (actually it is guidgen.exe, see replies below...that's why it was so hard to find...). Besides this, the swapping strategy is, although not a recommended approach, fairly secure if creating COM libraries is not a regular activity. If the interface is in a C# assembly of the type class library (project properties => application in Visual Studio, the solution should build a DLL that can be accessed by others… in theory. guid GUID The first problem one runs into is the question how the DLL will make its existence known to those other DLLs. One option (and the recommended one) is to 'upgrade' your DLL to become a full-fledged COM object itself. As the combination of managed code and GUIDs already has taken most of the necessary steps to achieve this, the only additional step required is to register your DLL to the Global Assembly Cache (GAC) of Windows. Yes…, this is a folder in Windows, but no, I will not try to explain where it is, for the simple reason that it would give people wrong ideas on how registering should occur. Instead, rely on the gacutil.exe tool that is provided with Visual Studio (e.g. c:\Program Files\Microsoft Visual Studio 8\SDK\bin\gacutil.exe). After setting the correct paths, open a command prompt and enter: gacutil /i MyLibrary.dll /f and your assembly is added to the cache. Piece of cake, huh? Well…the problems have now started. One of the mantras of software development is 'thin coupling' and COM Interop is a nice example of an attempt to create thin coupling between different software libraries. Most of us experienced programmers will be enthusiastic advocates of this design principle, but we often forget that there is an interesting bifurcation point between thin coupling and no coupling whatsoever! Consider yourself blessed when you register your DLL to GAC and you get strange and unexpected behaviour, for at least you are seeing something happening! The chances are much higher that you will register and see nothing at all. There are a number of pitfalls at this point: /f guid ComVisible false When developing a class library assembly, it may be a good idea to add a second test project (for instance a windows or console application project) to your solution that calls the interface you are developing: static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run( new MyTestApplication.TestInterfaceForm() ); } When running this code in Visual Studio, the following warning is an indication that the newly built assembly has not been added to the GAC (yet): Run the previous gacutil after building your project (from the debug / release directory of your project, or any other location where the most recent assembly is located) and the warning message will go away. Ignoring this will usually (not always) find you running a previous assembly. The oleview.exe tool that is also provided with Visual Studio (e.g. c:\Program Files\Microsoft Visual Studio 8\Common7\tools\bin\oleview.exe) can help in checking whether the DLL was added to GAC successfully. regasm MyLibrary.dll /tlb: MyTypeLibrary.tlb This will create a type library with the name MyTypeLibrary.tlb in the currently active folder. This often gives rise to problems when an older version of your DLL is already registered with Windows, for then that type library will be used rather than the new one. This can be checked with the 'view typelib' option of oleview, which is represented by the button with three red arrows. As the type library shows the structure of the interface that was implemented, this structure will be displayed in oleview. If there is a mismatch, then it is likely that regasm.exe or tlbexp.exe did not use the newly built DLL. Regasm and tlbexp do not give any useful warning or error messages that indicate a failure to register. The best way to prevent type library problems is to close all the applications that may be connected to your library, and then perform an unregister operation before registering the new DLL: regasm MyLibrary.dll /u This obviously only needs to be done when the interface structure is changed, but as by now we are doing quite a bit of typing after every build of our assembly, we can just as well create a batch file (e.g. register.bat) that we call everytime the assembly is built: regasm MyLibrary.dll /u regasm MyLibrary.dll /tlb: MyTypeLibrary.tlb gacutil /i MyLibrary.dll /f This approach is the best way to ensure that the type library always corresponds with every updated DLL we build. The type library can now be imported in the Visual Studio C++ project. #ifndef MY_INTERFACE_H #define MY_INTERFACE_H class MyInterface { public: long OpenForm(); }; #endif #import ".\VC8\managed\MyLibrary.tlb" raw_interfaces_only named_guids #include "resource.h" #include "mylib.h" MyNamespace::IMyInterfacePtr pDotNetCOMPtr; //Optional method to check if the DLL is loaded or unloaded bool APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: MessageBox (NULL, "Dll is loading!", "DllMain() says...", MB_OK); break; case DLL_PROCESS_DETACH: MessageBox (NULL, "Dll is UNloading!", "DllMain() says...", MB_OK); break; } return true; } long MyInterface::OpenForm( void ) { CoInitialize(NULL); //Initialize all COM Components HRESULT hRes = pDotNetCOMPtr.CreateInstance (MyNamespace::CLSID_MyInterface ); if (hRes == S_OK) hRes = pDotNetCOMPtr->openForm(); pDotNetCOMPtr = NULL; CoUninitialize (); //UnInitialize all COM Components return hRes; } When this project is built in Visual Studio C++, the type library is converted to a *.tlh file which represents the interface. In the example above, the interface is wrapped in a class that closely resembles the interface. The C++ project needs to be rebuilt every time the structure of the interface changes (in effect, when a new type library is copied to the C++ project). Building this project creates an (unmanaged)DLL that was used as a plug-in by the proprietary application. With all the tooling and work structures in place, cross-development between managed and unmanaged environments is quite stable and good. On one or two occasions it was necessary to completely remove all references of my library from the Windows registry (using regedit.exe provided by Windows), but as long as I kept to a strict routine of closing all applications that might be connected to my DLL (this obviously includes Office applications when developing Office Automation applications) and consistently using the batch file after building the library, everything went quite good. Sadly it had taken me three weeks to get to that point. By now, I had managed to open a .NET form by clicking a menu item from the proprietary application. The next step consisted of developing the reporting functionality, which consisted of COM calls to both Microsoft office applications and the COM interface of the proprietary application. In all honesty, developing this was rather straightforward. There are lots of good examples on the Internet of automating Microsoft Word, and the proprietary application's COM interface worked quite well also. Testing the functionality is a rather slow process, but luckily most calls to Microsoft Office could be tested from the test project, so it didn't require me to continuously open and close applications during testing. The headaches during this phase were therefore minor. Microsoft's preferred policy to Office automation is to open a new document, worksheet, etc, in which the reporting can be done. The alternative approach, to connect to an already opened document or worksheet is therefore hard to find on the Internet. The System.Runtime.InteropServices.Marshal.GetActiveObject method can be used to achieve this, for instance in a 'connect' method that looks for an open Office document or worksheet, connects to this if it is found, or opens a new application object if not. Alternatively, the 'Disconnect' method uses Marshal.ReleaseComObject to release the object. This consistent use of 'connect' and 'disconnect' methods with respect to COM Interop improves the development cycle greatly, as the chance becomes much smaller that other applications are connected to the assembly when a new DLL is registered to GAC. I also decided to implement the classes that contained these methods as singletons (one for every COM library), which also greatly reduced the chance of blocking the assembly in GAC. Disconnect Marshal.ReleaseComObject connect disconnect The term 'DLL Hell' manifests itself in full glory when deploying an application. To give a rough sketch, I had been developing my application on a Windows XP OS, using Visual Studio 2005 and Microsoft Office 2003. The client used Windows 2000 and Microsoft Office 2000. We both used the same proprietary application. I believe that many a reader who has been through the hell is already smirking at this prospect… Installing the reporting tool consisted of installing .NET, adding the plug-in to the plug-in directory of the proprietary application and finally adding the reporting tool to GAC. It seemed simple and should be simple, but alas, it wasn't. This section addresses the deployment along the various vague error messages I encountered. I have seen many software developers struggle with similar messages on various Internet forums and most of them will get replies telling them what the errors mean, without any mention of the cause of these errors. That is, if they get replies at all! The first vague exception I encountered referred to a mysterious mscorlib80.dll. The cause of this error is that Visual Studio C++ 2005 includes references to a number of libraries that are included in Visual Studio C++ 2005. If this is not available on the client's computer, which normally is the case, it starts begging for these DLLs. Mscorlib80.dll is the most likely library it will request (mscorlib80d.dll will be requested if the application was built in debug mode). Although there are a number of remedies that are suggested on the Internet, the most practical one is to download the required libraries from Microsoft (for PCs this is vcreditst_x86.exe). This executable copies the required library files to their designated locations, but… It will not work immediately on a pre-Windows XP OS such as Windows 2000. In the old days, DLLs were added to the Sytem32 folder under the Windows root. With XP, this policy has changed. Instead a WinSxS folder has been included that is the root of a tree structure that contains a number of application specific subfolders. Vcredist.exe adheres to this new convention, which results in nothing happening on a Windows 2000 OS after the installation is complete. Obviously Windows 2000 does not recognise winsxs and so the libraries are not found. The best ways to circumvent this is to either add paths pointing to the newly added folders in winsxs (recommended) or to copy them into the system32 folder. A detailed description of these issues can be found here. "Attempted to read or write protected memory. This is often an indication that other memory is corrupt." This error occurred when a COM call was made to Microsoft Office. After extensive Internet research, it appeared that this error was related to the version of Microsoft Office that was used. Contrary to intuition, Microsoft Office DLLs are not downwards compatible. If one develops an automation project and uses the COM Interop of Microsoft Office products that are newer than that of the target machine (so the references you add in your .NET project point to these newer COM objects), the system is likely to throw the above exception, or similar ones, when your application is deployed. An Office application is upward compatible with respect to COM objects, so newer versions of Microsoft Office will accept automation libraries of older Windows versions (which also means that you are restricted to the available functionality of that older version). It is therefore important that the application you develop uses the COM objects that represent the oldest version of Office that it should support. An additional complication is that the Microsoft.Office.Interop DLLs are only shipped since Office 2003. With older versions of Microsoft Office, you will have to generate the DLLs yourself using the type libraries that were included in the installation. These libraries have extensions .olb (e.g. excel8.olb, msword9.olb, etc) and the corresponding DLLs can be generated with tlbimp.exe tool that is shipped with Visual Studio (e.g. c:\Program Files\Microsoft Visual Studio 8\SDK\bin\tlbimp.exe): Tlbimp Excel8.tlb /keyfile=MyApplicationKeyPair.snk /out:Microsoft.Office.Interop.Excel Note that in this case, a signed DLL is made using the information found in MyApplicationKeyPair.snk file. This is due to the fact that this DLL is used by .NET, which requires signed (or strongly typed) libraries. The required DLLs can be created this way. Remember that these DLLs all have to be added to GAC on the target computer. It is also likely that source code needs to be changed after adding these DLL to the .NET project as some COM calls may have changed in newer versions. Yes, this exception is actually raised in the managed environment by an exception that you have programmed to catch somewhere. You may even pinpoint this exception to a line of code in your C# project. If you do you will probably notice that the application is trying to make a call to one of those libraries we just made from the type libraries. The exception is actually raised when the libraries have not been registered in GAC on the target computer or, less likely, when they need to be updated. This is hardly likely to occur for the Office DLLs, but the proprietary application I used was a COM server, and so the .NET project created a new Interop.ProprietaryApplication.dll every time the project was rebuilt. I had assumed that the proprietary software had registered its COM server in GAC when the application was installed on the target machine, but actually only the type library had been registered in the Windows registry. This mistake became transparent when I first started working with the Microsoft Office 2000 DLLs I had just created and forgot to register one of them. Suddenly I got the exception that had been nagging me for a few days (but which at the time wasn't high on my priority list) with another library and for which I immediately knew what was wrong. It goes to show that sometimes sloppiness pays off, I guess. The lesson that is learnt here is to remember to register all the Interop libraries your application needs with the target machine's GAC and to update them on the rare occasion that this could be required. As this does not need be done often (usually once per target machine), I decided to create a batch file called install.bat that basically is the same as register.bat but then with a number of additional calls to Gacutil.exe: regasm MyLibrary.dll /u regasm MyLibrary.dll /tlb: MyTypeLibrary.tlb gacutil /i MyLibrary.dll /f gacutil /i Interop.ProprietaryApplication.dll /f gacutil /i Microsoft.Office.Interop.Word.dll /f gacutil /i Microsoft.Office.Interop.Excel.dll /f gacutil /i Microsoft.Office.Interop.PowerPoint.dll /f And with this I finally got everything running the way it should be…, with a four week delay on my original estimates. I usually work in a JAVA environment, and therefore I can imagine that very experienced .NET and COM programmers may frown at some of the explanations that are given here, or the solutions that I came up with. I can also imagine that other programmers who were facing the same daunting journey through DLL hell may have additional problems that have not been described here.. I have no pretence or ambition to be a .NET or COM expert, in fact this article reflects the issues of someone who faced COM interoperability for the first time, with very little experience in that area, and found himself facing an enormous gap between the 'It Just Works' hallelujah on one side, and the enormous fragmented forum discussions on DLL hell on the other, especially related to the exceptions I had to deal with. By focusing on errors and exceptions instead of programming, I hope to make this gap a bit smaller for all those others who have to deal with COM Interop. For, in all honesty, once everything works it really adds a tremendous range of functionality to your.
http://www.codeproject.com/Articles/18240/COM-Interop-the-Hard-Way?fid=402392&df=90&mpp=10&sort=Position&spc=None&tid=2484622
CC-MAIN-2015-18
refinedweb
3,863
53
LintProject 1.4.1.13 (26th January, 2009) 1. Modifications to support $(PlatformName) with VS2002 onwards. Our thanks to Alex McCarthy for contributing these changes. LintProject 1.4.1.12 (23rd October, 2008) 1. LintProject now returns an error code of 1 in the event of an error in the command line. Our thanks to Brett Rowbotham for contributing this change. 2. The elapsed time value in project reports now shows hours as well as minutes and seconds (preventing an incorrect elapsed time from being reported for projects which take over an hour to analyse). Our thanks to Brett Rowbotham for contributing this change. 3. Removed the (no longer in existance) LintProject.h from the project files. LintProject 1.4.1.11 (21st October, 2008) 1. Updated the MSXML import in stdafx.h from msxml2.dll to msxml4.dll and added the named_guids qualifier. 2. Modifications to support $(SolutionDir) and $(ProjectName). Our thanks to Alex McCarthy for contributing these changes. 3. Removed a redundant declaration in CFileLintAnalyser 4. Removed the unused LintProject.h 5. Changed LintProject.zip to LintProject_1.4.zip in MakeZip.bat LintProject 1.4.0.10 (29th April, 2008) 1. Corrected a bug in the generation of analysis command lines. 2. Added the application version to generated reports. LintProject 1.4.0.9 (9th April, 2008) 1. Solution and project specific environment variables $(SolutionDir), $(ProjectDir), $(InputDir) and $(ConfigurationName) are now set during analysis. Our thanks to Andrej Pohlmann for contributing the code to implement this feature. 2. If a file of the form <project filename>.options.lnt is found in the project folder, it will now be used in the analysis command line. Our thanks to Andrej Pohlmann for contributing the code to implement this feature. 3. Corrected a potential buffer overflow in the loading of XSL stylesheets (thanks to Mark Ridgwell for identifying this). 4. Fixed a potential COM exception in Utils::RefreshAllOpenBrowserWindows(). 5. Corrected a bug in the parsing of intermediate file folders within Visual C++ projects. 6. Minor corrections to analysis command lines. 7. Visual C++ 6.0 project (.dsp) files containing only one project configuration are now parsed correctly. 8. Moved CSplitPath and CModuleVersion into the Riverblade::Libraries::Utils namespace. 9. Fixed minor lint issues. 10. The code is now released under the Code Project Open Licence (CPOL) v1.0; file banners have been updated accordingly. LintProject 1.4.0.8 (9th February, 2008) 1. Removed all MFC dependencies. LintProject now uses ATL 7 directly, and in consequence, the source now requires Visual Studio .NET 2002 or later to compile (project files are supplied for Visual Studio .NET 2003 and Visual Studio 2008, but porting to other versions should be straightforward). 2. Added support for eMbedded Visual C++ 4.0 workspaces and projects. 3. Added error checking for solution/project configurations. Attempting to analyse an invalid configuration will now cause an error to be generated. 4. Project intermediate folder specifications containing "$(ConfigurationName)" will now be expanded correctly on the PC-Lint command line (VS2002 onwards). 5. Reinstated a missing -u option in the analysis command line. 6. Added a "/exclude" parameter to allow specified projects to be excluded from analysis (our thanks to Andrej Pohlmann for contributing the code to implement this). 7. Integrated the solution and project file parsers from Visual Lint, along with various utility functions. 8. Converted the build to Unicode. LintProject 1.3.1.7 (26th June, 2007) 1. Added /configfile switch to allow the filename of the std.lnt file to be specified. 2. Incorporated customer requested fixes and corrections. 3. Started removing MFC specific code 4. Fixed most outstanding lint issues. LintProject 1.3.0.6 (12th February, 2006) 1. Added support for VS.NET solution configurations. The solution configuration can now be specified directly, with the corresponding configuration for each project being selected automatically. 2. Added the /cfg? parameter to allow the available configurations to be queried at either solution or project level. 3. CSolutionLintAnalyser and CProjectLintAnalyser now only attempt to refresh browser windows if the /s parameter is specified. This prevents problems when the utility is run as a service. LintProject 1.3.0.5 (21st April, 2005) 1. Added the +linebuf parameter to the command line used to generate project.lnt files. This increases the line width which PC-Lint will use when scanning the project file, and makes it more likely to work correctly with complex projects such as AnkhSVN. 2. Transposed the std.lnt and project.lnt location in the command line used to analyse a file. This should ensure that project specific include settings override the system defaults. 3. Project configurations can now be specified. If not specified, Lintproject will attempt to use the debug configuration by default. 4. The source now compiles with either VC6 or VS.NET 2003. 5. User specified parameters can now be passed to the project.lnt file generation process as well as during analysis. LintProject 1.2.4 (24th February, 2005) 1. CSolutionLintAnalyser::Analyse() and CProjectLintAnalyser::Analyse() now use SHCreateDirectoryEx() instead of mkdir() to create folders for analysis results so that recursive folders are automatically created. 2. Fix to UNC path checking suggested by coghlans@technologist.com on the LintProject CP forum. 3. Improved handling of relative pathnames. Analysis and source files no longer need reside on the same logical drive. 4. Added support for passing parameters directly to lint-nt.exe via a new command line option (/l"<params>") 5. If a warning count of 255 is returned from lint-nt.exe. CFileLintAnalyser::Analyse() will now parse the results file to try to retrieve the true warning count. 6. Reimplemented the FileExists() helper function. 7. Added solution to source code control. LintProject 1.2.3 (13th October, 2004) - Modifications to allow operation on systems where PC-Lint is installed in a pathname containing spaces (e.g. C:\Program Files\Lint) LintProject 1.2.2 (10th October, 2004; published on codeproject.com 11th October 2004) 1. Removed a couple of unnecessary includes 2. Replaced MSXML4 with MSXML3 (MSXML4 isn't installed by default on XP, but MSXML3 is). 3. Added checks to ensure that MSXML3 and lint-nt.exe are available before attempting to proceed with the analysis. 4. LintProject now uses env-vc7.lnt with VC7 projects instead of env-vc6.lnt. 5. Added a workaround for the duplicated carriage return bug in the XSLT generated HTML output. 6. Temporarily removed "the mark of the web" (needd for XP SP2) from generated analysis reports as it seems to be causing more problems than it solves... 7. Added MakeZip.bat to provide a convenient way to create a zipfile of the source. 8 Added company details to intro banner and reports. 9. Added start time to reports. 10. Improved support for "Pending" and "In Progress" analysis. 11. Fixed a handful of compiler warnings. 12. Enabled incremental linking in debug builds. 13. Added code to refresh all open browsers with any open lintproject output window. 14. Added support for /s (show results) option. 15. Solution results files are now updated as each file within a project is analysed. LintProject 1.2.1 - Initial version inherited from Sonardyne International Limited, August 2004.)
http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=8526&zep=Source%2FVersion+History.txt&rzp=%2FKB%2Fapplications%2Flintproject%2F%2FLintProject.zip
CC-MAIN-2015-40
refinedweb
1,195
53.17
Difference between revisions of "Using the XML Catalog" From Eclipsepedia Latest revision as of 22:53, 22 April 2010 Note that this document is a work in progress. Various portions are missing and incomplete. See bug 135079 for more info or to provide feedback. The eclipes WTP project provides support for using an XML Catalog based on the OASIS XML Catalog specification. An XML Catalog provides some limited control over how references to other resources are The XML Catalog (as shown in the figure below) can be accessed via the Eclipse preferences as follows... 1. Select “Window -> Preferences” to launch the Preferences dialog. 2. In the navigation tree expand the “Web and XML” group and select “XML Catalog”. Working With DTDs If you're working with XML documents that contain 'DOCTYPE' declarations to reference DTD resources you can control how the referenced DTD documents are located. If an XML document utlizes a DOCTYPE declaration that specifies a PUBLIC ID (as shown below) you can use the XML Catalog to register a local DTD file using the PUBLIC ID as the key. <!DOCTYPE Invoice PUBLIC "-//EXAMPLE//DTD INVOICE//EN" ""> If an XML document utlizes a DOCTYPE declaration that specifies a SYSTEM ID (as shown below) you can use the XML Catalog to register a local DTD file using the SYSTEM ID as the key. <!DOCTYPE Invoice SYSTEM ""> Hint : If you examine the XML Catalog setting in WTP you'll notice that there's several DTD related entries that specify a PUBLIC ID key. Note : If your XML document utlizes a DOCTYPE declaration (as shown below) that specifies a relative URI location (e.g. 'Invoice.dtd' as opposed to a fully qualified URI) then a DTD can NOT be registered using "Invoice.dtd" as the System Id key. TODO.. reference section below that describes why this is the case and how XML Catalog v1.1 provides a way to partially solve this. <!DOCTYPE Invoice SYSTEM "Invoice.dtd"> TODO... describe how to working DTD's that reference DTDs work the same way Working With XML Schemas XML instance document can be associated with XML Schemas in two ways. The first way involves explicit location attributes specified directly in the XML document that specify a URI location to the XML Schema. The second way involves an implicit association between an XML namespace and an XML Schema (where this association is stored outside of the XML document). Often XML documents are designed as shown below (in partial form) where schema locations are explicitly specified using 'xsi:schemaLocation' or 'xsi:noNamespaceSchemaLocation' attributes. In these cases you can use the XML Catalog to register a local XML Schema file using the Schema Location as the key. This way a reference to web resource (e.g.) can be redirected to a local resource. <xyz:foo xmln:xyz="". <xyz:foo xmln: Hint : If you examine the XML Catalog settings in WTP you'll notice that there's several XML Schema related entries that specify a Namespace Name key.:xyz="" xsi:schemaLocation="foo.xsd" ... - I've registered a DTD with a 'System ID' key of 'foo.dtd' and it doesn't work. Why not? Locations in an XML instance get expanded _before_ the XML Catalog is referenced. So the XML Catalog should contain only fully qualified URIs (e.g.). - I've registered an XML Schema with a 'Schema Location' key of 'foo.xsd' and it doesn't work. Why not? Locations in an XML instance get expanded _before_ the XML Catalog is referenced. So the XML Catalog should contain only fully qualified URIs (e.g.). - I've registered my DTD or XML Schema but eclipse is still going off to the internet to fetch a resource. Why? The registested DTD and XML Schema may have references to more DTDs and XML Schemas. - I've registered an XML Schema by namespace but XML files are still using the 'xsi:schemaLocation' value. Why? An explicitly specified schema location value takes precedence over XML Catalog entries that are keyed by namespace. - Can I register multiple XML Schemas for the same namespace? No you can't. There should be only one XML Schema registered for a given namespace. OASIS XML Catalog specification OASIS XML Catalog V1.1 specification XML Catalog Tutorial
http://wiki.eclipse.org/index.php?title=Using_the_XML_Catalog&diff=197796&oldid=6719
CC-MAIN-2013-48
refinedweb
707
55.24
With handling libraries under the hood, essentially playing the role of a java wrapper around them. It is the easy way to uncompress, modify, and re-compress any media file (or stream) from Java. FFmpeg is a complete, cross-platform solution to record, convert and stream audio and video, supporting numerous formats. It is probable that you are already using it on your computer, even without knowing it. However, Xuggler’s use is not limited to just providing an easy access to the complex FFmpeg native libraries. The Xuggler dev team also constantly adds improvements to FFmpeg. You can find the latest news on the Xuggle blog, where a number of tutorials is also published. Don’t miss the Overly Simplistic Guide to Internet Video from those guys. Let’s continue by getting FFmpeg. Note that Xuggler comes with its own (improved) FFmpeg version to avoid misconfiguration problems, so you do NOT have to manually obtain FFmpeg. Along the way, we are going to test some things directly using FFmpeg before passing control to Xuggler, so you might prefer to have the original version as a separate executable. Go to FFmpeg downloads page and get the latest distribution, version being 0.6.1 at the time. For Linux, you download the source code from the tarball and proceed with the compilation. In Windows though, you should probably get a precompiled binary. I used the one provided by Mplayer-win32 and can be obtained from here. You will find a ffmpeg.exe executable there. Copy that in a specific folder, I chose “C:\programs\ffmpeg” and optionally add the ffmpeg.exe in your system’s path if you don’t want to write the whole path every time. To test that the executable works correctly open a terminal and just run it with no arguments. You should see an output similar to this: Hyper fast Audio and Video encoder usage: ffmpeg [options] [[infile options] -i infile]… {[outfile options] outfile}… Use -h to get full help or, even better, run ‘man ffmpeg’ You can also use the “-h” switch, as suggested by the output, to receive a ridiculously long list of arguments and options. Better check out the online FFmpeg documentation. The next step would be to transcode your first video, probably from a prerecorded file. My input file is a MP4 video, 4min 20sec long, with a size of 18.1MB called “myvideo.mp4”. I would like to convert that to a Flash Video, considerably lowering its quality. This is accomplished with FFmpeg very easily by issuing the following command (note the use of forward slashes for the paths): ffmpeg.exe -i C:/myvideo.mp4 C:/myvideo.flv Here is what the console output looks like: Output #0, flv, to ‘C:/myvideo.flv': Stream #0.0(und): Video: flv, yuv420p, 480×270 [PAR 1:1 DAR 16:9], q=2-31, 200 kb/s, 1k tbn, 29.96 tbc Stream #0.1(und): Audio: libmp3lame, 44100 Hz, stereo, s16, 64 kb/s Stream mapping: Stream #0.1 -> #0.0 Stream #0.0 -> #0.1 Press [q] to stop encoding [libmp3lame @ 0038f3a0]lame: output buffer too small (buffer index: 9404, free bytes: 388) Audio encoding failed Ignore the “Audio encoding failed” message, there is no error. The outcome is a nice, playable FLV file named “myvideo.flv” with a size of 10.1MB. Cool, let’s proceed with installing Xuggler. First we get the latest version from the Xuggler downloads page. As stated there: The Xuggler is composed of two main components; a set of Java jar files, and a set of native shared libraries (.dll files on Windows, .so files on Linux, or .dylib files on Mac). To use you need to first install the native libraries, and then you can write programs that use the Xuggler. Make sure you download the correct file matching your OS’s architecture and your Java version. For example I downloaded the 32-Bit (no 64-bit for Windows), Java 1.5 or later version for Windows, which is basically an installer. You can find instructions on how to install the native libraries in the downloads page. For Windows, you uninstall any previous versions, run the installer and of course you reboot your computer. There is also a video describing how to install Xuggler on Microsoft Windows. After the reboot, let’s test if the installation was successful. First we check if the Xuggle path variable has been set: C:\>echo %XUGGLE_HOME% C:\Program Files (x86)\Xuggle The path has been correctly set. Note that the Xuggler FFmpeg executable resides in the “%XUGGLE_HOME%/bin” folder. Let’s play our first video by issuing the following command (replace the “c:/myvideo.mp4” with a file of yours): java -cp “%XUGGLE_HOME%\share\java\jars\xuggle-xuggler.jar” com.xuggle.xuggler.demos.DecodeAndPlayVideo c:/myvideo.mp4 Time to write our first code with Xuggler. We are going to inspect a video file, find out its media container, and print out a summary of the contents. Meanwhile, bookmark the Xuggle API Javadocs for future reference. Fire up your favorite IDE, create a new project and import all the JAR files found in the “%XUGGLE_HOME%/share/java/jars” folder. The example is similar to the one provided in the How To Write Your First Xuggler Application In Eclipse post. package com.javacodegeeks.xuggler.intro; import com.xuggle.xuggler.ICodec; import com.xuggle.xuggler.IContainer; import com.xuggle.xuggler.IStream; import com.xuggle.xuggler.IStreamCoder; public class VideoInfo { private static final String filename = "c:/myvideo.mp4"; public static void main(String[] args) { // first we create a Xuggler container object IContainer container = IContainer.make(); // we attempt to open up the container int result = container.open(filename, IContainer.Type.READ, null); // check if the operation was successful if (result<0) throw new RuntimeException("Failed to open media file"); // query how many streams the call to open found int numStreams = container.getNumStreams(); // query for the total duration long duration = container.getDuration(); // query for the file size long fileSize = container.getFileSize(); // query for the bit rate long bitRate = container.getBitRate(); System.out.println("Number of streams: " + numStreams); System.out.println("Duration (ms): " + duration); System.out.println("File Size (bytes): " + fileSize); System.out.println("Bit Rate: " + bitRate); // iterate through the streams to print their meta data for (int i=0; i<numStreams; i++) { // find the stream object IStream stream = container.getStream(i); // get the pre-configured decoder that can decode this stream; IStreamCoder coder = stream.getStreamCoder(); System.out.println("*** Start of Stream Info ***"); System.out.printf("stream %d: ", i); System.out.printf("type: %s; ", coder.getCodecType()); System.out.printf("codec: %s; ", coder.getCodecID()); System.out.printf("duration: %s; ", stream.getDuration()); System.out.printf("start time: %s; ", container.getStartTime()); System.out.printf("timebase: %d/%d; ", stream.getTimeBase().getNumerator(), stream.getTimeBase().getDenominator()); System.out.printf("coder tb: %d/%d; ", coder.getTimeBase().getNumerator(), coder.getTimeBase().getDenominator()); System.out.println(); if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) { System.out.printf("sample rate: %d; ", coder.getSampleRate()); System.out.printf("channels: %d; ", coder.getChannels()); System.out.printf("format: %s", coder.getSampleFormat()); } else if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) { System.out.printf("width: %d; ", coder.getWidth()); System.out.printf("height: %d; ", coder.getHeight()); System.out.printf("format: %s; ", coder.getPixelType()); System.out.printf("frame-rate: %5.2f; ", coder.getFrameRate().getDouble()); } System.out.println(); System.out.println("*** End of Stream Info ***"); } } } We start by obtaining an IContainer instance, which is a data source that contains one or more streams of audio and video data. We then attempt to open the media file and make it ready for reading. If the operation is successful, we can easily retrieve information such as the number of streams contained, the total duration, the file size and the bit rate. Note that this information responds to the container itself. However, we can obtain meta-data regarding the individual streams that the container consists of. We use the getStream method to take reference of the corresponding stream and then an IstreamCoder which is the decoder that can decode the particular stream. From that object, we can find the stream’s codec type, codec ID and a bunch of other information. Finally, we are able to distinguish among audio and video streams. For audio streams, we can find the sample rate used, the number of channels and the audio sample format. Likewise, for video streams, we can get dimensions (width and height), the pixel format and the frame rate. Here is what a sample output will look like: Number of streams: 2 Duration (ms): 260963888 File Size (bytes): 19007074 Bit Rate: 582672 *** Start of Stream Info *** stream 0: type: CODEC_TYPE_AUDIO; codec: CODEC_ID_AAC; duration: 11507712; start time: 0; timebase: 1/44100; coder tb: 1/44100; sample rate: 44100; channels: 2; format: FMT_S16 *** End of Stream Info *** *** Start of Stream Info *** stream 1: type: CODEC_TYPE_VIDEO; codec: CODEC_ID_H264; duration: 7819000; start time: 0; timebase: 1/29962; coder tb: 250/14981; width: 480; height: 270; format: YUV420P; frame-rate: 29.96; *** End of Stream Info *** That’s all guys. A soft introduction to Xuggler for video manipulation. As always, you can download the Eclipse project created for this tutorial. In the next tutorials I will show you some cooler stuff that can be done with Xuggler and FFmpeg, like video conversion and modification. So, stay tuned here at JavaCodeGeeks! And don’t forget to share! Related Articles: If I want to extract Date and Time of creation of the video information, how do I do that using Xuggler? Hi, is Mplayer-win32.exe available for win 64 bit machine? How to enable logger in xuggler ? to see the generating logs. i tried to execute this code in netbeans and i found some errors those are , SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”. SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See for further details. Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 0 at blesson.DecodeAndCaptureFrames.main(DecodeAndCaptureFrames.java:85) Java Result: 1 what to do? You should download slf4j api,,,.StaticLoggerBinder class is missing…which comes in slf4j api
http://www.javacodegeeks.com/2011/02/introduction-xuggler-video-manipulation.html/comment-page-1/
CC-MAIN-2015-22
refinedweb
1,676
59.4
by Forrest Sheng Bao I want to talk about two common errors people encounter when they compile old programs, especially when they are using recent version of g++. They may wonder why this code can be compiled in g++3.4 but not g++4.3. A lot people get shock when they see this: error: fstream.h: No such file or directory The answer to solve this problem is that "Header files in the C++ Standard Library do not use the .h extension; have have no extension," -Kyle Loudon, C++ Pocket Reference, p.5, O'Reilly, 2003. So instead of saying #include , you should say #include The second common error is that you have included the library which defines a function, but you still got this: error: ‘ifstream’ was not declared in this scope Well, recent versions of g++ does not import std namespace by default. So, you have to add this line using namespace std; Above two issues had been address in textbooks a long time ago, at least when I was a college freshman. But I really do not understand why people are still thinking in the old way after so many years.
http://forrestbao.blogspot.com/2009/05/no-h-fot-c-standard-library-head-file.html
CC-MAIN-2017-13
refinedweb
196
69.21
A supporting module for jplephem to handle data type 21 Project description spktype21 A supporting module for jplephem to handle data type 21 (Version 0.1.0) This module computes positions and velocities of a celestial small body, from a NASA SPICE SPK ephemeris kernel file of data type 21 (Extended Modified Difference Arrays). See You can get SPK files for many solar system small bodies from HORIZONS system of NASA/JPL. See This module reads SPK files of data type 21, one of the types of binary SPK file. At the point of Oct. 2018, HORIZONS system provides files of type 21 as binary SPK files by default. You can get type 21 binary SPK file for celestial small bodies through TELNET interface by answering back 'B' for 'SPK file format'. Also you can get type 21 binary SPK file from: Modules required - jplephem (version 2.6 or later) - numpy Usage from spktype21 import SPKType21 kernel = SPKType21.open('path') position, velocity = kernel.compute_type21(center, target, jd) print(kernel) ---- this line prints information of all segments kernel.close() where: path - path to the SPK file center - SPKID of central body (0 for SSB, 10 for Sun, etc.) target - SPKID of target body jd - time for computation (Julian date) position - a numpy array (x, y, z) velocity - a numpy array (xd, yd, zd) Modification Log 0.1.0 October 15, 2018 - Beta Release Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/spktype21/
CC-MAIN-2021-04
refinedweb
261
54.73
I'm new to final cut express. I color corrected a 60 minute video clip and attempted to export the sequence to Quicktime. It got about 80% complete and stopped due to out of disk space error. I have about 16 GB of remaining internal hard drive space on my macbook pro. I just received the software last night, so I do not yet understand scratch disk setup, etc. Is there a preference I should change or should I export to an external hard drive? I'm attempting to import the final clip into imovie and idvd. Alchroma Nov 14, 2012 2:43 PM Re: disk space error - final cut express 4 in response to mrholder Your Scratch Disc ( the disc where captures & media are stored) should ideally be on a disc other than the System drive eg. external firewire. This frees up your system drive for overall better performance. Video files are large and having 16 gig free is probaly the cause of the warning and export issue. DV is about 13 gig and hour and HD uo 40-50. FCE can use a Reference file export that uses way less space than a Self-Contained type. Reference exports work fine to iDVD as long as yu do everything on the same Mac. Scratch Disc settings are changed anytime through FCE->System Preferences. Al MartinR Nov 15, 2012 10:21 AM Re: disk space error - final cut express 4 in response to Alchroma In addition to Al's response, with only 16GB left on your internal hard drive you are effectively out of disk space. You need to move stuff off that drive and/or delete what you no longer need. If you are doing video it is wise to keep at least 50% free space especially if the drive capacity is 500GB or less. If you are doing HD video, here are some numbers to consider: - 1 hour source media (video clips) = ~45GB - 1 hour of render files of your 1 hour movie = ~45GB - 1 hour exported QT movie = ~45GB - 1 hour iDVD project of your completed QT movie = 2 to 4 GB So your 1 hour project could easily consume 140GB of disk space.
https://discussions.apple.com/thread/4507868?tstart=0
CC-MAIN-2015-11
refinedweb
367
76.66
Bear with me: MNIST is where everyone in machine learning starts, but I hope this tutorial is different from the others out there. Back when TensorFlow was released to the public in November 2015, I remember following TensorFlow’s beginner MNIST tutorial. I blindly copied and pasted all this code into my terminal and some numbers popped out as they should have. I thought, OK, I know there is something amazing happening here, why can I not see it? My goal was to make a MNIST tutorial that was both interactive and visual, and hopefully will teach you a thing or two that others just assume you know. In this tutorial, I will be using the machine learning library TensorFlow with Python3 on Ubuntu 14.04. If you need help installing TensorFlow on your own system check out my tutorial here. If you don't have numpy and matplotlib installed, you’ll need them. Open a terminal and type in: $ sudo apt-get install python-numpy python3-numpy python-matplotlib python3-matplotlib To begin, we will open up python in our terminal and import the MNIST data set: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import matplotlib.pyplot as plt import numpy as np import random as ran First, let’s define a couple of functions that will assign the amount of training and test data we will load from the data set. It’s not vital to look very deeply at these unless you want to figure out what’s going on behind the scenes. You will need to copy and paste each function and hit enter twice in your terminal: def TRAIN_SIZE(num): print ('Total Training Images in Dataset = ' + str(mnist.train.images.shape)) print ('--------------------------------------------------') x_train = mnist.train.images[:num,:] print ('x_train Examples Loaded = ' + str(x_train.shape)) y_train = mnist.train.labels[:num,:] print ('y_train Examples Loaded = ' + str(y_train.shape)) print('') return x_train, y_train def TEST_SIZE(num): print ('Total Test Examples in Dataset = ' + str(mnist.test.images.shape)) print ('--------------------------------------------------') x_test = mnist.test.images[:num,:] print ('x_test Examples Loaded = ' + str(x_test.shape)) y_test = mnist.test.labels[:num,:] print ('y_test Examples Loaded = ' + str(y_test.shape)) return x_test, y_test And we’ll define some simple functions for resizing and displaying the data: def display_digit(num): print(y_train[num]) label = y_train[num].argmax(axis=0) image = x_train[num].reshape([28,28]) plt.title('Example: %d Label: %d' % (num, label)) plt.imshow(image, cmap=plt.get_cmap('gray_r')) plt.show() def display_mult_flat(start, stop): images = x_train[start].reshape([1,784]) for i in range(start+1,stop): images = np.concatenate((images, x_train[i].reshape([1,784]))) plt.imshow(images, cmap=plt.get_cmap('gray_r')) plt.show() Now, we’ll get down to the business of building and training our model. First, we define variables with how many training and test examples we would like to load. For now, we will load all the data but we will change this value later on to save resources: x_train, y_train = TRAIN_SIZE(55000) Total Training Images in Dataset = (55000, 784) -------------------------------------------------- x_train Examples Loaded = (55000, 784) y_train Examples Loaded = (55000, 10) So, what does this mean? In our data set, there are 55,000 examples of handwritten digits from zero to nine. Each example is a 28x28 pixel image flattened in an array with 784 values representing each pixel’s intensity. The examples need to be flattened for TensorFlow to make sense of the digits linearly. This shows that in x_train we have loaded 55,000 examples each with 784 pixels. Our x_train variable is a 55,000 row and 784 column matrix. The y_train data is the associated labels for all the x_train examples. Rather than storing the label as an integer, it is stored as a 1x10 binary array with the one representing the digit. This is also known as one-hot encoding. In the example below, the array represents a 7: So, let’s pull up a random image using one of our custom functions that takes the flattened data, reshapes it, displays the example, and prints the associated label (note: you have to close the window matplot opens to continue using Python): display_digit(ran.randint(0, x_train.shape[0])) Here is what multiple training examples look like to the classifier in their flattened form. Of course, instead of pixels, our classifier sees values from zero to one representing pixel intensity: display_mult_flat(0,400) Until this point, we actually have not been using TensorFlow at all. The next step is importing TensorFlow and defining our session. TensorFlow, in a sense, creates a directed acyclic graph (flow chart) which you later feed with data and run in a session: import tensorflow as tf sess = tf.Session() Next, we can define a placeholder. A placeholder, as the name suggests, is a variable used to feed data into. The only requirement is that in order to feed data into this variable, we need to match its shape and type exactly. The TensorFlow website explains that “A placeholder exists solely to serve as the target of feeds. It is not initialized and contains no data.” Here, we define our x placeholder as the variable to feed our x_train data into: x = tf.placeholder(tf.float32, shape=[None, 784]) When we assign None to our placeholder, it means the placeholder can be fed as many examples as you want to give it. In this case, our placeholder can be fed any multitude of 784-sized values. We then define y_, which will be used to feed y_train into. This will be used later so we can compare the ground truths to our predictions. We can also think of our labels as classes: y_ = tf.placeholder(tf.float32, shape=[None, 10]) Next, we will define the weights W and bias b. These two values are the grunt workers of the classifier—they will be the only values we will need to calculate our prediction after the classifier is trained. We will first set our weight and bias values to zeros because TensorFlow will optimize these values later. Notice how our W is a collection of 784 values for each of the 10 classes: W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) I like to think of these weights as 10 cheat sheets for each number. This is similar to how a teacher uses a cheat sheet transparency to grade a multiple choice exam. The bias, unfortunately, is a little beyond the scope of this tutorial, but I like to think of it as a special relationship with the weights that influences our final answer. We will now define y, which is our classifier function. This particular classifier is also known as multinomial logistic regression. We make our prediction by multiplying each flattened digit by our weight and then adding our bias: y = tf.nn.softmax(tf.matmul(x,W) + b) First, let’s ignore the softmax and look what's inside the softmax function. Matmul is the function for multiplying matrices. If you know your matrix multiplication, you would understand that this computes properly and that x * W + b results in a Number of Training Examples Fed (m) x Number of Classes (n) matrix. If you don’t believe me, you can confirm it by evaluating y: print(y) Tensor("Softmax:0", shape=(?, 10), dtype=float32) That tells us what y is in our session, but what if we want the values of y? You cannot just print a TensorFlow graph object to get its values; you must run an appropriate session in which you feed it data. So, let’s feed our classifier three examples and see what it predicts. In order to run a function in our session, we first must initialize the variables in our session. Notice if you just run sess.run(y) TensorFlow will complain that you need to feed it data: x_train, y_train = TRAIN_SIZE(3) sess.run(tf.global_variables_initializer()) #If using TensorFlow prior to 0.12 use: #sess.run(tf.initialize_all_variables()) print(sess.run(y, feed_dict={x: x_train})) [[]] So, here we can see our prediction for our first three training examples. Of course, our classifier knows nothing at this point, so it outputs an equal 10% probability of our training examples for each possible class. But how did TensorFlow know the probabilities, you might ask; it learned the probabilities by calculating the softmax of our results. The Softmax function takes a set of values and forces their sum to equal one, which will give probabilities for each value. Any softmax value will always be greater than zero and less than one. Still confused? Try running this or read up on what softmax is doing mathematically: sess.run(tf.nn.softmax(tf.zeros([4]))) sess.run(tf.nn.softmax(tf.constant([0.1, 0.005, 2]))) Next, we will create our cross_entropy function, also known as a loss or cost function. It measures how good (or bad) of a job we are doing at classifying. The higher the cost, the higher the level of inaccuracy. It calculates accuracy by comparing the true values from y_train to the results of our prediction y for each example. The goal is to minimize your loss: cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) This function is taking the log of all our predictions y (whose values range from 0 to 1) and element wise multiplying by the example’s true value y_. If the log function for each value is close to zero, it will make the value a large negative number (i.e., -np.log(0.01) = 4.6), and if it is close to 1, it will make the value a small negative number (i.e., -np.log(0.99) = 0.1). We are essentially penalizing the classifier with a very large number if the prediction is confidently incorrect and a very small number if the prediction is confidendently correct. Here is a simple made up python example of a softmax prediction that is very confident that the digit is a 3: j = [0.03, 0.03, 0.01, 0.9, 0.01, 0.01, 0.0025,0.0025, 0.0025, 0.0025] Let’s create an array label of "3" as a ground truth to compare to our softmax function: k = [0,0,0,1,0,0,0,0,0,0] Can you guess what value our loss function gives us? Can you see how the log of “j” would penalize a wrong answer with a large negative number? Try this to understand: -np.log(j) -np.multiply(np.log(j),k) This will return nine zeros and a value of 0.1053, which when all summed up, we would consider a good prediction. Notice what happens when we make the same prediction for what is actually a 2: k = [0,0,1,0,0,0,0,0,0,0] np.sum(-np.multiply(np.log(j),k)) Now, our cross_entropy function gives us 4.6051, which shows a heavily penalized, poorly made prediction. It was heavily penalized due to the fact the classifier was very confident that it was a 3 when it actually was a 2. Next we begin to train our classifier. In order to train, we have to develop appropriate values for W and b that will give us the lowest possible loss. Below is where we can now assign custom variables for training if we wish. Any value that is in all caps below is designed to be changed and messed with. In fact, I encourage it! First, use these values, then later notice what happens when you use too few training examples or too high or low of a learning rate. If you set TRAIN_SIZE to a large number, be prepared to wait for a while. At any point, you can re run all the code starting from here and try different values: x_train, y_train = TRAIN_SIZE(5500) x_test, y_test = TEST_SIZE(10000) LEARNING_RATE = 0.1 TRAIN_STEPS = 2500 We can now initialize all variables so that they can be used by our TensorFlow graph: init = tf.global_variables_initializer() #If using TensorFlow prior to 0.12 use: #init = tf.initialize_all_variables() sess.run(init) Now, we need to train our classifier using gradient descent. We first define our training method and some variables for measuring our accuracy. The variable training will perform the gradient descent optimizer with a chosen LEARNING_RATE in order to try to minimize our loss function cross_entropy: training = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) Now, we’ll define a loop that repeats TRAIN_STEPS times; for each loop, it runs training, feeding in values from x_train and y_train using feed_dict. In order to calculate accuracy, it will run accuracy to classify the unseen data in x_test by comparing its y and y_test. It is vitally important that our test data was unseen and not used for training data. If a teacher were to give students a practice exam and use that same exam for the final exam, you would have a very biased measure of students’ knowledge: for i in range(TRAIN_STEPS+1): sess.run(training, feed_dict={x: x_train, y_: y_train}) if i%100 == 0: print('Training Step:' + str(i) + ' Accuracy = ' + str(sess.run(accuracy, feed_dict={x: x_test, y_: y_test})) + ' Loss = ' + str(sess.run(cross_entropy, {x: x_train, y_: y_train}))) In order to visualize what gradient descent is doing, you have to imagine the loss as being a 784 dimensional graph based on y_ and y, which contains different values of x, W, and b. If you can’t visualise 784 dimensions, that’s to be expected. I highly recommend Chris Olah’s blog to learn more amount the dimensions involved with MNIST. To explain things more simply in two-dimensions, we will use y = x^2: For each step in the loop, depending on how large the cross_entropy is the classifier will move a LEARNING_RATE step toward where it thinks cross_entropy’s value will be smaller. This lower point is calculated by TensorFlow using the derivative of the cross_entropy, which gives the slope of the tangent line at a given point. As it moves toward this new point, the values W and b change and the slope decreases. As in the case of y = x^2, you can think of this as moving toward X = 0, which is also called the minimum. If the learning rate is too small, the classifier will take very small steps when learning; if it's too high, the steps it takes will be too large, and it may figuratively “overshoot” the true minimum. Notice how near the end, the loss was still decreasing but our accuracy slightly went down? This shows that we could still minimize our loss on our training data, but this may not help us predict the unseen testing data used for measuring accuracy. This is also known as overfitting (not generalizing). With the default settings, I got an accuracy of about 91%. If I wanted to cheat to get 94% accuracy, I could set the test examples to 100. This shows how not having enough test examples can give you a biased sense of accuracy. Keep in mind this a very ineffective way to calculate our classifier. But I did this on purpose for the sake of learning and experimentation. Ideally, when training with large data sets, you train using small batches of training data at a time, not all at once. If you would like to learn how to do this, follow the tutorial on TensorFlow’s website. This is my favorite part. Now that we have calculated our weight cheatsheet, we can create a graph with the following code: for i in range(10): plt.subplot(2, 5, i+1) weight = sess.run(W)[:,i] plt.title(i) plt.imshow(weight.reshape([28,28]), cmap=plt.get_cmap('seismic')) frame1 = plt.gca() frame1.axes.get_xaxis().set_visible(False) frame1.axes.get_yaxis().set_visible(False) Now let’s visualize it: plt.show() This is a visualization of our weights from 0-9. This is the most important aspect of our classifier. The bulk of the work of machine learning is figuring out what the optimal weights are; once they are calculated, you have the “cheat sheet” and can easily find answers. (This is part of why neural networks can be readily ported to mobile devices; the model, once trained, doesn’t take up that much room to store or computing power to calculate.) Our classifier makes its prediction by comparing how similar or different the digit is to the red and blue. I like to think the darker the red, the better of a hit; white as neutral; and blue as misses. So, now that we have our cheat sheet, let’s load one example and apply our classifier to that one example: x_train, y_train = TRAIN_SIZE(1) display_digit(0) Let’s look at our predictor y: answer = sess.run(y, feed_dict={x: x_train}) print(answer) This gives us a (1x10) matrix with each column containing one probability: [[ 2.12480136e-05 1.16469264e-05 8.96317810e-02 1.92015115e-02 8.20863759e-04 1.25168199e-05 3.85381973e-05 8.53746116e-01 6.91888575e-03 2.95970142e-02]] But this is not very useful for us. So, we use the argmax function to return the position of the highest value and that gives us our prediction. answer.argmax() So, let us now take our knowledge to create a function to make predictions on a random digit in this data set: def display_compare(num): # THIS WILL LOAD ONE TRAINING EXAMPLE x_train = mnist.train.images[num,:].reshape(1,784) y_train = mnist.train.labels[num,:] # THIS GETS OUR LABEL AS A INTEGER label = y_train.argmax() # THIS GETS OUR PREDICTION AS A INTEGER prediction = sess.run(y, feed_dict={x: x_train}).argmax() plt.title('Prediction: %d Label: %d' % (prediction, label)) plt.imshow(x_train.reshape([28,28]), cmap=plt.get_cmap('gray_r')) plt.show() And now try the function out: display_compare(ran.randint(0, 55000)) Can you find any that guessed incorrectly? If you enter display_compare(2), you will find one digit the classifier got wrong. Why do you think it got it wrong? This is where this tutorial gets fun: notice what happens to the visualizations of the weights when you use 1-10 training examples. It becomes clear that using too little data makes it very hard to generalize. Here is a animation showing how the weights change as you increase your training size. Can you see what is happening? You can also see the limitations of a linear classifier; at a certain point, feeding it more data doesn’t help increase your accuracy drastically. What do you think would happen if we tried to classify a “1” that was drawn on the very left side of the square? It would have a very hard time classifying it because in all of its training examples, the 1 was very close to the center. I hope this helps make you more appreciative to know just how much is going on behind the scenes in MNIST. Keep in mind that this a neural network with two layers; it’s not deep learning. In order to get close to near-perfect accuracy, we have to start thinking convolutionally deep. If you would prefer to run a more interactive session, here is my GitHub repo with the Jupyter Notebook version of this. I had a lot of fun writing this and learning along the way. Thanks for reading, and most of all, I really hope something new clicked in your brain today.
https://www.oreilly.com/learning/not-another-mnist-tutorial-with-tensorflow
CC-MAIN-2017-34
refinedweb
3,277
63.7
On Fri, May 15, 2015 at 7:25 PM, Philip Martin <philip.martin_at_wandisco.com> wrote: > Philip Martin <philip.martin_at_wandisco.com> writes: > > > Philip Martin <philip.martin_at_wandisco.com> writes: > > > >> Prompted by the warnings I think there are some issues to fix. For > >> APR_HASH_KEY_STRING keys there is no protection against abnormally long > >> keys. combined_long_key() will allocate strlen() memory even if it is > >> many GB. The item will not get cached if key+data length is more than > >> 4GB but the memory for the key, which could be more than 4GB, will be > >> permanently allocated in the cache. There is also a problem with > >> overflow in membuffer_cache_set_internal() when calculating key+data > >> length, although in practice a key large enough to trigger this will > >> probably fail memory allocation first. > > > > Another issue: > > > > static svn_boolean_t > > entry_keys_match(const entry_key_t *lhs, > > const entry_key_t *rhs) > > { > > return (lhs->fingerprint[0] == rhs->fingerprint[0]) > > && (lhs->fingerprint[1] == rhs->fingerprint[1]) > > && (lhs->key_len == rhs->key_len); > > } > > > > I think the key_len comparison is wrong and should be removed. If two > > keys have fingerprints that collide it does not mean the key lengths are > > the same. When attempting to use two keys with colliding fingerprints > > the behaviour when the key lengths vary should be same as when the key > > lengths are the same and the key data varies. > Not necessary. It is true that we could decide to *only* use the fingerprint as discriminator. But the implementation here includes the key length; it reduces the number of conflicts that result in entries that evict each other. Most fixed-length keys are 16 bytes long and for them, the fingerprint is almost identical to the key and conflicts are extremely unlikely. So, varible-length keys are the one that may have fingerprint conflicts now due to the weakness of FNV1. For them, however, the key_len (often derived from paths) has a good chance of being different. Note that if the key_len differs, it *cannot* be the same key. Hence, including the key_len does not create false negatives. > Another issue: find_entry() now calls drop_entry() in more cases and can > now call it when find_empty==FALSE during read operations. On Unix when > using the read-write lock this means the cache gets modified while only > holding a read lock, not a write lock, and that can corrupt the cache. > > If we use read-write locks then when read detects a fingerprint > collision it cannot modify the cache to clear the collision, it will > have to return NULL and leave the entry in the cache. > You are absolutely right. Fixed in r1679681. -- Stefan^2. Received on 2015-05-16 06:48:39 CEST This is an archived mail posted to the Subversion Dev mailing list.
https://svn.haxx.se/dev/archive-2015-05/0092.shtml
CC-MAIN-2019-22
refinedweb
445
62.38
). Aliases are no longer available in Brian 2. scalar parameter and update it using a user-defined function (e.g. a CodeRunner). Flags¶ A new syntax is the possibility of flags. A flag is a keyword in brackets,. - scalar - this means that a parameter or subexpression isn’t neuron-/synapse-specific but rather a single value for the whole NeuronGroup or Synapses. A scalar subexpression can only refer to other scalar variables. Different. An open question is whether we should also allow it to depend on a parameter not defined as constant (I would say no). Currently, automatic event-driven updates are only possible for one-dimensional linear equations, but it could be extended.') In contrast to Brian 1, Equations objects do not save the surrounding namespace (which led to a lot of complications when combining equations), they are mostly convenience wrappers around strings. They do') In contrast to Brian 1, specifying the value of a variable using a keyword argument does not mean you have to specify the values for all external variables by keywords. [Question: Useful to have the same kind of classes for Thresholds and Resets (Expression and Statements) just for convenience?]
http://brian2.readthedocs.io/en/2.0a8/user/equations.html
CC-MAIN-2017-39
refinedweb
195
54.12
New in version 2.1. for line in fileinstead. This module defines a new object type which can efficiently iterate over the lines of a file. An xreadlines object is a sequence type which implements simple in-order indexing beginning at 0, as required by for statement or the filter() function. Thus, the code import xreadlines, sys for line in xreadlines.xreadlines(sys.stdin): pass has approximately the same speed and memory consumption as while 1: lines = sys.stdin.readlines(8*1024) if not lines: break for line in lines: pass except the clarity of the for statement is retained in the former case. An xreadlines object s supports the following sequence operation: If successive values of i are not sequential starting from 0, this code will raise RuntimeError. After the last line of the file is read, this code will raise an IndexError.See About this document... for information on suggesting changes.
http://www.wingware.com/psupport/python-manual/2.2/lib/module-xreadlines.html
CC-MAIN-2016-50
refinedweb
153
58.28
Hi guy, before continuing with the operators, today I want to explain the Marble Diagrams. The Marble Diagrams is a timeline where you can illustrate the state of your observable during its execution. The actors in this diagram are timeline and values(circle). The timeline is used to represent the time during the execution of the observable though the circles indicate the values emitted. But let me show you an example: This example is based on this code import { Observable } from "rxjs"; import { map } from "rxjs/operators"; const source$ = new Observable<number>(observer => { let count = 0; const id = setInterval(() => { if (count++ < 3) { observer.next(count); } else { clearInterval(id); observer.complete(); } }, 1000); }); source$.pipe(map(value => value * 2)).subscribe({ next: console.log, }); As you can notice, in the diagram there are two timelines, one for the source and the other for the map operator. In the first timeline you can see when the source emits the value, in the second timeline you can see the result of the transformation after the execution of the map operator. To build a Marble diagram you need to keep in mind some easy rules: there is always a timeline that represents the source observable, there are N timelines as many operators as you need to display, every timeline illustrates the state of the values after the execution of the operator indicated in the timeline and finally, you need to use a circle to represent the values. This tool is very convenient to illustrate the transformation of the observable during its execution and it helps us to have an image of the state of the observable execution. In addition to the Marble Diagram you can use the Marble Testing to test the execution of you Observable. The Marble testing uses a special format to represent the timeline and the value during the execution, but I will speak about it in the future. To reinforce the Marble Diagram concept let me show you another example import { Observable } from "rxjs"; import { delay, map } from "rxjs/operators"; const source$ = new Observable<number>(observer => { let count = 0; const id = setInterval(() => { if (count++ < 3) { observer.next(count); } else { clearInterval(id); observer.complete(); } }, 1000); }); source$ .pipe( map(value => value * 2), delay(1500) ) .subscribe({ next: console.log, }); In this example you can see how the observable in the first operator doubles the value and then it waits 1.5 seconds before emitting the result. To represent this case the marble diagram has 3 timelines, one with the source, one with the map operator and one with the delay operator. Every timeline indicates the value during the execution of its operator so you can see the behaviour of this implementation. It's all from the marble diagram. See you soon guys! Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/this-is-learning/rxjs-marble-diagrams-4jmg
CC-MAIN-2021-49
refinedweb
459
54.52
… Rd Sharma Class 12 Maths.pdf !EXCLUSIVE! ☘️ Rd Sharma Class 12 Maths.pdf !EXCLUSIVE! ☘️ Rd Sharma Class 12 Maths.pdf Rd Sharma Class 12 Maths.pdf Cracked 2022 Latest Version RD Sharma Class 12 Mathematics PDF. apruti industrial university pdf. pdf. in korematics class 10, question number 2, (a) what will be the standard deviation of iif . Jan 25, 2019 · Download free RD Sharma Class 9 Maths Solutions NCERT Solutions pdf for class 9, Class 10, Class 11, Class 12 and Other . PDF Pearson Education Topic 4 Maths Answer Sheet Pearson 4th Grade. Pearson Realize ChEAT SHEET K-12 Reading Language Arts English K-12. rd sharma pdf download here. the present democratic country of India, it is essential that young Indian should be schooled in the . Math · MTS CX-1 – English · Maths · Class 8 · CBSE · Level 4;. Part3 . Math IIT JEE Answers – ajinkya. nehal sharma class 12 pdf free download. ninth standard mathematics solution contains two types of solutions such as negative form and positive form. one may require one part only which will be divided into . Diploma In Website Design: 5 Steps to a Complete Online Design Process | eHow. | GoPagination. The assignment should have detailed answer. class 12 mathematics pdf free download free pdf of ncert solutions for all chapters of class 10 rd sharma class 12 mathematics book pdf free download for iit jee advanced objective. Jan 17, 2019 · Download free RD Sharma Class 9 Maths Solutions NCERT Solutions pdf for class 9, Class 10, Class 11, Class 12 and Other . IIT JEE Advanced Exam Solved Paper | JEE Main & JEE Advanced. CC : 10th Mathematics – Objective & Descriptive – 304 – Question. The present democratic country of India, it is essential that young Indian should be schooled in the . We have full description about books available here. And If this is not true then please tell us. – Rakshasi. Maths by RD Sharma Class 10-11 Mathematics Solutions for exams in India NCERT books are useful for students since they come from the well-known and authentic teacher R D Sharma who was the Chief Editor of . Download free ICSE Solutions for Mathematics Class 10: Gauss-Bonnet Formula, R. Page 8. R D Sharma Maths Solutions for Class 9 to 12.pdf Page 10. Direct Download. R D Sharma Maths Solution Class 10 to 12 (CBSE and ICSE Board). Maths Solutions by renowned. PDF R D SharmaÃs Maths Solutions, all solved by leading Maths experts of Doubtnut. NEW RD SHARMA MATHS BOOK PART I AND II NEED THE FREE PDF EBOOK OF R D.. ncert solutions mathematics book pdf free download – cadastro de despachos. RD Sharma Solutions for Class 9 to 12.pdf. Page 12. rd sharma solutions math class 12 free download – connectdocnet. The latest edition of the RD Sharma Class 12 Maths textbook is solved by. Sth Class Xsolutions. INR Class 12solutions.ns.in. RD Sharma Class 12 Solutions for School Standards are provided below.. . (3 MB).. RD Sharma Mathematics Solutions for class 9 to 12 (CBSE and ICSE Board). RD Sharma Solutions for class 10 Maths pdf provided here covers all the. (PDF Ready). Founded in the year 2016, the Mission of Doubtnut is to make available the best and free answer material to all those who are interested in solving mathematical problems. Having strong support of the Director of Doubtnut, an eminent name in the field of Maths, it has become the first choice of thousands of Mathematicians and Students around the world. . Last Updated : February 19, 2020. Download Freely!. ICSE NCL Class 10 Mathematics – R D Sharma Solutions. On Read/Download  Â. You can directly Download RD Sharma Solutions. ICSE and ISC Class 9 to 12 to CBSE and. 3rd Edition Math Solutions (Covering Class 9 to 12). Welcome to the Maths Solutions section of Doubtnut. In this.Q: JSF Converter and actions I’m a beginner with JSF and I’m trying to use a Converter and action to get the value from the user to the bean property. The Converter looks like that: public class ObjectToUriConverter implements Converter { private Object objeto; private Uri url; public Object toObject(FacesContext context, UIComponent component, String value) { if (value!= null) { 648931e174 Junior solved 12th standard Mathematics problems. Easily solve RD Sharma 12th Maths solutions at free of cost.. NCERT Chapter Solutions NCERT Solutions for Class 9 Maths Chapter 5 Heron’s Formula Exam 12 NCERT Solutions for Class 8 Maths.The BlackBerry Bold Tour The BlackBerry Bold Tour is an upcoming five-inch Android-based smartphone manufactured by BlackBerry, following on from the launch of the BlackBerry Bold. The device was announced on 15 January 2011 by BlackBerry CEO Thorsten Heins, and marked the first time a BlackBerry device had featured on display at a CES. The device was previously known by the codename Kova, after Kova are the key caps, similar to the Torch series. The name Bold Tour was originally announced to be taken out of the foldable keyboard processor, but after feedback from customers in focus groups, it was confirmed to have been scrapped in favour of the Tour name. Unlike the BlackBerry Curve, the Bold Tour was not sold as an international device, but instead is purely a Canadian-only device, part of the exclusive BlackBerry Tour lineup. Specifications Hardware The BlackBerry Bold Tour hardware specifications are based on the same hardware seen in the BlackBerry Bold 9900, except on a smaller screen. It is a clamshell with a black matte back which incorporates the keys and trackpad. The back of the device appears to be brushed metal with soft-touch rubberised detailing, and a power button which is recessed on the right-hand side. A blue LED is located on the top-right corner of the device. There are four physical buttons on the side of the phone: menu, back, search, and one for app launch. On the front of the device are capacitive Android buttons. Screen The Bold Tour has a touchscreen display, with a resolution of 480×360 and a pixel density of 154 ppi. For comparison, the BlackBerry Curve’s screen is 320×240 at 114ppi. The screen is 4.3 inches in size, and is polarized for outdoor usability. Although this is a smaller screen than the 5.2 inch screens of most smartphones, the Bold Tour is still larger than many competitors with screens of 4 inches or smaller. The BlackBerry Bold’s screen is rated to be “high-resolution at high brightness” and “high-sensitivity in direct sunlight”. Unlike the Bold 9900, the Bold Tour does not feature a physical keyboard. Instead, it has a soft Buy RD Sharma Maths Solutions For Class 12. Free download and Print NCERT . Free Download rd sharma maths solutions for class 12. Free Download rd sharma maths solutions for class 12 FREE NCERT Book Solved. NCERT book solution for class 7th 9th 10th. Free Mathematic solution books for class XII Maths (Free Download). Direct and Inverse Proportions RS Aggarwal Class 8 Maths Solutions CCE. Board (PDF) The classes will not be held for grade X and XII on Wednesday, 23 October. Free download RD sharma maths solutions for class 12. Free download and Print NCERT . Download Free Books For Your NOOK Tablet can come in PDF and EPUB file formats.. ePub files. book – les cent une – filetype rd sharma class 12 pdf-free ebook.. edisi 10 en. rd sharma solutions for class 12 maths – free pdf download in 12th grade is a. NCERT Solutions for Class 12 Maths Chapter 5 Exercise 5. Free download and Print NCERT . Free RD Sharma Maths Solutions for Class 12 Chapter wise Solutions solved by Expert Mathematics Teachers on Vedantu.com as per NCERT . Class 12 Mathematics- Free Chapter 5 Books Here are the notes for 9th Class Maths in PDF for Federal Board for. Free NCERT Solutions for class 6, 7, 8, 9, 10, Maths, Science, . Download Complete NCERT Maths books series from class 1 to 12 PDF Free,. RD sharma class 12 maths book pdf download: Hey everyone, in this post will . Buy RD Sharma Maths Solutions For Class 12. Free download and Print NCERT . Free Mathematic solution books for class XII Maths (Free Download). Direct and Inverse Proportions RS Aggarwal Class 8 Maths Solutions CCE. Board (PDF) The classes will not be held for grade X and XII on Wednesday, 23 October. Free download and Print NCERT . Jan 16, 2020 · MP Board Class 8th Sanskrit Solutions Guide Pdf Free. Buy DAV – Mathematics Class 7 by Full Marks Books Online shopping at low Price in India.. >The classes will not be held for grades X and XII on Wednesday, 23 October. Free RD Sharma Solutions for Class 7 Mathematics NCERT Solutions, Tests . NCERT Solutions
https://madisontaxservices.com/rd-sharma-class-12-maths-pdf-exclusive
CC-MAIN-2022-40
refinedweb
1,461
66.54
Hide Forgot From Bugzilla Helper: User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4.1) Gecko/20031114 Description of problem: The Java VM supplied with Matlab 6.1 and 6.5 cannot run with Fedora Core 1 and java built in matlab 6.1 still doesn't work (I read about similar problem with java on ) Here is the output from matlab: . Whot is worse, I tried export LD_ASSUME_KERNEL=2.2.5 and 2.4.1 and 2.4.19. None of these work. The problem is very important for many of people who make serious job on linux. When I changed MATLAB_JAVA environment variable to point SUN's java 1.4.2 the matlab start with java GUI but, after opening one more window of matlab (like editor or preferences) matlab freezes. I use system locale pl_:PL and have SUN's java 1.4.2 with locale for en,gb,de,es. I don't know if it could be locale problem or maybe NPTL or glibc because I cannot find any log from java crash. Same was with standard version of glibce supplied with fedora and with upgraded version glibc-2.3.2-101.1. Version-Release number of selected component (if applicable): glibc-2.3.2-101.1 How reproducible: Always Steps to Reproduce: 1.run matlab from CLI 2. 3. Actual Results: . Matlab works only in text mode without java GUI and without graphic debugger and editor. Aditional windows (like axes setu of plots) cannot open. Expected Results: Matlab working with java GUI Additional info: Very important because I read about similar problems with other applications and java under Fedora 1 (test 3, RedHat Linux 9). Try using some less buggy JVM. Latest Sun JDK should work just fine for example. Or, as a workaround for the buggy JVM, you can try: gcc -O2 -shared -o ~/libcwait.so -fpic -xc - <<\EOF #include <errno.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> and run the program with LD_PRELOAD=~/libcwait.so LD_ASSUME_KERNEL=2.4.19 in environment. Hi! That solution works really good! I wonder if this piece of code will by used as patch on glibc int the next wersion of glibc rpm available in updated of Fedora Core 1. Will it? No, it will not. We have been applying it as workaround for 2 years and vendors did not bother to fix their buggy software. Great :) I though I'd chime in here to describe what I see, in case it helps others who come across this bug report. I am not asking for anyone (Jakub) to fix anything. I find the following in RHL 9: First of all, I see basically the same symptoms that bednar sees with Matlab R12.1. I didn't use the fix that Jakub suggested. A fix for me is to install the latest release of Sun JRE 1.3.1, and tell matlab to use it. Matlab R12.1 comes only with JRE 1.1.8 included, and it runs fine on RHL 8, but it doesn't run on RHL 9. Providing JRE 1.3.1 makes Matlab R12.1 run on RHL 9; perhaps this fix would work on FC 1 as well. Incidentally Matlab R13 and R13SP1 both come with JRE 1.3.1, and use it by default. They also come with 1.1.8, but do not use it by default (at least in my installs). I have been trying to get J2RE 1.4.2 to work with Matlab, and have had no success. Googling suggests that all other reporters have failed as well. I was intrigued by Jakub's fix, but this did not help me use Matlab R13 with J2RE 1.4.2 on RHL 9. It has the same problem that bednar described when using J2RE 1.4.2: you can open e.g. the Matlab desktop Java window just fine, but if you open e.g. an editor window (which also uses Java), the editor window doesn't fully render, and Matlab permanently hangs (I've let it run overnight with no return to normal state). I had the same problem running java launcher of JRE 1.3.1_08. We have big java project that currently runs only on JRE 1.3.1. I installed JRE 1.3.1_12 and it works! Best regards, Ciril
https://bugzilla.redhat.com/show_bug.cgi?id=110610
CC-MAIN-2019-13
refinedweb
737
78.25
07-07-2017 01:48 PM Hello, I am trying to use the I2C embedded in the ARM. I used the master polled example to reproduce this code: #include <stdio.h> #include "xiicps.h" #include "xparameters.h" #define TAS5706_0_I2C_ID XPAR_PS7_I2C_0_DEVICE_ID #define TAS5706_ADDRESS 0x36 #define TAS5706_I2C_SCL_RATE 20000 static XIicPs Iic; int main(void) { int Status; XIicPs_Config *Config; unsigned char u8TxData[2], buff[1024]; int32_t ByteCount; u8TxData[0] = 0x00; u8TxData[1] = 0x01; /* * Initialize the IIC driver so that it's ready to use * Look up the configuration in the config table, * then initialize it. */ Config = XIicPs_LookupConfig(TAS5706_0_I2C_ID); if (NULL == Config) { return XST_FAILURE; } Status = XIicPs_CfgInitialize(&Iic, Config, Config->BaseAddress); if (Status != XST_SUCCESS) { return XST_FAILURE; } /* Set the IIC serial clock rate. */ XIicPs_SetSClk(&Iic, TAS5706_I2C_SCL_RATE); while(1) { XIicPs_MasterSendPolled(&Iic, u8TxData, 2, TAS5706_ADDRESS); while(XIicPs_BusIsBusy(&Iic)); usleep(50000); //XIicPs_MasterRecvPolled(&Iic, buff, 2, TAS5706_ADDRESS); } return 0; } I am only seeing the address on the osciloscope on the SDA pin. Have I missed something in the code? Thanks for the help. 07-07-2017 03:04 PM Could you post the status of the Interrupt Mask Register after each I2C operation? 07-07-2017 04:40 PM 07-08-2017 09:34 PM Seeing the address on the bus is a very good start. Not moving past the address may not necessary be an issue with your program but it could be the slave device not responding. After the address is sent on the bus by the master, it is followed by the R/W bit (also sent by the master) and then the slave will acknowledge. The acknowledge is the SDA (the data line) being held low.for at one clock cycle (there could and will most likely be many many more cycles of SDA held low). Have a look with your scope to see if the SDA is being held low after the R/W cycle. If is not then the slave hasn't recognized the address and this will provoke an abort of the transfer. For your convenience, the I2C standard can be retrieved from: Regards. 07-09-2017 08:20 AM Nice explanation. Later you need to see if data transaction followed by address. I see that you have two data to send. regards Praveen 07-09-2017 09:33 AM To make sure I didn't add some confusion, when the slave holds the SDA line low for many many clock, the SCL (clock) line is also held low by the slave. That's how a slave can temprary freeze the bus transaction until it's ready to send or read the data. Regards 07-09-2017 03:31 PM I have to check again at the lab (I will do it in about 15 hours), but if I recall correctly, I see the address, then the next bit is low (I believe it is then the acknowledge from the slave) and the SDA goes back to 1 and stays like that. I will post a picture and also try with another slave. 07-09-2017 05:26 PM The bit after the address is the R/W bit. If it is low, therefore it means a write transfer on the bus. As you are doing a write of 2 bytes, so far so good. If the line doesn't also remain low for the following bit, it means the slave device didn't respond. Looking forward the scope capture Regards 07-10-2017 06:52 AM 07-10-2017 06:59 AM 07-10-2017 08:41 AM 07-10-2017 10:10 AM It looks like you're getting very close to nail down the problem Have a look at sections 3.1.2 & 3.1.6 in the standard. Regards 07-10-2017 10:15 AM A reminder: there are 7 address bits, not 8 Regards 07-10-2017 10:42 AM 07-10-2017 10:55 AM 07-10-2017 10:59 AM You're correct. The scope shows 0110110,0,0,11111 0110110 is the address 0 is R/W indicating a write transfer 0 is the slave acknowledging Then the clock stops. So the Zynq does not see/process the acknowledge from the slave. As tn45eng mentioned, you'll have to check the interrupt mask register. You can get all the information about the I2C controller registers in Appendix B of the Zynq TRM Also check section 20.2.2 in the TRM. Regards 07-10-2017 11:16 AM 07-10-2017 11:20 AM To read the register: MASK_VALUE = *((volatile unsigned int *)REGISTER_ADDRESS); You'll find the address of the register in Appendix B of the TRM 07-10-2017 12:57 PM I have seen that the XIicPs_MasterSendPolled function configures the control register and it sets the ACK bit. After it is called, I read the control register with `RegVal = XIicPs_ReadReg(Config->BaseAddress, XIICPS_CR_OFFSET);` which returns 0x0e. This means that ACK_EN is enabled (Page 1385 from the Zynq TRM). If I read the interrupt status register, it reads 0x04, NACK set to 1 (Transfer not acknowledged. slave responds with a NACK or master terminates the transfer before all data is supplied). Shouldn't it be one or the other, or complementary? 07-10-2017 03:18 PM In the control register, no choice as the ACK bit must be set (see the description text for that bit). For the status register #2, you now know the 2 possible causes for not seeing the 2 bytes being sent after the address on the bus. You should read and understand the standard otherwise you are trying to debug this a bit on the blind side. You have a scope,which is great because you can see what is going on the bus. Carefully read and reread TRM's chapter #20 and correlate / double check with your code (and Xilinx's BSP) & the registers. 07-10-2017 04:15 PM Well, as far as setting the register, accordingly to the TRM: 1. Write to the control register to set up SCL speed and addressing mode. This is done by `XIicPs_SetSClk(&Iic, TAS5706_I2C_SCL_RATE);` in my main and XIicPs_SetupMaster(InstancePtr, SENDING_ROLE); called from XIicPs_MasterSendPolled, if I am not mistaken. 2. Set the MS, ACKEN, and CLR_FIFO bits and clear the RW bit in the Control register. This is again done by XIicPs_SetupMaster. Therefore, the procedure from the TRM (Page 606) is being followed by the functions generated in the BSP, and when I read the registers, I believe I read them as the should be so I am lost on how to proceed. 07-10-2017 05:04 PM We don't use Xilinx's BSP as we prefer to create and provide drivers with simple APIs limited to init / recv / send using compile time configuration for polling / ISR / DMA transfers. So I can't provide meaningful feedback on the internal of the BSP functions, but it looks like the registers values are OK. If you want to try something different, all our drivers are free supplied with working demos The I2C demos supports 5 or 6 different devices. You can fill a request on our website. Regards 07-11-2017 12:25 PM 07-12-2017 06:53 AM Ok, I am back at the lab with the scope. I have changed in the XIicPs_SetupMaster function, called within the XIicPs_MasterSendPolled that I call from my main (in the infitive loop), where it configures the ACK bit: /* * Set up master, AckEn, nea and also clear fifo. */ ControlReg |= (u32)XIICPS_CR_ACKEN_MASK | (u32)XIICPS_CR_CLR_FIFO_MASK | (u32)XIICPS_CR_NEA_MASK | (u32)XIICPS_CR_MS_MASK; if (Role == RECVING_ROLE) { ControlReg |= (u32)XIICPS_CR_RD_WR_MASK; }else { ControlReg &= (u32)(~XIICPS_CR_RD_WR_MASK); } XIicPs_WriteReg(BaseAddr, XIICPS_CR_OFFSET, ControlReg); I changed it so it looks like this: ControlReg |= (u32)XIICPS_CR_CLR_FIFO_MASK | (u32)XIICPS_CR_NEA_MASK | (u32)XIICPS_CR_MS_MASK; So I am not setting the ACK bit, but when I see the SDA on the scope, it still only outputs the address. My address is #define TAS5706_ADDRESS 0x36 // 0011 0110. It is correct to do XIicPs_MasterSendPolled(&Iic, u8TxData, 2, (TAS5706_ADDRESS>>1));, as it is a 7-bit address. Right? Thanks for the help. 07-12-2017 06:59 AM 07-12-2017 08:36 AM So from the IMR values you reported here (0x04), it is clear that the slave doesn't acknowledge the transfer (NACK bit is set). The goal is to get the COMP bit set in the IMR. You are seeing some value in the clock and data so the pin mapping is right. So its either you are missing some setting in the processor or the hardware interface is not OK or the chip itself is not OK. Your hardware is new so there are a couple some basic questions like does the hardware work at all and what is the address? Since this is a new hardware will first verify if the hardware is OK and get back to settings later. As for address, one lazy and easy thing to do with I2C is to run a while loop with all possible address 0 to 128(normal addressing) to find out all the slaves connected to it. So you don't have to wonder if you have the address right. Voltage levels, clock speed, reset and pull up resistor values are the next thing you would want to look into. Did you check if the chip supports the clock speed you are running? The voltage level of the I2C pins in ZynQ matches up with that of the chip? Apply a hard reset to the chip and make sure it is out of reset? What is the pull up resistor value you are using? 07-14-2017 10:37 AM 07-14-2017 08:25 PM The interrupt status register bits are sticky Sec 20.2.8 in the TRM. So once a bit has been set, it will remain set until manually cleared. Bit #1 was likely set before the end of the transfer. 07-15-2017 05:45 AM 07-17-2017 07:50 AM
https://forums.xilinx.com/t5/Processor-System-Design-and-AXI/Zynq-I2C-only-outputs-address/td-p/777390
CC-MAIN-2020-40
refinedweb
1,658
70.13
wcscat - concatenate two wide-character strings #include <wchar.h> wchar_t *wcscat(wchar_t *ws1, const wchar_t *ws2); The wcscat() function appends a copy of the wide-character string pointed to by ws2 (including the terminating null wide-character code) to the end of the wide-character string pointed to by ws1. The initial wide-character code of ws2 overwrites the null wide-character code at the end of ws1. If copying takes place between objects that overlap, the behaviour is undefined. The wcscat() function returns ws1; no return value is reserved to indicate an error. No errors are defined. None. None. None. wcsncat(), <wchar.h>. Derived from the MSE working draft.
http://pubs.opengroup.org/onlinepubs/007908775/xsh/wcscat.html
CC-MAIN-2013-20
refinedweb
110
65.32
This pattern allows the client to absorb data from mutiple sources of data (tables, other XML documents etc.) and delinks the front end GUI from the middle tier. Where can it be used (sample): 1: for report generation, after extracting data from multiple sources. 2: workflow queries How it works: Entity EJBs model the Database (DB here onwards), so that the DB is abstracted by the EJBs. This is a known pattern documented on this site and elsewhere. These entity beans are next wrapped in session beans. This is also a known pattern documented on this site and elsewhere. These session beans perform the query on the entity EJBs and format the result of the finders from the entity EJBs into XML documents. These XML documents are passed back to the servlet (or session EJB client) which called the session EJB. The servlet can then parse this XML document and display the data whichever way it wants via XSL or can pass the data to other servlets for processing. Each table can be represented by a XML Schema so that the client can parse it. This XMLSchema can be got from the actual table schema by mapping the table schema. This helps the display servlet to merge data from multiple sources and give a unified view. The display servlet can then pass this back as a HTML document or even a SOAP response. The EJBs act as XML data sources effectively forming a database to XML bridge. Step by Step: a) The database is mirrored by Entity EJBs (CMP or BMP). b) The entity beans are covered with a session EJB facade. c) The clients call methods on the session EJBs to query data. d) The session EJBs, after getting the results from the entity EJBs, format the query result into a XML document and return the XML document back to the client. e) This calls for each table to have a XML Schema giving what type of data it contains, so that the client knows how to parse it. f) This allows the client to get XML data from various sources (tables) and display it via XSL as whatever format it wants. g) The client can be a servlet or JSP or any EJB client. h) This allows multiple datasources to be combined into a single view and enables the EJBs to give a XML based interface. You can even use SOAP to pass this XML data to various other types of clients. XML data generation from EJBs (56 messages) Threaded Messages (56) - XML data generation from EJBs by Venkat Harish Devanur on July 27 2000 08:11 EDT - XML data generation from EJBs by Girish Bhatia on July 31 2000 11:39 EDT - XML data generation from EJBs by JT Wenting on August 21 2000 04:26 EDT - XML data generation from EJBs by Channing Walton on August 25 2000 12:12 EDT - XML data generation from EJBs by zebah singh alfred on June 07 2001 05:57 EDT - XML data generation from EJBs by suresh babu on August 01 2000 07:16 EDT - XML data generation from EJBs by phani kumar on September 27 2000 03:51 EDT - XML data generation from EJBs by pankaj grover on August 01 2000 13:35 EDT - XML data generation from EJBs by Anil Lobo on August 02 2000 02:34 EDT - XML data generation from EJBs by pankaj grover on August 02 2000 04:07 EDT - XML data generation from EJBs by Anil Lobo on August 03 2000 12:26 EDT - XML data generation from EJBs by kiran kumar on August 04 2000 05:51 EDT - XML data generation from EJBs by Varadarajanarayanan Srinivasan on August 30 2000 03:47 EDT - XML data generation from EJBs - jeyabalan by jeyabalan P on June 22 2003 05:55 EDT - XML data generation from EJBs by nabil bousaada on August 05 2000 01:45 EDT - XML data generation from EJBs by Jeyaraman Raju on September 27 2000 12:10 EDT - XML data generation from EJBs by Shawn Wall on August 02 2000 18:18 EDT - XML data generation from EJBs by Robert McIntosh on August 08 2000 10:24 EDT - XML data generation from EJBs - why use EntityBeans by Stanislav Markin on August 09 2000 07:00 EDT - Passing XML data by Alex Burdenko on August 11 2000 22:02 EDT - Passing XML data by Alex Burdenko on August 11 2000 10:06 EDT - Passing XML data by Stefan Frank on September 25 2000 10:30 EDT - XML data generation from EJBs by Channing Walton on August 12 2000 14:03 EDT - XML data generation from EJBs by Robert McIntosh on August 16 2000 10:49 EDT - XML data generation from EJBs by Channing Walton on August 19 2000 07:15 EDT - XML data generation from EJBs by Channing Walton on August 19 2000 07:17 EDT - XML data generation from EJBs by Robert McIntosh on August 22 2000 01:16 EDT - XML data generation from EJBs by Anil Lobo on August 23 2000 04:28 EDT - XML data generation from EJBs by Ravi Reddy on September 29 2000 04:03 EDT - XML data generation from EJBs by Kashmiri Kaser on February 06 2001 01:04 EST - XML data generation from EJBs by Jeff Mackay on March 09 2001 11:37 EST - toXml() is a good idea, but a bad method by Alex Chaffee on October 06 2000 13:24 EDT - toXml() is a good idea, but a bad method by Georgi Kostadinov on October 24 2000 12:49 EDT - toXml() is a good idea, but a bad method by Idan Efroni on December 06 2000 11:43 EST - toXml() is a good idea, but a bad method by Idan Efroni on December 06 2000 11:53 EST - XML data generation from EJBs by Rob Murtha on August 18 2000 02:02 EDT - XML data generation from EJBs by Justin Echternach on August 31 2000 09:51 EDT - XML data generation from EJBs by olivier delbos on October 25 2000 08:33 EDT - XML data generation from EJBs by aa aa on August 31 2000 12:02 EDT - XML data generation from EJBs by Josh Price on September 07 2000 12:07 EDT - XML data generation from EJBs by Stu Charlton on September 13 2000 23:42 EDT - XML data generation from EJBs by Dino Chiesa on September 20 2000 12:46 EDT - an update.. by Stu Charlton on September 28 2000 14:32 EDT - legacy integration by Jeff Mackay on September 29 2000 01:23 EDT - XML data generation from EJBs by Chad Brockman on October 24 2000 12:46 EDT - XML data generation from EJBs by Anil Lobo on October 25 2000 18:35 EDT - XML data generation from EJBs by Anil Lobo on October 25 2000 19:20 EDT - XML data generation from EJBs by Chris Sellers on October 27 2000 10:26 EDT - XML data generation from EJBs by Anil Lobo on October 31 2000 06:00 EST - XML data generation from EJBs by Justin Hartley on January 17 2001 20:27 EST - XML data generation from EJBs by sridhar sirigiri on December 13 2000 13:18 EST - XML data generation from EJBs by Swami Iyer on December 19 2000 14:38 EST - XML data generation from EJBs by steve selak on January 11 2001 09:40 EST - XML data generation from EJBs by Rahul Murudkar on February 06 2001 03:03 EST - XML data generation from EJBs by Rodolfo Rothganger on March 26 2001 14:47 EST - XML data generation from EJBs by Stacy Curl on April 09 2001 15:02 EDT XML data generation from EJBs[ Go to top ] Hey - Posted by: Venkat Harish Devanur - Posted on: July 27 2000 08:11 EDT - in response to Anil Lobo Can you give the sample code thanks bye XML data generation from EJBs[ Go to top ] How XML data is passed back to the Servlet...in the form of hashtable or vectore or ????? - Posted by: Girish Bhatia - Posted on: July 31 2000 11:39 EDT - in response to Anil Lobo also, is it possible for you to provide a sample XML code that parase the XML document and display all the elements as data.....I have done it for one specific node...but wondering what would be the trick to gel all the elements node ..from xml..and store them in java string...so we can use it whatway way we want... -Girish Bhatia XML data generation from EJBs[ Go to top ] I can see several ways to transfer the XML back to the servlet: - Posted by: JT Wenting - Posted on: August 21 2000 04:26 EDT - in response to Girish Bhatia 1) as a Stream 2) as a StringBuffer 3) as a XML DOM Object 4) (cumbersome, might be required for very large amounts) as a filename (file being generated by the bean and read by the servlet, find some way to delete the files at regular intervals). XML data generation from EJBs[ Go to top ] My understanding is that EJB's aren't allowed to access the Filesystem or take part in any IO of that nature. Is this correct ? - Posted by: Channing Walton - Posted on: August 25 2000 12:12 EDT - in response to JT Wenting Channing XML data generation from EJBs[ Go to top ] Even i am facing the same kind of problem.....One possible solution is to return data in the form of ResultSet object....but i came across Marshalling Exception and NotSerializable Exception.Could anyone give a better solution please....? - Posted by: zebah singh alfred - Posted on: June 07 2001 05:57 EDT - in response to Girish Bhatia XML data generation from EJBs[ Go to top ] hi, - Posted by: suresh babu - Posted on: August 01 2000 07:16 EDT - in response to Anil Lobo I am another guy here looking out for some code fragments for XML data generation from EJBs. This is the core part of my module for which my hunt has already started any help in this regard would be thanked a lot. Please do respond. My mail id is : satya_m_09@yahoo.com XML data generation from EJBs[ Go to top ] u stupied u don't no how to create xml file - Posted by: phani kumar - Posted on: September 27 2000 03:51 EDT - in response to suresh babu but u want us placement. bye XML data generation from EJBs[ Go to top ] Hi anil, - Posted by: pankaj grover - Posted on: August 01 2000 13:35 EDT - in response to Anil Lobo I had just one question . how is it better than passing serialized objects. As a java client can access an EJB which generates XML. So the presentation can be independent of the data (Model -view) in both cases i.e in case data is passed as XML or serialized java Objects. Also If you could pls send some snippets of code which create XML and also which parse XML . I can be reached at pankajgrover at yahoo dot com Thanks Pankaj XML data generation from EJBs[ Go to top ] I had come across systems in which the data is already in XML format. So to integrate other applications with these XML systems, it would be easier if the EJBs gave out their data in the form of XML. Also, in some cases one half of the systems had say some reports generated in XML and other reports coming in some form out of a database. So to merge these 2 it would be better if all were in XML. Hence I thought about this pattern. - Posted by: Anil Lobo - Posted on: August 02 2000 02:34 EDT - in response to pankaj grover As for storing XML as serialised objects (CLOBs)in the DB, 1: Your beans would be BMP since weblogic does not support CMP for CLOBs. 2: Your data since it is stored as a serialized string now would have no relation to any other table. I mean that your table relationships are lost. Here in this pattern, the data gets stored back into the fields it belongs to. Your table data is totally independent of the XML document. 3: but yes, if you are doing some processing on the XML data and you want the preocessed results to be stored, especially if the processing is resource intensive, then you might as well store the result as a serialized string. The case I had mentioned has nothing to do with storing XML data as a serialized strings (although that could be done). I extract data from the DB using normal EJBs i.e the data is stored as normal SQL datatypes like varchar or number. These EJBs then convert the data to an XML format and passes it to a servlet or some other program for further processing. This helps to get multiple data from various sources and merge them into a single XML document. The EJbs effectively act as a XML to Database bridge. The EJBs can also parse the XML document and break it up into java primitive types and store the data back in the required tables. The SQL schema for these tables correspond to the XML Schema for these documents (like a one to one mapping betweem the table columns and the XML tags). This thing would work for simple XML docs but i thnk it can be made to work for complex XML docs, since the work for getting data and parsing is handled by session beans with some parsing logic. Admitted, it would be easier to store the XML data as a CLOB in the DB, but then the relational aspect is lost. In my case, the data is stored as normal data types. The Entity beans map the tables. The session beans manipulate the data to XML form and back from XML form to normal data. I will write some sample code and put it here in the next few days, cheers, Anil XML data generation from EJBs[ Go to top ] I think I have been misunderstood . what I was referring to was pros and cons of passing XML between ejb's and java clients like servlets with passing serialised objects from the ejb to the servlets like java beans which could be acessed by JSP's as well with relative ease. - Posted by: pankaj grover - Posted on: August 02 2000 16:07 EDT - in response to Anil Lobo I ma interested in knowing what relative benefits does the XML provide in passing the data to the client layer. I can understand if it is going to de different clients like a servlet and a MFC GUI. If it has to be only a java client, I fail to understand any relative merits of this approach. Thanks Pankaj XML data generation from EJBs[ Go to top ] This pattern was meant as a means to give out and put in XML data via EJBs into a database. This decouples the EJBs from the presentation layer totally. - Posted by: Anil Lobo - Posted on: August 03 2000 00:26 EDT - in response to pankaj grover 1: You could have a servlet which would take this XML data and via XSL convert it to HTML or WML maybe. 2:Or you could even write a servlet which consolidates all the XML from various EJBs and merges them into a single document. (one of such applications being reporting tools). 3: Or you could write a servlet which takes this XML data from the EJBs, and formats back a SOAP response and sends it back to a SOAP client. The point being that since your EJBs give out XML, you can do whatever you want with thier output, whether to do more processing or just display. You can always create JavaBeans from these XML documents and use them if you want to. It is a design issue which you will have to decide. XML data generation from EJBs[ Go to top ] dear friend, - Posted by: kiran kumar - Posted on: August 04 2000 17:51 EDT - in response to Anil Lobo i have a very basic question. i want to know where exactly XML comes to picture in a real world web based project. like 1. client side or server side 2. like if in client side can we design UI forms with all the elements like list boxes, tables as we do in html. if we can do that can we completely eliminate HTML in our applications please reply soon. my contact kirankandagiri at yahoo dot com have a nice time kiran XML data generation from EJBs[ Go to top ] Hi Kiran, - Posted by: Varadarajanarayanan Srinivasan - Posted on: August 30 2000 03:47 EDT - in response to kiran kumar The XML part comes both in the server side as well as in the server side. Client Side: When you are using the XML in Client Side you can get the input and process in XML format itself using tools like XSQL Servlet which you can get from ORACLE site(). Server side: You can query a database get the contents in XML form and process the same thru a the same XSQLSERVLET or ordinary SERVLET or JSP and you can make your screen to view in XML form itself.As you have mentioned in your message in this way we can eliminate the usage of HTML effectively. If you do the process like this then you can see the time taken for processing the data is considerably reduced. Regds, S.Varadarajanarayanan Developer, SIP Technologies & Exports Ltd, G4,Elnet Software City, Taramani, CHENNAI. (narayanan at siptech dot co dot in) XML data generation from EJBs - jeyabalan[ Go to top ] Hi, - Posted by: jeyabalan P - Posted on: June 22 2003 05:55 EDT - in response to Varadarajanarayanan Srinivasan Could you tell me, how does XSQL tool reduces the performance in this issue. Regards, X-employee of SIP XML data generation from EJBs[ Go to top ] I think that the real benefit of using xml with EJBs is on the process side, particulary in the way session EJBs exchange data and informations. - Posted by: nabil bousaada - Posted on: August 05 2000 01:45 EDT - in response to Anil Lobo Exchanging XML documents is more "abstractive" than exchanging serialized Objects or calling each others public remote methods. Actually the only problem with XML is the lack of a good and simple querry language, it is possible to map an xml document against a DB table and then use SQL but it's not very realistic because the XML shema can be complex and can evolve frequentely. XML data generation from EJBs[ Go to top ] Hi Anil Lobo ! - Posted by: Jeyaraman Raju - Posted on: September 27 2000 12:10 EDT - in response to Anil Lobo U talked about mapping entity beans to represent the database and having session beans to communicate with the entity beans. In my view to think about the architecture it is a clear one.But if we consider about performance I don't think it'll give a fast response system when we imagine a big system take an example financial systems.There we've to map hundreds of tables with entity beans and if we talk with them using session beans see the roundtrips and load on the server.It'll affect the performance. What I think would be the best is we can cut entity from the architecture and we can use XML methods to parse data directly from the database. Feel free to share your experience with the design architecture u proposed with a huge system if u felt it enhanced the performance. My mail Id is : rajujeya at usa dot net XML data generation from EJBs[ Go to top ] I dont want this to sound like an advertisement, but my company uses cerebellum software [], which is used to create data access components that can be used in a variety of methods. Heterogeneous queries can be graphically created, and included inside entity beans that can in turn be used in jsp pages. it makes this whole process a LOT easier. then again its not free... It seriously cuts down development time though. - Posted by: Shawn Wall - Posted on: August 02 2000 18:18 EDT - in response to Anil Lobo XML data generation from EJBs[ Go to top ] I'm glad this topic was brought up, as I use it in two of the projects I'm working on. We use XML as a serialization mechanism between the client (an applet) and the server, with a servlet being the router, or controller. Why, as Pankaj asked? Well, for one, we could only use HTTPS, not IIOP, RMI, etc. and we spent a lot of time investigating the use of just 'plain' serialization, but found this to be somewhat problematic in that it is very rigid. What if the server through an exception, and you are expecting your object graph to come back? In our case we have no way of catching it, because of HTTP. So, we are using XML as an RPC mechanism as well, serializing both the message (method calls) and the data back and forth. The actual GUI doesn't know about XML as it is deserialized back into objects for it's use, as in the Details Object pattern. - Posted by: Robert McIntosh - Posted on: August 08 2000 10:24 EDT - in response to Anil Lobo Also, as mentioned before, you could apply XSL for HTML clients using something like Apache's Cocoon, use it as an app-to-app communication (B2B), etc. At the moment it has also served us well as a temp storage medium until we finalize the DB schema. Our first major question that came up was that of performance, which we expected to take a big hit on. Suprisingly, it was really no slower than standard serialization on a large object graph; maybe a few milliseconds at most. On peristence, I probably wouldn't store XML directly in the db, but mapping to it won't be a major chore either. I'm not a big fan of CMP anyway... -Robert XML data generation from EJBs - why use EntityBeans[ Go to top ] If you are planning to provide ReadOnly access to the data stored in you DB and to present information as XML, what is the reason for Entity bean usage? - Posted by: Stanislav Markin - Posted on: August 09 2000 07:00 EDT - in response to Anil Lobo Why don't you use only Session bean? There are some tools(libs) for DB-XML mapping that could be used directly from Session bean. Maybe it's better to use them. Consider the situation with the price-list items. When you generate XML for the first 1000 items you will use the code like this: Collection items = itemHome.findFirst1000(); //for each item in items collection for(...){ // add new <item> to resulting XML price = item.getPrice(); //add price to resulting XML // and so on } For every item there'll be the instance of Entity bean in memory, this could be a great overhead (especially when there are a lot of users asking for different parts of price-list). Think that the pattern is useful in situation when you already have coarse-grained Entity beans and plan to add XML support. Passing XML data[ Go to top ] Just thought I'd add my 2 cents as passing data as XML seems to be a trendy choice. There are actually 4 proven methods for passing data from the EJB business tier back to the servlet Presentation layer for processing that I'm aware of. These are: - Posted by: Alex Burdenko - Posted on: August 11 2000 22:02 EDT - in response to Stanislav Markin 1) Use an array of strings 2) Use an array of structs ( Java classes with public fields - standard C technique ) 3) Use a Java bean 4) Use XML I think the pattern that started this discussion is good but it's not complete. IMHO, the final step, after the data is passed from Entity EJB to the Stateless Session EJB, is to pass the data back to the servlet for display. The Servlet acts as the display controller in the classic MVC pattern. Now, does it really make sense to serialize the data coming back from the EJB tier as an XML string when it's always passsed to the servlet for rendering anyway? What I'm getting at is that passing a bean over RMI for Java EJB to Java servlet communication within a firewall makes a lot more sense to me in terms of performance. When the bean gets to the servlet, the servlet can then decide to transform it into XML, WML, HTML or anything else. An interesting notion is to use sun's new WebRowSet for just this purpose. WebRowSet is a beanified jdbc resultset that was created to pass data from an EJB to a servlet. This is not an original Sun idea. It's a pretty good copy of the Microsoft RecordSet COM object. Anyway, the servlet can then choose to call toXML() on this bean and the data will be converted automatically to XML. Presto, you don't get the performance hit of converting to XML and back unless you need to send data thru a firewall across the Internet via HTTP. Passing XML data[ Go to top ] I apologize for reading the above pattern too fast. It does indeed include using a servlet to control the display. - Posted by: Alex Burdenko - Posted on: August 11 2000 22:06 EDT - in response to Alex Burdenko Passing XML data[ Go to top ] Your perfectly right, but here are some Applications for this patterns (haven't checked this ones for performance or stability, just for ease of use: <br> - Posted by: Stefan Frank - Posted on: September 25 2000 10:30 EDT - in response to Alex Burdenko - EntityBeans always have more than one view: Most prominent example is a view inside a web application and the corresponding administration client: Having an XML-Representation of an EntityBean will serve as a good Starting-Point for Generating for example a Swing GUI to administrate the Bean. (Is this compatible with the Pattern?! Even a Swing-GUI always interacts with a Session Bean wich extracts the XML from the EntityBean or puts it back.)<br> - this is essentially just another way of marshalling/unmarshalling an EntityBean, and this can be done automatically (e.g. castor.exolab.org) which makes the Pattern even more useful.<br> - Essentially this is just a rephrasing of the well-known Transport-Object, or am I wrong? XML data generation from EJBs[ Go to top ] Hi, - Posted by: Channing Walton - Posted on: August 12 2000 14:03 EDT - in response to Anil Lobo I am very glad this pattern is being discussed as it is relevant to something I am working on. In particular, I am trying to convince people around me that writing a 'toXML' method on an Entity bean is a bad idea. I was too surprised when the idea was presented to give a coherent argument. I spoke of MVC and the like but it seemed not to be understood. Any thoughts would be much appreciated ? Channing XML data generation from EJBs[ Go to top ] The only time I probably would NOT use any kind of to/fromXML is if you know that you: - Posted by: Robert McIntosh - Posted on: August 16 2000 10:49 EDT - in response to Channing Walton - are never going to communicate app to app or B2B - never need to communicate over HTTP (such as in an applet or WML) - are never going to use XSL vs. JSP for presentation (which has a strong following) It doesn't always make sense to go from EJB to XML to HTML (via JSP), when you can go from EJB to JSP, but then again sometimes it does. It really depends on the end use of the application and it's growth potential. Robert XML data generation from EJBs[ Go to top ] My problem with toXML in Entity Beans is that: - Posted by: Channing Walton - Posted on: August 19 2000 07:15 EDT - in response to Robert McIntosh - XML is a kind of view of the model and the model shouldn't be responsible for generating views - The Entity Bean will have to be changed everytime the DTD is amended - The Entity will have to not only produce a valid XML document but also XML fragments as one might want to build an XML view from several Entities. This means that the Entity must know about all the different DTD's it might form a fragment of. My feeling that the proper place for generation of XML from Entity beans is in stateless session beans whose sole function is to build XML views of the underlying data in Entity beans. This allows the greatest flexibility in putting different XML documents with different DTDs/Schemas together of the underlting model without cluttering the model. I agree entirely with your assertion that it doesn't always make sense to go from beans - xml - xml+xsl = xhtml, xhtml + css + jsp. Much better to go directly from bean to presentation when thats all the app does (no B2B for instance). Channing XML data generation from EJBs[ Go to top ] I should add that the session beans responsible for building XML documents could of courese build those documents from entity beans AND other session beans that produce appropriate data. - Posted by: Channing Walton - Posted on: August 19 2000 07:17 EDT - in response to Channing Walton Channing XML data generation from EJBs[ Go to top ] I like the idea of a stateless session bean doing the generation of XML as opposed to the Entity bean itself. In my own framework I do something similiar; I have a utility class that generates the XML for our business objects, and reinstantiates objects from XML as well (we are using XML for RPC/marshalling over HTTPS). - Posted by: Robert McIntosh - Posted on: August 22 2000 01:16 EDT - in response to Channing Walton Robert XML data generation from EJBs[ Go to top ] The point i would like to make is that not to look at XML as view specific as was pointed out in this discussion. The view is controlled by a servlet and XSL. XML in this pattern is only data. - Posted by: Anil Lobo - Posted on: August 23 2000 16:28 EDT - in response to Robert McIntosh XML data generation from EJBs[ Go to top ] I used this pattern in my previous project. it worked nicely. I consider XML is the objects property like draw() method of shapes. When control asks the entities to draw each entity like line and circle draws itself. - Posted by: Ravi Reddy - Posted on: September 29 2000 16:03 EDT - in response to Channing Walton This is how I used this pattern before in a content based email system - I have entity beans for Channel, content and product. Channel is entertainers - Title, author etc. Content is about Tom Hanks and products are Apollo 13, xxx and yyy - When I need to display only product session bean x calls product entity bean and toXML() and hands of this XML to XSL - When I was building full email, my yy session bean calls channel bean, content bean and all the realted products beans to get individual XML and builds the total XML for the email - I use same entity beans to producr preview screens for content generation people Hope this makes some sense Ravi XML data generation from EJBs[ Go to top ] Hi, - Posted by: Kashmiri Kaser - Posted on: February 06 2001 13:04 EST - in response to Channing Walton I have one argument against your belief. You said "XML is a kind of View", but I say "XML is a kind model, XSL is the kind of view". The controller (a stateless session bean) has a responsibility to build the XSL (ie, the controller class has a immplemented method getXSL) and this method collects the XML (sole data) from the entity bean and applies the proper XSL (according to viewing needs - admin view, compact view, detailed view, edit view etc) to the XML. I think, XML must me considered as a more meaningful representation of the data inside the entity bean. Hence, it should be entity bean's responsibility to generate XML and give it (stream or file or some other representation) to the controller class when requested. -- Kartik XML data generation from EJBs[ Go to top ] We are using a form of this pattern in a production application (3000 users). Our beans are really pretty dumb--stateful session beans that are really a poor man's version of entity beans wrapping concepts resident in legacy systems. Communication to and from legacy systems is in XML form. - Posted by: Jeff Mackay - Posted on: March 09 2001 11:37 EST - in response to Kashmiri Kaser A request dispatcher servlet receives requests, request handlers orchestrate multiple beans. Each bean includes methods that return data in XML form, using a financial services industry standard schema. A simple transformation request handler transforms the XML assembled by application specific handlers into HTML. Works great--we're now updating the application to implement an entirely different interface by replacing the xsl stylesheets. Updates, which can get pretty complex, will be handled by an XML-savvy business rule engine. toXml() is a good idea, but a bad method[ Go to top ] Being able to convert an object to and from XML is a great idea. For an example, see my BeanMapper at, or any of the countless other Bean<->XML serializers. - Posted by: Alex Chaffee - Posted on: October 06 2000 13:24 EDT - in response to Channing Walton <p> However, you should not allow an object to serialize itself with a toXml() method (or fromXml()). This limits the object to having one and only one possible XML representation, when as we all know, there are an infinite number of mappings to choose from. <p> Instead, use a separate serializer object (like BeanMapper). That maintains object separation (often mistakenly called MVC). <p> Cheers -<br> - Alex toXml() is a good idea, but a bad method[ Go to top ] I agree with Alex, - Posted by: Georgi Kostadinov - Posted on: October 24 2000 12:49 EDT - in response to Alex Chaffee > ...Instead, use a separate serializer object > (like BeanMapper). That maintains object separation... I just want to add that one can use the Adapter pattern to do this. For example have a XmlCarAdpater wich takes a Car object in it's constructor and have a method toXML() to get the XML string presentation of the Car object. Note: In one of the projects I am working on, I use composite objects, like CarPark containg a list of cars, etc This lends itself to using the Composite pattern in which you specify composite objects as branches having one or more leaves. Each such object then, wrapped in an adapter would know how to represent itself (acording to the adpater rule). Thus, the whole tree (or composite component) will know how to represent itself when wrapped in an adapter. This leads to a solution where your composite object doesn't know anything about how to represent itself, rather the Adapater defines rules of that. Also adpater uses the Composite pattern to allow for complex, composite objects to be represented. Cheers! Georgi toXml() is a good idea, but a bad method[ Go to top ] I also agree with Alex. An entity may have several XML representation. - Posted by: Idan Efroni - Posted on: December 06 2000 11:43 EST - in response to Georgi Kostadinov In our project, for example, we have to represent Entities which have aggregated entities in them. Whether the client has to receive the aggregated entities along with the parent depends on the exact use case. As for the adapter pattern, how would that be better than a Translator class?, e.g. public class CarXmlTranslator { public static String toXML1(CarBusinessInterface); public static String toXML2(CarBusinessInterface); public static CarBusinessInterface fromXML(String); } It looks to me that that would achieve the same results and will not require creation of a whole tree of adaptors. Am I wrong here? toXml() is a good idea, but a bad method[ Go to top ] Ofcourse I'm wrong. Ignore that. - Posted by: Idan Efroni - Posted on: December 06 2000 11:53 EST - in response to Idan Efroni XML data generation from EJBs[ Go to top ] Great topic!! Here are some performance and maintenance considerations for large applications. Our project, a large eCommerce portal, has ~100 entity beans and just as many session beans. - Posted by: Rob Murtha - Posted on: August 18 2000 02:02 EDT - in response to Anil Lobo I have seen finders and iteraters become too slow for creating large numbers of XML messages. We also have to deal with dereferencing OIDs and looking up reference codes on large data sets. Our data is maintained by session and entity EJBs ( using Lazy References and DataBeans as we call them ) and supports inbound and outbound XML. We took a different Java approach for outbound XML since large numbers of XML messages can be requested. Our approach includes JDBC, Oracle views, HashMaps, a text Formatting class, and external element tag files with matching java classes. We perform queries against the views which perform complete translation of all reference codes and conversion to element column names. The HashMaps are produced from JDBC result sets and store references to data by element name. The tag files and Formatters are referenced by reflection and loaded on demand. This is quite fast against large result sets and is also easy to test. Our next goal is to move this into Oracle 8i for even more speed. On the maintenance side it is much faster to engineer, test, and roundtrip debug given the large number of beans that we are already supporting. Rob Murtha robmurtha at yahoo dot com XML data generation from EJBs[ Go to top ] Where can I find a good XML parser that I can use with EJB? How about something for XSL on the server side? - Posted by: Justin Echternach - Posted on: August 31 2000 09:51 EDT - in response to Anil Lobo Thanks. Justin XML data generation from EJBs[ Go to top ] you can find, a SAX or DOM parser on - Posted by: olivier delbos - Posted on: October 25 2000 08:33 EDT - in response to Justin Echternach also you have JDOM XML data generation from EJBs[ Go to top ] Plz elaborate this scheme little in more detail to extract data in xml from ejb. example could be report generation for vendor in B2B kind of application. - Posted by: aa aa - Posted on: August 31 2000 12:02 EDT - in response to Anil Lobo Bye, Ajit wadekar. XML data generation from EJBs[ Go to top ] Why not add toXML/fromXML methods to the Value object (pass-by-value pattern) which represents the data in your entity bean? - Posted by: Josh Price - Posted on: September 07 2000 12:07 EDT - in response to Anil Lobo This way you can use XSL to display results or manipulate/aggregate several value objects together in your Session beans. XML data generation from EJBs[ Go to top ] I've been looking at this kind of mechanism for a current project I'm running for a 30-person class at a major financial institution to do fixed income holdings... - Posted by: Stu Charlton - Posted on: September 13 2000 23:42 EDT - in response to Anil Lobo The tradeoffs I've come up with is pretty similar to the ones I've seen stated here: do you explicitly generate the XML inside the entity bean with a toXML() method? Or do you write a visitor of some sort to allow the "XML Hub/Broker", so to speak, to traverse the beans' get/set methods to get the data and turn it into XML. By and large my major concern is performance with the visitor approach. It's obviously cleaner from the beans' perspective, because then they really don't have any XML knowledge, but if a business entity has hundreds of fields (not uncommon with securities that have hundreds of derived economic indicators), this becomes a bottleneck with RMI/IIOP, even over the local loopback. If the servlet engine (which runs the XML hub) is on the same server as the EJB's, and you have short-circuted RMI stubs that perform in-process call routing, then I suppose you lose that network trip overhead. I believe BEA Weblogic does this sort of short-circuiting, but I need to confirm... My other concerns are how we can format the DTD. I'm thinking we can use or possibly mildly extend an existing DTD for hierachial data, such as XML-DATA from Microsoft.. this allows for a pretty generic Object oriented data representation, but it doesn't really provide me any way to map "process", or "actions" in my XML. What I want to be able to do is to map queries and result collections, but also to map business transactions in my XML. Right now I think the best way to accomplish this would be to provide an ID for the bean (session typically) that has the business transaction on it, and the transaction name, and just to use Java reflection, i.e.: <TRANSACTION ON="FundingProcess" NAME="performDataValidation"> <PARAM>foo</PARAM> <PARAM>bar</PARAM> </TRANSACTION> and to map this to a reflected Java method call. Another concern I have is that I'm not sure I want to have the complexity of scanning my beans for fields through get/set methods. I had to do this once for a business object framework that allowed me to arbitrarily update methods based on key/value spec in HTML, and it was somewhat complex (ask Floyd, he knows... :) Anyway, what I'm thinking is that perhaps I should have an XML file that acts as a "data dictionary", or sort of an app-specific deployment descriptor, that lists the fields of my entity beans. My XML hub then, completely un-knowing about any hard-coded bean names or method calls, would just map the XML messages to the info in the data dictionary, and call the appropriate methods. This could also lead a wilder implication in that I could roll my own object/relational mapper to do schema changes to my BMP entity beans fairly simply by just adding a field+getters+setters to the bean and updating the stored procs for my ejbCreate/Remove/Store/Load/Finders... (yes I know I should probably PURCHASE an OR mapping tool, but if I can teach one team of students how to build a scaled-down, simplified OR mapper, they'd get a world of experience..) anyway, just my ramblings XML data generation from EJBs[ Go to top ] My take on this discussion. - Posted by: Dino Chiesa - Posted on: September 20 2000 12:46 EDT - in response to Stu Charlton 1. Talking about how to generate XML from EJB gets complicated quickly, not least because these two approaches overlap at the model layer. Why not simply ask the database to generate the XML directly (see comments by S.Varadarajanarayanan)? Most databases are supporting this anyway. What value does the entity bean offer if it simply gets in the way of efficient processing (see Rob Murtha's comments re: iterators)? Also, when using the db to generate the XML directly, the data is stored as the DB likes it (not as a CLOB), preserving the relations. This avoids the problem Channing Walton mentioned: the entity bean must change each time the DTD is amended. If there is no entity bean, but only DTD and XML, then obviously this goes away. This is an example of "Adding Lightness" to the design, making it simpler, by removing the EJB Entity. 2. re: Why generate XML? - with all the hype surrounding XML, perhaps we sometimes forget to answer this question. To me, it's quite clear that for interop (either via JMS, or some other external connector) XML will be quite important in server-side java systems. 2. Sun's WebRowSets - this is an interesting idea, but when applied with EJB entity beans, really it is a patch, a band-aid approach to delivering sets of data from entity beans. [see Stu Charlton's comments re: short-circuiting RMI]. Much more preferable will be JDO (still in JSR) or perhaps WebRowSets with JDBC directly against the db (again, avoiding the entity bean completely). 3. Some of us perhaps are thinking XML is useful only in the View of MVC, hence the questions "why generate XML in the EJB?" But XML holds value in integrated distributed systems primarily in representing the Model (see S.Varadarajanarayanan). Which is why it makes sense to generate it in a layer as close to the storage as possible. XML can also be useful at the view layer, but that is not the point here. ---- re: xml in java, use xerces, which is available at xml.apache.org. This was previously IBM's xml4j, but is now open-source. an update..[ Go to top ] We went ahead with the visitor approach to XML generation... here's our results (our first iteration is completed and demoed on October 6th): - Posted by: Stu Charlton - Posted on: September 28 2000 14:32 EDT - in response to Anil Lobo A servlet is tightly coupled to a session bean "XML Hub". This enables each XML request to contain N number of method calls that are brought in as one transaction through the parseXML(String s) method on this session bean. We use a 500 kilobyte StringBuffer in this bean that represents the cache for the generated XML. This object is nullified on ejbPassivate and re-created on ejbActivate. This allows for fast XML generation from the resultsets, with few redundant String creatiosn. Row-level data reads & updates occur through a coarse-accessor method on a fine-grained generic entity bean, driven by our own schema-management data dictionary. The combination of XML and a dictionary-driven bean allow for near-transparent field-lengthening and field additions. Set based data reads and updates occur through stored procs that are encapsulated in session beans. Performance is promising, though we have not come up with hard numbers yet. Relatively little CPU overhead is apparent in using XML (we're using SAX). Network overhead is obviously going to be higher than raw rowsets, but it has not impacted us yet. We are using a data-windowing strategy to limit the maximum amount of data sent for a details-query and will optimize this further by "window shading" various groups of columns. So far, I'm fairly pleased. In one iteration, we'll have developed a basic inventory system with ad hoc querying, easy schema chagnes, fixed-file format import, and scalability/fail-over support in 3 1/2 weeks... all with junior developers, some of whom learned Java only 2 months ago. Obviously, it's not perfect, nor is it a full product, but it shows that even though the J2EE is complex, it provides a lot of time-to-market value. legacy integration[ Go to top ] We're using a variation on this theme for putting a web front end on multiple legacy systems. The theory is that we're not creating yet another <xyz> (insert your own domain) information system. We're creating a web front end. So why build entity beans that have to be modified whenever business rules change? - Posted by: Jeff Mackay - Posted on: September 29 2000 01:23 EDT - in response to Stu Charlton The presentation layer consists of a servlet that uses session beans to implement a "request handler" architecture. Request handlers in turn communicate with entity beans that exist mainly for caching purposes. The entity beans communicate with an integration layer that manages communication with legacy systems (mainframe, COBOL, etc.) through message queueing over some relatively slow links. Responses from the integration layer all the way back to the presentation layer are in XML. The entity beans have no real knowledge of the entities they represent. They just know primary keys, sort keys, etc. Everything else is maintained by the beans in XML format, and isn't really accessed by anything but the XSLT stylesheets that format the XML into HTML. This allows us to isolate changes to a great degree. Presentation of information is handled entirely by XSLT. We'll be implementing a business rule engine to manage validation for updates. So changes to front-end logic are managed without having to modify any code... It's still early in the project, and we had some initial problems with the complexity of XSLT, but our initial prototypes look very promising. XML data generation from EJBs[ Go to top ] Anil? Code? - Posted by: Chad Brockman - Posted on: October 24 2000 12:46 EDT - in response to Anil Lobo Please :) XML data generation from EJBs[ Go to top ] The code for this pattern is very easy to write yourself and I feel that you should. I wrote the stuff with sample code from the weblogic examples plus some stuff from the xerces examples. The more complex part of generating a report from the database tables is part of a product and I would be violating copyrights if I made it open. - Posted by: Anil Lobo - Posted on: October 25 2000 18:35 EDT - in response to Chad Brockman XML data generation from EJBs[ Go to top ] After a long time I had a chance to read all the comments/ideas posted on this site. I have had a few more experiences to add since the day I posted the pattern. Most of you will know them, but anyway here goes: - Posted by: Anil Lobo - Posted on: October 25 2000 19:20 EDT - in response to Anil Lobo 1: In any project, get the data model perfectly. 2: Decide on the queries you are going to perform. How many queries/how many updates/how many concurrent users? 3: Decide to go either the EJB way or the direct Servlet JDBC way depending on the complexity and marketing strategy of the product. I have seen products do EJB and XML jsut because they could be marketed as cutting-edge, not for any performance or other real world issues! 4: Finally how will data be passed in the system - as XML or as serialised objects? This depends on your project. If it is a reporting system, it would be easier in XML. If it is a system to just lookup data and pass it to JSPs for a view you would be better off with Javabeans. Coming to the pattern: A lot of good experiences with this pattern have been posted here. The visitor approach by Stu Charlton looks good. The other appliction of this pattern which I found interesting was by Stefan Frank (XML representation of an EntityBean will serve as a good Starting-Point for generating for example a Swing GUI to administrate the Bean.) (How come I never thought of that!) I had come across this pattern when my team was grappling with the problem of making user customisable reports from a system which already had EJBs. For creating reports XML/XSL is the easiest way to go. The data was anyway present as EJBs and also we could integrate our system with other providers of XML data to generate unified reports. Finally some clarifications: I had initially stated that we could map each table with an XMLSchema which in hindsight should have been that XMLSchema is used to map the resultant data which is generated by the session EJBean. XML data generation from EJBs[ Go to top ] I’m not sure where this idea originally came from but I’d like to throw it out here and see what you think. - Posted by: Chris Sellers - Posted on: October 27 2000 10:26 EDT - in response to Anil Lobo A servlet accepts an XML description of a session bean from the client. The servlet parses the XML description and uses reflection to call the corresponding EJB. The method called must accept and return a XML Document object. The servlet then outputs the returned Document object to the client where it is combined with XSL for presentation. Here’s an example of what the session bean description could look like: <?xml version="1.0"?> <businessRequest> <method> <server></server> <ejbPath>com.companyid.components.helloworld.business.HelloWorld</ejbPath> <methodName>someMethod</methodName> <data> XML Data intended for the session bean... </data> </method> </businessRequest> I know this won’t display perfectly so I hope you get the idea. XML data generation from EJBs[ Go to top ] What you are doing looks pretty cool and interesting. But isn't what you are doing similar to SOAP (or XML-RPC)? What is the business problem you are trying to solve? - Posted by: Anil Lobo - Posted on: October 31 2000 18:00 EST - in response to Chris Sellers XML data generation from EJBs[ Go to top ] Doesn't representing elements of the model in XML make it harder to manipulate? This may be alright if the data is read-only, except that it still doesn't provide as many options for scaling up the servers as when the XML representation is deferred to a View. I will try to illustrate... - Posted by: Justin Hartley - Posted on: January 17 2001 20:27 EST - in response to Anil Lobo Consider a system with the following characteristics: 1. Business logic is implemented in an object Model that uses entity and session EJBs. 2. Entity beans deal only in Java data types. They may persist directly to a RDB (SQL data types) or talk to some other legacy system. 3. Controller is a servlet. Requests may come in XML format (SOAP?); they are parsed and the requested service is invoked. 4. Services are also servlets. They make calls to the session beans (and possibly entity beans) and make the results available to the View through data beans. 5. The View consists of JSP documents that are XML with custom JSP tags. Note that if the DTD or schema changes, no programming changes are required; just get someone who knows XML to modify the View documents. 6. Possibly wrap the service servlet and the XML/JSP in a filter that then applies XSLT, resulting in a transformed XML (or HTML) document. This approach allows great flexibility in specific XML formats, back-end implementation (eg. swap out EJBs, swap in JDO), scalability options (add extra servlet engines). Note that it is not necessarily a web-based system. The source of the requests and responses (both XML) could be a message queue, talking to some other business. XML data generation from EJBs[ Go to top ] Hey! can u send the source code. - Posted by: sridhar sirigiri - Posted on: December 13 2000 13:18 EST - in response to Anil Lobo sirigiri XML data generation from EJBs[ Go to top ] Hi ANil, - Posted by: Swami Iyer - Posted on: December 19 2000 14:38 EST - in response to Anil Lobo Can you send me the source code for this pattern. Also I am looking for some good comparison or advantages of session beans over servlets where in this system the persistence is not handled by the session beans or entity beans (entity beans are not going to be used) and it is handled by a bunch of networking services which uses JDBC. If you happen to come across any such document can you point me out to that. Thanks a lot. Swami XML data generation from EJBs[ Go to top ] If possible, I would also like to receive a copy of the source code. - Posted by: steve selak - Posted on: January 11 2001 09:40 EST - in response to Anil Lobo Steve dot Selak at eds dot com Thanks, Steve XML data generation from EJBs[ Go to top ] hi Anil, - Posted by: Rahul Murudkar - Posted on: February 06 2001 03:03 EST - in response to Anil Lobo i am looking for the source code where ejb sent back xml data to client( servlets etc). will you plsease kindly sent me the code. bye thanxs Rahul XML data generation from EJBs[ Go to top ] Another aproach would be to use a helper class (instantiate by the Entity EJB) to convert the EJB Data into XML and XML into DATA. - Posted by: Rodolfo Rothganger - Posted on: March 26 2001 14:47 EST - in response to Anil Lobo On the client side, like so many pointed out, instead of a servelet or a XSL translator, one could use a pesistent adapter class (coupled to the Bean), to convert the XML received form the Entity EJB (using the helper class) into inside data, which can be accessed by the cliente (by getValueA, getValueB, etc) . (the client do not call or refere to the EJB itself, the adapter is the one who does). The client could use the adapter to update the bean as well. Just calling a adapter method that update its inside data, send this data as XML to the Entity EJB. The entity bean, using the helper class already instantiated, convert the XML into DATA and stores it. Note: you cold change the that inside the adapter and do not update the bean by creating to diferent methods: one to change and one to update. XML data generation from EJBs[ Go to top ] I think that having a toXML method is nice because you can present a OO interface to the Entity Bean. Locking the EB to a specific DTD of course is a Bad Thing. The visitor pattern over RMI would also be slower, so couldn't all of the above be solve thusly: - Posted by: Stacy Curl - Posted on: April 09 2001 15:02 EDT - in response to Rodolfo Rothganger public class XMLGenerator implements Serializable { public XMLGenerator(DTD dtd) {} public String getXML(Object thang) { // use reflection on 'thang' to generate XML, using // previously set DTD. } } public class EntityBean // ??? { public String toXML(XMLGenerator xg) { // might cache xg return xg.getXML(this); } } XMLGenerator is Serializable so when it's passed to the Entity Bean the entity bean will have a local copy of it, so conversly when the entity bean passes itself to the XMLGenerator the XMLGenerator will have a local reference of the Entity Bean, therefore method calls will be a fast as you can get. The XMLGenerator could use Reflection to determine the EB's getters or a specific XMLGenerator for an EB could make direct calls. I'm not a EJB guru, nor even a neophyte, but I'm assuming that you can still use inheritance in the implementation of an EJB, so all this code can be placed into a base, including code for caching of XMLGenerators.
http://www.theserverside.com/discussions/thread/343.html
CC-MAIN-2017-26
refinedweb
9,838
64.34
Exploring the code of java.util.LinkedList as it is in OpenJDK 8, I found the following code. The code is straightforward, but I'm confused about saving reference to the first node to a constant in the second line of code. As far as I understand, this code will be inlined to one-liner without reference copying. Am I right? If so, why does one need to copy reference in this and similar situations (such idiom may be found in a half of methods in java.util.LinkedList)? public E peek() { final Node<E> f = first; return (f == null) ? null : f.item; } My first thought was that it helps concurrency in some way... ...so I guess it is some hint for optimizer... Both. :-) The fact that LinkedList doesn't support concurrency doesn't mean that the authors aren't going to follow good practices anyway, and it tells the compiler and the JIT that they should only look up first once. Without the f local variable, we'd have: public E peek() { return (this.first == null) ? null : this.first.item; } I've added the implied this. to emphasize that first is an instance field. So if the this.first == null part is evaluated on Thread A, then this.first is changed on Thread B, when this.first.item is evaluated on Thread A, it may throw because this.first has become null in the meantime. That's impossible with f, because f is local; only the thread running the peek call will see it. The final part is both good in-code documentation (as the author never intends to change the value of f) and a hint to the optimizer that we're never going to change f, which means that when it comes time to optimize, it can optimize it to within an inch of its life, knowing that it only ever has to read this.first once and can then use a register or stack value for both the null check and the return.
https://codedump.io/share/OzaqTTQww78b/1/is-it-important-to-copy-reference-before-using-in-java
CC-MAIN-2017-34
refinedweb
337
73.27
Easy build API using Laravel and GraphQL (Mutation) part 2 Mutation GraphQL Previous article we learn Building API using Laravel And GraphQL for Product List and User List, if you read previous article , i suggest you read it first. Now we will learn about Mutation and Authentication API with GraphQL GraphQL is awesome technology for making simple and dynamic API, it is powerful for client app which develop using React Native / ReactJs. there are many library for support GraphQL documented in below 1. Create Mutation Class Mutation is type for inserting data into a database or altering data already in a database more detail here, in previous article we already have User Model, this sample we will add new user with profile and update user information using mutation query. First we must add new class for new user and update user in NewUserMutation.php we have args function to declare field input and type input. Type::nonNull mean the field is required, in GraphQL query marked by exclamation (!), after save success we will return data user UpdateUserMutation.php is example update data user, all action update and insert still using Eloquent and you can using Query builder for complicated query 2. Append Mutation in GraphQL you can find graphql.php in config folder and append class with namespace in mutation schema after append mutation class, open in documentation appears mutation detail 4. Demo don’t worry about full source code, you can access it below :). The next article we will continue learn GraphQL JWT Authentication Click ❤ and follow me to get other articles. thanks related articles
https://medium.com/skyshidigital/easy-build-api-using-laravel-and-graphql-mutation-part-2-14dfc9ceb44c?source=rss-ce18b9b10401------2
CC-MAIN-2020-16
refinedweb
266
52.6
Kazade 1019 Report post Posted October 16, 2004 Hi i'm having a lot of trouble with the stl vector. It keeps throwing me linker errors whenever I try to use push_back. The errors I am getting are: [Linker error] undefined reference to `std::_GLIBCPP_mutex_init(' [Linker error] undefined reference to `std::_GLIBCPP_once' [Linker error] undefined reference to `std::_GLIBCPP_mutex' [Linker error] undefined reference to std::_GLIBCPP_mutex_address_init()' there are a few more but they are all very similar. In a class I have the line vector<char*> textureNames; and in the same header file i have #include <vector> using namespace std; and in one of the methods: textureNames.push_back("hello"); If i comment out that line, everything compiles. This has me stumped and I cant find any info on the errors. So any help would be great, i'm using Dev C++. Thanks Kazade. 0 Share this post Link to post Share on other sites
https://www.gamedev.net/forums/topic/276598-vector-push_back-causing-linker-errors/
CC-MAIN-2017-39
refinedweb
154
61.56
A loader implementing the PasteDeploy syntax to be used by plaster. Project description plaster_pastedeploy is a plaster plugin that provides a plaster.Loader that can parse ini files according to the standard set by PasteDeploy. It supports the wsgi plaster protocol, implementing the plaster.protocols.IWSGIProtocol interface. Usage Applications should use plaster_pastedeploy to load settings from named sections in a configuration source (usually a file). Please look at the documentation for plaster on how to integrate this loader into your application. Please look at the documentation for PasteDeploy on the specifics of the supported INI file format. Most applications will want to use plaster.get_loader(uri, protocols=['wsgi']) to get this loader. It then exposes get_wsgi_app, get_wsgi_app_settings, get_wsgi_filter and get_wsgi_server. import plaster loader = plaster.get_loader('development.ini', protocols=['wsgi']) # to get any section out of the config file settings = loader.get_settings('app:main') # to get settings for a WSGI app app_config = loader.get_wsgi_app_settings() # defaults to main # to get an actual WSGI app app = loader.get_wsgi_app() # defaults to main # to get a filter and compose it with an app filter = loader.get_wsgi_filter('filt') app = filter(app) # to get a WSGI server server = loader.get_wsgi_server() # defaults to main # to start the WSGI server server(app) Any plaster.PlasterURL options are forwarded as defaults to the loader. Some examples are below: development.ini#myapp development.ini?http_port=8080#main pastedeploy+ini:///path/to/development.ini pastedeploy+ini://development.ini#foo egg:MyApp?debug=false#foo 0.7 (2019-04-12) Support Python 3.7. Depend on pastedeploy >= 2.0 to enforce new behavior when overriding defaults. Default values passed into the loader will now override values in the [DEFAULT] section. See 0.6 (2018-07-11) Change setup_logging to invoke logging.config.fileConfig with disable_existing_loggers=False to avoid disabling any loggers that were imported prior to configuration of the logging system. See 0.5 (2018-03-29) Removed environment variable support entirely for now. The feature requires bugfixes upstream in PasteDeploy which have not been done yet and this was breaking people’s environments so it is gone for now. See 0.4.2 (2017-11-20) Fix ConfigDict.copy so that it works. See 0.4.1 (2017-07-10) Disable environment variable support on Python 2. PasteDeploy does not support escaping the contents on Python 2 which means any variable with a value of the format %(foo)s would break the parser. Because this is implicit behavior it was deemed too error prone to support. See Escape environment variables such that their contents are not subject to interpolation. See Invoke logging.basicConfig when setup_logging is called and the config file doesn’t contain any logging setup or the URI is using the egg: protocol. See 0.4 (2017-07-09) Fix get_settings for an arbitrary section to follow the same rules as PasteDeploy with regards to the handling of defaults. The goal of this package is to be compliant with PasteDeploy’s format for all sections in the file such that there are no surprising format changes in various sections. Supported added for set default_foo = bar and get foo = default_foo syntax to override a default value and to pull a default value into the settings, respectively. In the above example the value foo = bar would be returned. Any other defaults not pulled into the section via either interpolation or the get syntax will be ignored. See Inject environment variables into the defaults automatically. These will be available for interpolation as ENV_<foo>. For example if environment variable APP_DEBUG=true then %(ENV_APP_DEBUG)s will work within the ini file. See get_settings and get_wsgi_app_settings both return only the local config now. However, the returned object has a global_conf attribute containing the defaults as well as a loader attribute pointing at the loader instance. See 0.3.2 (2017-07-01) Resolve an issue in which NoSectionError would not be properly caught on Python 2.7 if the configparser module was installed from PyPI. See 0.3.1 (2017-06-02) Recognize the pastedeploy+egg scheme as an egg type. 0.3 (2017-06-02) Drop the ini scheme and replace with file+ini and pastedeploy. Also rename ini+pastedeploy and egg+pastedeploy to pastedeploy+ini and pastedeploy+egg respectively. See 0.2.1 (2017-03-29) Fix a bug in 0.2 in which an exception was raised for an invalid section if the a non-config-file-based protocol was used. 0.2 (2017-03-29) No longer raise plaster.NoSectionError exceptions. Empty dictionaries are returned for missing sections and a user should check get_sections for the list of valid sections. 0.1 (2017-03-27) Initial release. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/plaster-pastedeploy/
CC-MAIN-2022-40
refinedweb
805
50.63
This chapter describes how to use NetBeans IDE (“the IDE”) and GlassFish to build and deploy a web service and client that use WSIT. It includes examples of the files that the IDE helps you create and examples of the build directories and the key files that the IDE produces to create a web service and a client. This chapter covers the following topics: Registering GlassFish with the IDE Configuring WSIT Features in the Web Service Deploying and Testing a Web Service Creating a Client to Consume a WSIT-Enabled Web Service Before. The. Now that you have coded a web service, you can configure the web service to use WSIT technologies. This section only describes how to configure the WSIT Reliable Messaging technology. For a discussion of reliable messaging, see Chapter 6, Using Reliable Messaging. To see how to secure the web service, see Chapter 7, Using WSIT Security. To> Now that you have configured the web service to use WSIT technologies, you can deploy and test it. Right> Now that you have built and tested a web service that uses WSIT technologies, you can create a client that accesses and consumes that web service. The client will use the web service’s WSDL to create the functionality necessary to satisfy the interoperability requirements of the web service. To create a client to access and consume the web service, perform the following steps. Choose File->New Project, select Web Application from the Web category and click Next. Name the project, for example, CalculatorWSServletClient, and click Finish. Right-click the CalculatorWSServletClient node and select New->Web Service Client. The New Web Service Client window appears. NetBeans submenus are dynamic, so the Web Service Client option may not appear. If you do not see the Web Service Client option, select New->File\Folder->Webservices->Web Service Client. Select the WSDL URL option. Cut and paste the URL of the web service that you want the client to consume into the WSDL URL field. For example, here is the URL for the CalculatorWS web service: When JAX-WS generates the web service, it appends Service to the class name by default. Type org.me.calculator.client in the Package field, and click Finish. The Projects window CalculatorWSServletClient project node, choose Properties, click Run, type /ClientServlet in the Relative URL field, and click OK. If ClientServlet.java is not already open in the Source Editor, open it., then choose Web Service Client Resources->Call Web Service Operation. The Select Operation to Invoke dialog box appears. Browse to the Add operation and click OK. The processRequest method is as follows, with bold indicating code added by the IDE:WS port = service.getCalculatorWSPort(); // TODO initialize WS operation arguments here int i = 0; int j = 0; // TODO process result here int result = port.add(i, j); out.println("Result = " + result); } catch (Exception ex) { // TODO handle custom exceptions here } out.println("</body>"); out.println("</html>"); out.close(); } Change the values for int i and int j to other numbers, such as 3 and 4. Add a line that prints out an exception, if an exception is thrown. The try/catch block is as follows (new and changed lines from this step and the previous step are highlighted in bold text): try { // Call Web Service Operation org.me.calculator.client.CalculatorWS port = service.getCalculatorWSPort(); // TODO initialize WS operation arguments here int i = 3; int j = 4; // TODO process result here int result = port.add(i, j); out.println("<p>Result: " + result); } catch (Exception ex) { out.println("<p>Exception: " + ex); } If Reliable Messaging is enabled, the client needs to close the port when done or the server log will be overwhelmed with messages. To close the port, first add the following line to the import statements at the top of the file: import com.sun.xml.ws.Closeable; Then add the line in bold at the end of the try block, as shown below. try { // Call Web Service Operation org.me.calculator.client.CalculatorWS port = service.getCalculatorWSPort(); // TODO initialize WS operation arguments here int i = 3; int j = 4; // TODO process result here int result = port.add(i, j); out.println("<p>Result: " + result); ((Closeable)port).close(); } catch (Exception ex) { out.println("<p>Exception: " + ex); } Right-click the project node and choose Run Project. The server starts (if it was not running already), the application is built, deployed, and run. The browser opens and displays the calculation result.
http://docs.oracle.com/cd/E19159-01/820-1072/ahibn/index.html
CC-MAIN-2015-27
refinedweb
739
57.37
tl. Below is a contrived example, in which we load a profile. After the yield statements, you can see 3 side effects that tend to show up in our team's sagas: select"instructs the middleware to invoke the provided selector" on the store put"instructs the middleware to dispatch an action" to the store callinstructs the middleware to call the given function You can find full descriptions in the API reference. All the code snippets in this blog can be found in this example repository. import {call, put, select} from 'redux-saga/effects'; import {isAuthenticated} from './selectors'; import {loadProfileFailure, loadProfileSuccess} from './actionCreators'; import {getProfile} from './api'; export function* loadProfileSaga(action) { // use a selector to determine if the user is authenticated const authenticated = yield select(isAuthenticated); if (authenticated) { // call the API and dispatch a success action with the profile const profile = yield call(getProfile, action.profileId); yield put(loadProfileSuccess(profile)); } else { // dispatch a failure action yield put(loadProfileFailure()); } } Testing sagas step-by-step is rubbish To test sagas, our approach so far has been to call the generator function to get the iterator object, and then to manually call .next() to bump through the yield statements, asserting on the value of each yield as we go. To test that the saga dispatches a failure action if the user is not authenticated, we can assert that the first gen.next() - i.e. the first yield - calls the selector. Then, to pretend that the selector returned false, we need to pass a pretend return value from the selector into the following gen.next(). That's why we have to call gen.next(false).value in the test below. Without an intimate understanding of generators, this syntax is alien and opaque. it('should fail if not authenticated', () => { const action = {profileId: 1}; const gen = loadProfileSaga(action); expect(gen.next().value).toEqual(select(isAuthenticated)); expect(gen.next(false).value).toEqual(put(loadProfileFailure())); expect(gen.next().done).toBeTruthy(); }); Next, let's test the case where the user is authenticated. It's not really necessary to assert that the first yield is a select(), since we did that in the previous test. To avoid the duplicate assertion, we can write gen.next() outside of an assertion to just skip over it. However, when reading the test in isolation, this gen.next() is just a magic incantation, whose purpose is not clear. Like in the previous test, we can call gen.next(true).value to pretend that the selector has returned true. Then, we can test that the following yield is the API call, pass some pretend return value of getProfile() into the following gen.next() and assert that the success action is dispatched with that same return value. it('should get profile from API and call success action', () => { const action = {profileId: 1}; const gen = loadProfileSaga(action); const someProfile = {name: 'Guy Incognito'}; gen.next(); expect(gen.next(true).value).toEqual(call(getProfile, 1)); expect(gen.next(someProfile).value).toEqual(put(loadProfileSuccess(someProfile))); expect(gen.next().done).toBeTruthy(); }); Why is step-by-step testing bad? Unintuitive test structure Outside of saga-land, 99% of tests that we write roughly follow an Arrange-Act-Assert structure. For our example, that would be something like this: it('should fail if not authenticated', () => { given that the user is not authenticated when we load the profile then loading the profile fails }); For sagas, the conditions of our tests could be the results of side effects like yield call or yield select. The results of these effects are passed as arguments into the gen.next() call that immediately follows, which is often itself inside an assert. This is why the first example test above includes these two lines: // this is the call that we want to "stub" // ↓ expect(gen.next().value).toEqual(select(isAuthenticated)); expect(gen.next(false).value).toEqual(put(loadProfileFailure())); // ↑ // this is the return value (!) So, rather than Arrange-Act-Assert, the example saga tests above are more like this: it('should fail if not authenticated', () => { create the iterator for each step of the iterator: assert that, given the previous step returns some_value, the next step is a call to someFunction() }); Difficult to test negatives For the example saga, it would be reasonable to test that we don't call the API if the user is not authenticated. But if we're testing each yield step-by-step, and we don't want to make assumptions about the internal structure of the saga, the only thorough way to do this is to run through every yield and assert that none of them call the API. expect(gen.next().value).not.toEqual(call(getProfile)); expect(gen.next().value).not.toEqual(call(getProfile)); ... expect(gen.next().done).toBeTruthy(); We want to assert that getProfile() is never called, but instead we have to check that every yield is not a call to getProfile(). Coupling between test and implementation Our tests closely replicate our production code. We have to bump through the yield statements of the saga, asserting that they yield the right things, and as a byproduct, asserting that they are called in some fixed order. The tests are brittle, and refactoring or extending the sagas is incredibly difficult. If we reorder the side effects, we need to fix all of our expect(gen.next(foo).value) assertions, to make sure we're passing the right return value into the right yield statement. If we dispatch an additional action with a new yield put() near the top of a saga, the tests will all have to have an additional gen.next() added in somewhere, to skip over that yield, and move the assertions "one yield down". I have frequently stared at a failing test, repeatedly trying to insert gen.next() in various places, blindly poking until it passes. A better way is to run the whole saga What if we could set up the conditions of our test, instruct the saga to run through everything and finish its business, and then check that the expected side effects have happened? That's roughly how we test every other bit of code in our application, and there's no reason we can't do that for sagas too. The golden ticket here is our utility function recordSaga(), which uses redux-saga's runSaga() to start a given saga outside of the middleware, with a given action as a parameter. The options object is used to define the behaviour of the saga's side effects. Here, we're only using dispatch, which fulfils put effects. The given function adds the dispatched actions to a list, which is returned after the saga is finished executing. import {runSaga} from 'redux-saga'; export async function recordSaga(saga, initialAction) { const dispatched = []; await runSaga( { dispatch: (action) => dispatched.push(action) }, saga, initialAction ).done; return dispatched; } With this, we can mock some functions to set up the test's conditions, run the saga as a whole, and then assert on the list of actions dispatched or functions called to check its side effects. Amazing! Consistent! Familiar! Note: it's possible to pass a store into runSaga() that selectors would be run against, as in the example in the documentation. However, instead of building a fake store with the correct structure, we've found it easier to stub out the selectors. Here's the necessary set up, which can go in a describe() block. We're using jest to stub the functions that the saga imports. api.getProfile = jest.fn(); selectors.isAuthenticated = jest.fn(); beforeEach(() => { jest.resetAllMocks(); }); For our first test, we can set up the conditions of our test using the stubbed selector, run through the saga, and then assert on the actions it dispatched. We can also assert that the API call was never made! it('should fail if not authenticated', async () => { selectors.isAuthenticated.mockImplementation(() => false); const initialAction = {profileId: 1}; const dispatched = await recordSaga( loadProfileSaga, initialAction ); expect(dispatched).toContainEqual(loadProfileFailure()); expect(api.getProfile).not.toHaveBeenCalled(); }); In our second test, we can mock the implementation of the API function to return a profile, and then later, assert that the loadProfileSuccess() action was dispatched, with the correct profile. it('should get profile from API and call success action if authenticated', async () => { const someProfile = {name: 'Guy Incognito'}; api.getProfile.mockImplementation(() => someProfile); selectors.isAuthenticated.mockImplementation(() => true); const initialAction = {profileId: 1}; const dispatched = await recordSaga( loadProfileSaga, initialAction ); expect(api.getProfile).toHaveBeenCalledWith(1); expect(dispatched).toContainEqual(loadProfileSuccess(someProfile)); }); Why is it better to test as a whole? - Familiar test structure, matching the Arrange-Act-Assert layout of every other test in our application. - Easier to test negatives, because the saga will actually call functions, so we have the full power of mocks at our disposal. - Decoupled from the implementation, since we're no longer testing the number or order of yieldstatements. I think this is absolutely the main reason why this approach is preferable. Instead of testing the internal details of the code, we're testing its public API - that is, its side effects. The two approaches to testing sagas are mentioned in the redux-saga documentation, but I'm surprised the step-by-step method is even discussed. Testing a saga as a whole is conceptually familiar, and considerably less brittle. Heavily inspired by this github issue. Discussion (13) This is a great article! Thank you for this! How would you throw exceptions to test for api call failures? For example, if you had a try / catch block for, const profile = yield call(getProfile, action.profileId); When you test the saga as a whole, how do you force an error? I tried using to mockImplementation to return a new Error(), but that doesn't go into the catch block. I don't know if the APIs are changed, at the moment (Feb, 2020) runSagareturns a Task that has a toPromise()method. So await runSaga(...).donedoes not make sense, you need to do anyway: thank you so much for the article 😊 i'm not sure that's entirely true. when i've gone down the path of testing sagas step-by-step, i've thrown gen.next()s into the body of the test without any assertions to get to the step i'm actually trying to test. it's not great and it's pretty brittle if you change your order of operations, but it's not silly either. i don't need to assert that the saga isn't calling a function. Phil, this is brilliant- thanks for writing the article. I'm trying to (roughly) define a testing approach for sagas that'll encourage a more maintainable test suite, and I think you've just nailed a decent way of going about it without introducing another dependency! Agree with you Phil! I've come across this repo where you can set up end to end test for sagas github.com/jfairbank/redux-saga-te... How you got the api calls to be overrided inside the saga? Thanks bro, you help me a lot..! I'd love it if you wanted to dissect my Redux one line replacement hook... useSync dev.to/chadsteele/redux-one-liner-... Hi Phil, I've been trying the runSaga approach but my dispatch is never called... :-/ I'm not sure if this still relevant, but .done seems to be depracated. Have you tried appending .toPromise() to the end of runsaga ? Really helpful article. Thanks Phil! This helped me alot. Great overview, its surprising how little info there is on testing sagas this way. Awesome post!
https://practicaldev-herokuapp-com.global.ssl.fastly.net/phil/the-best-way-to-test-redux-sagas-4hib
CC-MAIN-2021-43
refinedweb
1,912
55.24
Originally published on my personal blog. Tail call optimization (a.k.a. tail call elimination) is a technique used by language implementers to improve the recursive performance of your programs. It is a clever little trick that eliminates the memory overhead of recursion. In this post, we'll talk about how recursion is implemented under the hood, what tail recursion is and how it provides a chance for some serious optimization. Recursion 101 If you're familiar with function call stacks and recursion, feel free to skip this section. Most languages use a stack to keep track of function calls. Let's take a very simple example: a "hello, world" program in C. #include <stdio.h> int main() { printf("hello, world!\n"); return 0; } Every function call in your program gets its own frame pushed onto the stack. This frame contains the local data of that call. When you execute the above program, the main function would be the first frame on the stack, since that's where your program begins execution. The topmost frame in the stack is the one currently being executed. After it completes execution, it is popped from the stack and the bottom frame resumes execution. In our example, main in turn calls printf, another function, thereby pushing a new frame onto the stack. This frame will contain printf's local data. Once printf completes execution, its frame is popped and control returns to the main frame. Recursive functions do the same. Every recursive call gets its own frame on the stack. Here's a horrible example of a recursive function which prints "hello" n times: // hello_recursive.c void hello(int n) { if (n == 0) return; printf("hello\n"); hello(n - 1); } int main() { hello(2); return 0; } The above code gives the following output: hello hello The function call stack will be something like this: The first two calls will print out "hello" and make recursive calls with n - 1. Once we hit the last call with n = 0, we begin unwinding the stack. Now imagine that we wish to print "hello" a million times. We'll need a million stack frames! I tried this out and my program ran out of memory and crashed. Thus, recursion requires O(n) space complexity, n being the number of recursive calls. This is bad news, since recursion is usually a natural, elegant solution for many algorithms and data structures. However, memory poses a physical limit on how tall (or deep, depending on how you look at it) your stack grows. Iterative algorithms are usually far more efficient, since they eliminate the overhead of multiple stack frames. But they can grow unwieldy and complex. Tail Recursion Now that we've understood what recursion is and what its limitations are, let's look at an interesting type of recursion: tail recursion. Whenever the recursive call is the last statement in a function, we call it tail recursion. However, there's a catch: there cannot be any computation after the recursive call. Our hello_recursive.c example is tail recursive, since the recursive call is made at the very end i.e. tail of the function, with no computation performed after it. ... hello(n - 1); } Since this example is plain silly, let's take a look at something serious: Fibonacci numbers. Here's a non tail-recursive variant: // Returns the nth Fibonacci number. // 1 1 2 3 5 8 13 21 34 ... int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } You might argue that this is tail recursive, since the recursive calls appear at the end of the function. However, the results of the calls are added after they return. Thus, fib is not tail recursive. Here's the tail-recursive variant: int fib_tail(int n, int a, int b) { if (n == 0) return a; if (n == 1) return b; return fib_tail(n - 1, b, a + b); } The recursive call appears last and there are no computations following it. Cool. You may be thinking, "Hmm, tail recursion is interesting, but what is the point of this?". Turns out, it is more than just a way of writing recursive functions. It opens up the possibility for some clever optimization. Tail Call Optimization Tail call optimization reduces the space complexity of recursion from O(n) to O(1). Our function would require constant memory for execution. It does so by eliminating the need for having a separate stack frame for every call. If a function is tail recursive, it's either making a simple recursive call or returning the value from that call. No computation is performed on the returned value. Thus, there is no real need to preserve the stack frame for that call. We won't need any of the local data once the tail recursive call is made: we don't have any more statements or computations left. We can simply modify the state of the frame as per the call arguments and jump back to the first statement of the function. No need to push a new stack frame! We can do this over and over again with just one stack frame! Let's look at our example with the non tail-recursive fib function. To find out the 3rd Fibonacci number, we'd do: ... int third_fib = fib(3); ... Assuming right-to-left precedence (i.e. the direction in which an expression is evaluated), the call stack would look something like this: Quite large, isn't it? Imagine the size of the stack for finding out a later Fibonacci number! The problem here is that all the stack frames need to be preserved. You may use one of the local variables in the addition and hence the compiler needs to keep the frames around. If you look at the assembled output of this program, you'll see a call instruction for the fib function. You can use the -S flag on GCC to output the assembly code. I've deliberately used the -O2 flag which uses the 2nd level of optimization among GCC's 0-3 levels. O2 enables tail call optimization. If you're not familiar with assembly, use GCC's -fverbose-asm flag while compiling. It adds your C code as comments before its corresponding assembled output. Here's the final command, which will produce a .s file: gcc fib.c -S -O2 -fverbose-asm This is what our tail call translates to: # Snippet extracted from: fib.s # fib.c:7: return fib(n - 1) + fib(n - 2); movl %ecx, %edi # ivtmp.22, call fib # subl $2, %ecx #, ivtmp.22 addl %eax, %edx # _4, add_acc_7 Now, I'm not going to pretend that I understand this completely, because I don't. We only care about the instructions, none of the operand details. Notice the call fib instruction? That's the recursive call. It pushes a new frame onto the stack. Once that completes and pops, we have our addition instruction. Thus, we conclude that even at the 2nd level of optimization, the recursive calls cannot be eliminated, thanks to the addition. ... return fib_tail(n - 1, b, a + b); } Let's take a look at our tail recursive Fibonacci function, fib_tail. Once the above recursive call is made, there's no need to keep the local data around. There's no computation following the statement and it's simply returning the value returned by the recursive call; we could do that straight from the recursive call. This presents an opportunity to simply replace the values of the local n, a and b variables with the ones used in the recursive call. Instead of a call instruction like before, the compiler can simply redirect the flow of execution to the first instruction in the function, effectively emulating a recursive call. But, without the overhead of one! Basically, the compiler goes: This is how the call stack would look like: You don't have to take my word for it, let's look at the assembler output for fib_tail. We compile the same way as before: gcc fib_tail.c -S -O2 -fverbose-asm For our tail recursive call, I see the following snippets of assembly: # fib_tail.c:11: return fib(n - 1, b, a + b); movl %eax, %edx # <retval>, b # fib_tail.c:11: return fib(n - 1, b, a + b); leal (%rsi,%rdx), %eax #, <retval> # fib_tail.c:11: return fib(n - 1, b, a + b); leal (%rcx,%rdx), %esi #, _5 # fib_tail.c:11: return fib(n - 1, b, a + b); movl %esi, %edx # _5, b As I said, I don't really understand assembly, but we're just checking if we've eliminated the call fib recursive calls. I'm not really sure how GCC is redirecting the control flow. What matters, however, is that there are no call fib instructions in the code. That means there are no recursive calls. The tail call has been eliminated. Feel free to dive into the assembly and verify for yourself. Support - We've been using C in this post since GCC and Clang both support tail call optimization (TCO). - For C++, the case holds with Microsoft's Visual C++ also offering support. - Java and Python do not support TCO with the intention of preserving the stack trace for debugging. Some internal Java classes also rely on the number of stack frames. Python's BDFL, Guido van Rossum, has explicitly stated that no Python implementations should support TCO. - Kotlin even comes with a dedicated tailreckeyword which converts recursive functions to iterative ones, since the JVM (Kotlin compiles to JVM bytecode) doesn't support TCO. - TCO is part of ECMAScript 6 i.e. the JavaScript specification, however, only Safari's JavaScriptCore engine supports TCO. Chrome's V8 retracted support for TCO. - C# does not support TCO, however, the VM it runs within, Common Language Runtime (CLR) supports TCO. - Functional languages such as Haskell, F#, Scala and Elixir support TCO. It appears that support for TCO is more of an ideological choice for language implementers, rather than a technical one. It does manipulate the stack in ways the programmer would not expect and hence makes debugging harder. Refer the documentation of the specific implementation of your favorite language to check if it supports tail call optimization. Conclusion I hope you understood the idea and techniques behind TCO. I guess the takeaway here is to prefer iterative solutions over recursive ones (that is almost always a good idea, performance-wise). If you absolutely need to use recursion, try to analyze how big your stack would grow with a non-tail call. If both of these conditions don't work for you and your language implementation supports tail call optimization, go for it. Keep in mind that debugging will get harder so you might want to turn off TCO in development and only enable it for production builds which are thoroughly tested. That's it for today, see you in the next post! Discussion Little nitpick: "Assuming right-to-left precedence (i.e. the direction in which an expression is evaluated)" does not specify the order in which the functions are called. This is often stated (even in books) but wrong. The chosen order is implementation (aka compiler) specific and independent from the order their results are then used in the caller. well written keep it up... One question, if I add a local variable to a tail recursive function then will it allocate separate stack frame for every call?
https://practicaldev-herokuapp-com.global.ssl.fastly.net/rohit/demystifying-tail-call-optimization-5bf3
CC-MAIN-2021-04
refinedweb
1,911
65.32
Opened 6 years ago Closed 6 years ago #20896 closed Uncategorized (worksforme) Missing a step in "Activate the admin site" Description If you use Django 1.4.5 and follow the steps on to "Activate the admin site" you'll get a "DoesNotExist at /admin/" error page. With a new installation, the django_site table is empty. It needs at least one record or the admin site will fail with the "DoesNotExist at /admin/" error page. To fix the problem: python manage.py shell from django.contrib.sites.models import Site Site.objects.create(pk=1, domain='YourDomainName', name='YourName') Please update the with this info. An entry for "example.com" should be created automatically when you run syncdb. You may have made a mistake following the instructions.
https://code.djangoproject.com/ticket/20896
CC-MAIN-2019-13
refinedweb
127
61.02
by Bill Wagner Of all the features in C# 3.0, local type inference is generating the most questions and misunderstanding. You know, ‘var’. The fact is local type inference is not as scary as it seems. In fact, you’re not losing strong typing. It’s a simple time saver that is actually necessary to support anonymous types. Let’s begin with anonymous types. Anonymous types are simple tuples, a class containing some set of fields and read/write properties. Essentially, the compiler creates a type that mirrors what you would have written on your own. You’re simply saved the extra typing. Take this query from one of the sample queries included in the LINQ CTP: string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" }; var upperLowerWords = from w in words select new {Upper = w.ToUpper(), Lower = w.ToLower()}; The compiler creates an anonymous type to represent each of the objects returned from the query. The new type’s definition is similar to this: public class Anonymous1 { private string upper; public string Upper { get { return upper; } set { upper = value; } } private string lower; public string Lower { get { return lower; } set { lower = value; } } } I am taking quite a few liberties with the exact names of the generated class and the fields. Remember that when you create a type with multiple members, the compiler creates the new class for you. The local variable upperLowerWords is a sequence of these Anonymous1 objects. The addition of anonymous types has saved you from the drudgery of creating this type by hand. The only problem is that you don’t know the name of the compiler-generated type. This is where local type inference, and the ‘var’ keyword comes in. The actual type generated by the compiler gets a compiler specified name. It’s probably something like <Projection>f__c1. You can’t predict the class name, I only point it out here to show you what the compiler creates. Therefore, the only way to declare variables using these anonymous types is to use var. Var was added to the language so that you can use anonymous types. Now that you see why var exists, let’s look at what it actually does, and more importantly, what it doesn’t do. Var does not create an untyped object; nor is it a synonym for System.Object. Rather, it’s a shorthand variable declaration that means “this variable’s type is the compile time type of the right hand side of this assignment”’ Therefore, these two declarations are equivalent: var i = 5;int i = 5; Both declare a variable ‘i’ that is an integer. To prove that, try this and verify that it does not compile: var i = 5;i = "this is a string"; // Compiler error! Can’t convert string to int After its initial assignment, the type of ‘i’ is fixed. (Note that any variable declared using the var keyword must be assigned when it is declared. The following is illegal: var unknown; // Not Assigned, Not Legal! In fact, there are many restrictions on the var keyword. Variables defined using ‘var’ must be local variables declared inside a method block (or inside a property getter or setter). You can’t declare member variables with var; you can’t declare a method return value as var. Now that you know what var is and isn’t let’s briefly discuss some of the current thinking behind when you should use var as a variable declaration. You must use var when you are declaring a variable that is based on an anonymous type. You don’t have any choice there. I also find that I use the var declaration for many results from queries. As I create new queries, I test them step by step, and I’ll declare each intermediate result using ‘var’. Then, as I refactor the code to its final form, I’ll occasionally replace var with the actual type. In general, I’ll replace var with an explicit type only if it increases the readability of the code. Often times, it doesn’t. Consider this sample (also from the CTP samples): string[] words = { "cherry", "apple", "blueberry" };var sortedWords = from w in words orderby w select w; It’s fairly obvious that sortedWords is some sequence of strings. (It’s actually a System.Query.OrderedSequence<string, string>). In my opinion, OrderedSequence<string,string> doesn’t add any new information for me when I’m trying to read this code. In fact, I think it’s clearer with the var keyword. If you’re really opposed for ‘var’, you might consider replacing var with IEnumerable<string>, but that would depend on the usage. Var is really a rather simple concept: it’s used for local type inference: local variables whose value is assigned as part of the declaration of the variable. Nothing weakly typed, nothing magical. It’s a combination of a necessity for using anonymous types, and a convenience for complicated variable type definitions. The more you see it used, the more it becomes part of your regular vocabulary, and the clearer it becomes.
http://msdn.microsoft.com/en-us/vcsharp/bb417257.aspx
crawl-002
refinedweb
845
64
munmap - unmap pages of memory #include <sys/mman.h> int munmap(void *addr, size_t len); corresponding(). Upon successful completion, munmap() shall return 0; otherwise, it shall return -1 and set errno to indicate the error. The munmap() function shall fail if:The following sections are informative. None. The munmap() function is only supported if the Memory Mapped Files option or the Shared Memory Objects option is supported. The munmap() function corresponds to SVR4, just as the mmap() function does. It is possible that an application has applied process memory locking to a region that contains shared memory. If this has occurred, the munmap() call ignores those locks and, if necessary, causes those locks to be removed. None. .
http://manpages.sgvulcan.com/munmap.3p.php
CC-MAIN-2017-09
refinedweb
117
57.16
malloc, calloc, reallocarray, realloc, free— #include <stdlib.h>void * malloc(size_t size); void * calloc(size_t nmemb, size_t size); void * reallocarray(void *ptr, size_t nmemb, size_t size); void * realloc(void *ptr, size_t size); void free(void *ptr); char *malloc_options; malloc() function allocates uninitialized space for an object of the specified size. malloc() calculation nmemb * size. The free() function causes the space pointed to by ptr to be either placed on a list of free pages to make it available for future allocation or, if required, to be returned to the kernel using munmap(2). If ptr is a NULLpointer, no action occurs. If ptr was previously freed by free(), realloc(), or reallocarray(), the behavior is undefined and the double free is a security concern. malloc(), calloc(), realloc(), and reallocarray() return a pointer to the allocated space; otherwise, a NULLpointer is returned and errno is set to ENOMEM. If size or nmemb is equal to 0, a unique pointer to an access protected, zero sized object is returned. Access via this pointer will generate a SIGSEGVexception. If multiplying nmemb and size results in integer overflow, calloc() and reallocarray() return NULLand set errno to ENOMEM. The free() function returns no value. calloc() or the extension realloc); MALLOC_OPTIONS malloc() must be used with multiplication, be sure to test for overflow: size_t num, size; ... /* Check for size_t overflow */ if (size && num > SIZE_MAX / size) errc(1, EOVERFLOW, "overflow"); if ((p = malloc(size * num)) == NULL) err(1, NULL); int num, size; ... /* Avoid invalid requests */ if (size < 0 || num < 0) errc(1, EOVERFLOW, "overflow"); /* Check for signed int overflow */ if (size && num > INT_MAX / size) errc(1, EOVERFLOW, "overflow"); if ((p = malloc(size * num)) == NULL) err(1, NULL); calloc() or reallocarray(). The above examples could be simplified to: if ((p = reallocarray(NULL, num, size)) == NULL) err(1, NULL); if ((p = calloc(num, size)) == NULL) err(1, NULL); malloc(), calloc(), realloc(), reallocarray(), or free() detect an error condition, a message will be printed to file descriptor 2 (not using stdio). Errors will result in the process being aborted. Here is a brief description of the error messages and what they mean: Xoption is specified it is an error for malloc(), calloc(), realloc(), or reallocarray() to return NULL. free(), realloc(), or reallocarray() an unallocated pointer was made. free(), realloc(), or reallocarray() has been modified. size or nmemb() or reallocarray() instead of using multiplication in malloc() and realloc() to avoid these problems on OpenBSD.
https://man.openbsd.org/OpenBSD-5.9/free.3
CC-MAIN-2018-39
refinedweb
402
51.99
WWW::Blog::Identify - Identify blogging tools based on URL and content use WWW::Blog::Identify "identify"; my $flavor = identify( $url, $html ); Attempts to identify the blog based on an examination of the URL and content. Returns undef if all tests fail, otherwise returns a guess as to the blog 'flavor'. This is a heuristic module for identifying weblogs based on their URL and content. The module is a compilation of identifying patterns observed in the wild, for a variety of blogging tools and providers worldwide. You can read a full list of blogs represented in the README. Please email the author if you have a blogging engine you would like added to the detector. The module first checks the URL for common blog hosts (BlogSpot, Userland, Persianblog, etc.) and returns immediately if it can find a match. Failing that, it will look through the blog HTML for distinctive markers (such as "powered by" images) or META generator tags. As a last resort, it will test to see if the page contains an RSS feed, or has the word 'blog' in it repeated at least five times. The philosophy of this module is to favor false negatives over false positives. If you are a blog tool author, you can vastly improve the detection rate simply by using a generator tag in your default template, like this: <meta name="generator" content="myBlogTool 0.01" /> This module is in active use on a large blog index, so I'll try to keep it reasonably up to date. None by default. You can export 'identify' out into your namespace if you like. Maciej Ceglowski, <developer@ceglowski.com> (c) 2003 Maciej Ceglowski This module is distributed under the same license as Perl itself.
http://search.cpan.org/~mceglows/WWW-Blog-Identify-0.06/Identify.pm
crawl-002
refinedweb
288
63.29
This tutorial describes how to read text resources from satellite assemblies in ASP.NET applications. The method is not unique and other methods can be found. This particular one is based on Duwamish 7.0 sample application. Let's now start step by step Create a new ASP.NET Web Application project and give it a name. I will name mine "ResourcesDemo". The project will contain in the root a resource file that will be the application's default resource. This resource will be part in the main assembly so any changes to this require a project recompilation. So let's add an "Assembly Resource File" from the "Add New Item" menu item. The name this file will have is important because will be used when reading the text resources. I will name my file "TextRes.resx". The file can now be edited either in its Data form or directly in Xml form. Add some strings to the file to play with. Here is how it looks my resx file data (in xml view) after I added 2 strings: ... <data name="EMPLOYEE"> <value>Employee</value> </data> <data name="DELETE_EMPLOYEE_CONFIRMATION"> <value>Are you sure you want to delete this employee? Doesn't matter it will be deleted any way...</value> </data> ... This is the class that will read the resources( through the ResourceManager object) and provide a static method for text resource retrieval. Let's name this class ResourceText using System; using System.Resources; using System.Reflection; namespace ResourcesDemo { /// <summary> /// Class for resource retrieval /// </summary> public class ResourceText { private ResourceText() {} private static ResourceManager _resourceManager; } } The constructor of ResourceText class is marked as private because only it's static methods are used. Let's add now code for ResourceManager creation public static void InitializeResources() { Assembly resourceAssembly = Assembly.GetExecutingAssembly(); _resourceManager = new ResourceManager( "ResourcesDemo.TextRes", resourceAssembly); _resourceManager.IgnoreCase = true; //This is my preference. You can change this... } This method will be called from Global.asax Application_Start To locate the resource we will need first to locate the assembly that contains the resource file. A simple method for doing this is to use the Assembly static method GetExecutingAssembly to get the assembly we are in. An alternative method is to use the method Load to locate the assembly. The first argument ( baseName) in the ResourceManager constructor is the full name of the resource file including the namespace but without extension. Be very careful here: if your default namespace is something like n1.n2.n3 then the baseName must be n1.n2.n3.ResourceFileNameWithoutExtension Let's now add the main method of this class for text retrieval public static string GetString(string key) { try { string s = _resourceManager.GetString( key ); if( null == s ) throw(new Exception()); return s; } catch { return String.Format("[?:{0}]", key); } } If the key is not found in the resource a text containing the key itself is returned to help quickly view the missing strings. For example for EMPLOYEE key the string [?:EMPLOYEE] is returned if not found in resource file. This can be change to suit your particular needs. The static method InitializeResources must be called before we ask for a string to ResourceText class. So we will put a call to this method in Application_Start in Global.asax.cs file assure the initialization is done. protected void Application_Start(Object sender, EventArgs e) { ResourceText.InitializeResources(); } Add a Web Form to the project and add a label in it <asp:Label id=Label1</asp:Label> On PageLoad event of the web form add the following line: private void Page_Load(object sender, System.EventArgs e) { Label1.Text = ResourceText.GetString( "DELETE_EMPLOYEE_CONFIRMATION"); } Now if we will run the project we will se an page with the text we put in the resource file. Until here we sow how we can read string resources from a resource located in the main assembly of a web application. This is no doubt very useful as we can put the text from the pages in a single file and not spread in the hole application. But the real usefulness of the resources show up when multilingual applications must be made. The first thing we must done is add another resource assembly file. This file must be named in the following format: [ResourceFileName].[language].resx so we will name our file TextRes.fr.resx for French language as an example. Edit the file to add the same keys as in the TextRes.resx file. Here is an example of the file data (in Xml view): ... <data name="EMPLOYEE"> <value>Employ�</value> </data> <data name="DELETE_EMPLOYEE_CONFIRMATION"> <value>�tes-vous s�r que vous voulez supprimer cet employ� ? N'importe, pas il sera quand m�me supprim�...</value> </data> ... Now if you look in the bin folder of your web application you will notice a folder named "fr" that contains the dll ResourcesDemo.resources.dll. This dll contains the resource file for French. CurrentUICultureto the CultureInfofor French language. We do this in the Application_BeginRequestin Global.asax.cs file. using System.Threading; using System.Globalization; ... private void Page_Load(object sender, System.EventArgs e) { Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("fr-FR"); } Run the application and voil� the text in French appear on the page. That's all. See the demo application for this code assembled together. You will need to copy the project folder in your wwwroot and create an application in IIS. The demo application was build and tested on a Windows 2000 Professional with .Net Framework 1.0 SP2. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/aspnet/SatResourcesDemo.aspx
crawl-002
refinedweb
912
59.4
A device driver needs to work transparently as an integral part of the operating system. Understanding how the kernel works is a prerequisite for learning about device drivers. This chapter provides an overview of the Solaris kernel and device tree. For an overview of how device drivers work, see Chapter 1, Overview of Solaris Device Drivers. This chapter provides information on the following subjects: Multithreaded Execution Environment Displaying the Device Tree Binding a Driver to a Device The)., a driver.. Devices in the Solaris OS are represented as a tree of interconnected device information nodes. The device tree describes the configuration of loaded devices for a particular machine. the branches of the device tree. A branch consists of one or more bus nexus devices and a terminating leaf device. A bus nexus device provides bus mapping and translation services to subordinate devices in the device tree. PCI - PCI bridges, PCMCIA adapters, and SCSI HBAs are all examples of nexus devices. The discussion of writing drivers for nexus devices is limited to the development of SCSI HBA drivers (see Chapter 18, SCSI Host Bus Adapter Drivers). Leaf devices are typically peripheral devices such as disks, tapes, network adapters, frame buffers, and so forth. Leaf device drivers export the traditional character driver interfaces and block driver interfaces. The interfaces enable user processes to read data from and write data to either storage or communication devices. The system goes through the following steps to build the tree: The CPU is initialized and searches for firmware. The main firmware (OpenBoot, Basic Input/Output System (BIOS), or Bootconf) initializes and creates the device tree with known or self-identifying hardware. When the main firmware finds compatible firmware on a device, the main firmware initializes the device and retrieves the device's properties. The firmware locates and boots the operating system. The kernel starts at the root node of the tree, searches for a matching device driver, and binds that driver to the device. If the device is a nexus, the kernel looks for child devices that have not been detected by the firmware. The kernel adds any child devices to the tree below the nexus node. The kernel repeats the process from Step 5 until no further device nodes need to be created. Each driver exports a device operations structure dev_ops(9S) to define the operations that the device driver can perform. The device operations structure contains function pointers for generic operations such as attach(9E), detach(9E), and getinfo(9E). The structure, that driver requests its parent to provide the service. This approach enables drivers to function regardless of the architecture of the machine or the processor. A typical device tree is shown in the following figure. The nexus nodes can have one or more children. the ls(1) command to view the hierarchy. . The following excerpted prtconf(1M) command example namespace that represents the device tree. Following is an abbreviated listing of the /devices namespace. determines the drivers that are used to manage the devices. Binding a driver to a device refers to the process by which the system selects a driver to manage a particular device. The binding name is the name that links a driver to a unique device node in the device information tree. For each device in the device tree, the system attempts to choose a driver from a list of installed drivers. Each device node has an associated name property. This property can be assigned either from an external agent, such as the PROM, during system boot or from a driver.conf configuration file. In any case, the name property represents the node name assigned to a device in the device tree. The node name is the name visible in /devices and listed in the prtconf(1M) output. A device node can have an associated compatible property as well. The compatible property. Each entry on the list is processed until the system either finds a match or reaches the end of the list. enables the system to determine alternate driver names for devices with a generic device name, for example, glm for scsi HBA device drivers or hme for ethernet device drivers. Devices with generic device names are required to supply a compatible property. For a complete description of generic device names, see the IEEE 1275 Open Firmware Boot Standard. The following figure shows a device node with a specific device name. The driver binding name SUNW,ffb is the same name as the device node name. The following figure shows a device node with the generic device name display. The driver binding name SUNW,ffb is the first name on the compatible property driver list that matches a driver on the system driver list. In this case, display is a generic device name for frame buffers.
https://docs.oracle.com/cd/E19253-01/816-4854/kernelovr-77198/index.html
CC-MAIN-2019-39
refinedweb
799
56.15
Hi! I am very confused. I have attached a simple project with only two files. The first file define a simple class, while the second creates an instance of it. This is a very simple test project. But I could not use autocompletion in it. I understand that I should not open an issue. Most likely I did something wrong doing. I can anyone help? I'm at a loss. Here is two files: [Model.php] <?php namespace Core { class Model { function getName() { return \get_class($this); } } } [autocomplete.php] <?php $y= new Core\Model(); $y->getName(); In the first line of autocomplete.php autocompletion works fine for class name. From this it is expected that the project is indexed properly and that the second line autocompletion will work too. However, it is not. WinXP SP3 PHPStorm PS-102.114 Thank you! Attachment(s): tv2.zip Hi alexey, Tested in latest EAP build -- PS-102.206. In autocomplete.php file you have to look at Structure tab: PhpStrom treats $y as Model .. but it should be Core\Model instead. Add use Core\Model; to your autocomplete.php: Now it works fine -- PhpStorm treats $y as Core\Model. On another hand -- the code below can be processed by PhpStorm just fine: Model.php autocomplete.php As I'm not using namespaces in my projects I have not done any deep research into this subject and therefore cannot really advice if it is a bug, or inconsistent behavior or if it meant to be this way (i.e. PhpStorm behaves correctly and you need to use "use" clause in order for namespaces to work properly). Andriy, thank you very much for this reply.First of all Structure tab explain me very much. Now it looks like PhpStorm parses namespases incorrectly. Using "use" statements in this example is optional from php point of view.This two ways are equivalent from php point of view <?php $y= new Core\Model(); <?php use Core\Model; $y = new Core\Model(); On the other hand Nebeans parses this sources correct at all ways (screenshot). Perhaps I forgot to check some option in Settings like Netbeans "PHP Version PHP 5.3". Without this option Netbeans parses PHP 5.3 featured project incorrectly. can anyone help? Thanks! Attachment(s): a.JPG Hi alexey, There is no such option in PhpStorm as it officially supports PHP v5.3.x only. I can only suggest look trough already reported issues or create new one if nothing matches your case.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206377259-PHP-autocomplete-simple-project-102-114?page=1
CC-MAIN-2020-10
refinedweb
416
69.68
. Basic Exception Handling To begin, it must be said that bare exceptions are usually NOT recommended! You will see them used though and I’ve used them myself from time to time. A bare except looks like this: try: print monkey except: print "This is an error message!" As you can see, this will catch ALL exceptions, but you don’t really know anything about the exception which makes handling it pretty tricky. Because you don’t know what exception was caught, you also can’t print out a very relevant message to the user. On the other hand, there are times when I think it’s just plain easier to use a bare except. One of my readers contacted me about this and said that database interactions are a good example. I’ve noticed that I seem to get a wide array of exceptions when dealing with databases too, so I would agree. I think when you reach more than 3 or 4 exception handlers in a row, it’s better to just use a bare except and if you need the traceback, there are ways to get it (see the last section). Let’s take a look at a few normal examples of exception handling. try: import spam except ImportError: print "Spam for eating, not importing!" try: print python except NameError, e: print e try: 1 / 0 except ZeroDivisionError: print "You can't divide by zero!" The first example catches an ImportError only which happens when you import something that Python cannot find. You’ll see this if you try to import SQLAlchemy without actually having it installed or when you mis-spell a module or package name. One good use for catching ImportErrors is when you want to import an alternate module. Take the md5 module. It was deprecated in Python 2.5 so if you are writing code that supports 2.5-3.x, then you may want to try importing the md5 module and then falling back to the newer (and recommended) hashlib module when the import fails. The next exception is NameError. You will get this when a variable hasn’t been defined yet. You’ll also notice that we added a comma “e” to the exception part. This lets us not only catch the error, but print out the informational part of it too, which in this case would be: name ‘python’ is not defined. The third and last exception is an example of how to catch a Zero Division exception. Yes, users still try to divide by zero no matter how often you tell them not to. All of these exceptions that we have looked at our subclasses of Exception, so if you were to write an except Exception clause, you would essentially be writing a bare except that catches all exceptions. Now, what would you do if you wanted to catch multiple errors but not all of them? Or do something no matter what happened? Let’s find out! try: 5 + "python" except TypeError: print "You can't add strings and integers!" except WindowsError: print "A Windows error has occurred. Good luck figuring it out!" finally: print "The finally section ALWAYS runs!" In the code above, you’ll see that we have two except statements under one try. You can add as many excepts as you want or need to and do something different for each one. In Python 2.5 and newer, you can actually string the exceptions together like this: except TypeError, WindowsError: or except (TypeError, WindowsError). You will also notice that we have an optional finally clause that will run whether or not there’s an exception. It is good for cleaning up actions, like closing files or database connections. You can also do a try/except/else/finally or try/except/else, but the else is kind of confusing in practice and to be honest, I’ve never seen it used. Basically the else clause is only executed when the except does NOT get executed. It can be handy if you don’t want to put a bunch of code in the try portion that might raise other errors. See the documentation for more information. Getting the Entire Stack Traceback What if you want to get the entire traceback of the exception? Python has a module for that. It’s called, logically enough, traceback. Here’s a quick and dirty little example: import traceback try: with open("C:/path/to/py.log") as f: for line in f: print line except IOError, exception: print exception print print traceback.print_exc() The code above will print out the exception text, print a blank line and then print the whole traceback using the traceback module’s print_exc method. There are a bunch of other methods in the traceback module that allow you to format the output or get various portions of the stack trace rather than the full one. You should check out the documentation for more details and examples though. There’s another way to get the whole traceback without using the traceback module, at least not directly. You can instead use Python’s logging module. Here’s a simple example: import logging logging.basicConfig(filename="sample.log", level=logging.INFO) log = logging.getLogger("ex") try: raise RuntimeError except RuntimeError, err: log.exception("RuntimeError!") This will create a log file in the same directory that the script is run in with the following contents: ERROR:ex:RuntimeError! Traceback (most recent call last): File "C:\Users\mdriscoll\Desktop\exceptionLogger.py", line 7, in <module> raise RuntimeError RuntimeError As you can see, it will log what level is being logged (ERROR), the logger name (ex) and the message we passed to it (RuntimeError!) along with the full traceback. You might find this even handier than using the traceback module. Creating a Custom Exception As you write complex programs, you might find a need to create your own exceptions. Fortunately Python makes the process of writing a new exception very easy. Here’s a very simple example: ######################################################################## class ExampleException(Exception): pass try: raise ExampleException("There are no droids here") except ExampleException, e: print e All we did here was subclass the Exception type with a blank body. Then we tested it out by raising the error inside a try/except clause and printed out the custom error message that we passed to it. You can actually do this with any exception that you raise: raise NameError(“This is an improper name!”). On a related note, see pydanny’s article on attaching custom exceptions to functions and classes. It’s very good and shows some neat tricks that makes using your custom exceptions easier without having to import them so much. Wrapping Up Now you should know how to catch exceptions successfully, grab the tracebacks and even create your own custom exceptions. You have the tools to make your scripts keep on running even when bad things happen! Of course, they won’t help if the power goes out, but you can cover most cases. Have fun hardening your code against users and their many and varied ways of making your programs crash. Additional Reading - Official Exceptions tutorial - Python’s traceback module documentation - StackOverflow: Catch multiple exception in one line except - AdamSkutt - AdamSkutt - Wayne Bell - AdamSkutt - jmafc - AdamSkutt - peter - New Venture Funds - Hector Alvarez
http://www.blog.pythonlibrary.org/2012/09/12/python-101-exception-handling/
CC-MAIN-2014-52
refinedweb
1,221
63.9
During the sprint I was (at least a little) working with Tom Lazar on the markup stuff. The idea here was to enable more markups via PortalTransforms and then make the default configurable. This means that for any TextField not defining allowable_types a user defined default markup should be used. For this part Martin Aspeli proposed to use utilities as sort of a registry. So I tried to implement it the following way: - create a base interface IMarkupfor all the markups - create derived interfaces for each implemented markup like Markdown, Structured Text, etc. - create a utility for each markup just returning name and mimetype(s) - register these utilities - for getting the list of all possible markups retrieve the list of utilities implementing IMarkup. Now the problem was how to actually write the utilities as I somehow couldn’t find it in the Zope3 book (just local ones but maybe I just missed the global ones. The reason for using global ones was that the local ones will be overhauled soon and thus it would be easier for now to use global ones which do the job, too, for now). So I asked around and discussed it with Martijn Pieters a bit. He proposed at first glance not to use derived interfaces but simply named utilities so all these would just implement IMarkup. So I wonder now when it’s best to use named ones and when derived ones (probably if the derived ones add more functionality). So I went with named utilities and Martijn also showed me how to use them. So here is how I did it for all those who are interested. But first maybe let me tell what utilities are all about. Utilities Actually utilities are very simple components. They are basically a class implementing a more or less simple functionality like e.g. returning a list of items or computing things. So for our markup application a utility for doing the markup could look as follows: class MarkdownSupport: implements(IMarkup) def getName(self): """return our name""" return "Markdown" def mimetype(self): """return our mimetype""" return "text/x-web-markdown" So it needs to define an interface which does look like this:: class IMarkup(Interface): """markup utility""" def getName(): """return name""" def mimetype(): """return mimetype""" In my implementation I actually went a different way in using the transforms of PortalTransforms for the utilities as these exist already and know about their mimetypes and name. The only reason not to do so is maybe a conceptual one as the PortalTransforms module should actually hide them and the transforms are never called directly. So it seems a bit strange to use them now. Registering utilities While the implementation was quite clear to me registering them with ZCML wasn’t. So here’s how it’s being done (but using the transforms now): <utility name="Restructured Text" provides="Products.markup.interface.IMarkup" factory="Products.PortalTransforms.transforms.rest.rest" /> <utility name="Structured Text" provides="Products.markup.interface.IMarkup" factory="Products.PortalTransforms.transforms.st.st" /> As you see, I defined them here for the actual transforms. I also used named utilities and only one common interface. Because I used the transforms directly I need to make them implement ‚IMarkup‘: <five:implements <five:implements I actually used a different IMarkup interface here to fit the methods of the transforms. Basically it should be the same as itransforms already used inside PortalTransforms. Retrieving Utilities So the last part is actually to get the utilites back. If we need a list of all markups registered the above way we need to ask the utility machinery for that interface: from zope.app.zapi import getUtilitiesFor us = getUtilitiesFor(IMarkup) This will return a generator we can iterate over. Each iteration gives a tuple with the name used in configure.zcml and the utility instance. Discussion I actually wasn’t that fond of using utilities as we might not really need the actual utilities (we already have the name) but „misuse“ them for a repository purpose. I’d rather have some other configuration possibility in Zope3 (I also vaguely remember that I’ve seen other such reuses when visiting Philipp but I am not too sure anymore what it was ;-). My other worry was that for each list generation we would need to create all the utility instances although we only might want the name or at least the name. But checking things a bit revealed that utilities are actually only instanciated once. So no too big overhead. Another good thing would probably to have a call like getUtilityNamesFor() which just returns the names. Might be handy..
http://mrtopf.de/personal/how-zope3-utilities-got-introduced-to-me/
CC-MAIN-2017-26
refinedweb
769
52.6
Warm-up: numpy¶ A third order polynomial, trained to predict \(y=\sin(x)\) from \(-\pi\) to \(pi\) by minimizing squared Euclidean distance. This implementation uses numpy to manually compute the forward pass, loss, and backward pass. A numpy array is a generic n-dimensional array; it does not know anything about deep learning or gradients or computational graphs, and is just a way to perform generic numeric computations. import numpy as np import math # Create random input and output data x = np.linspace(-math.pi, math.pi, 2000) y = np.sin(x) # Randomly initialize weights a = np.random.randn() b = np.random.randn() c = np.random.randn() d = np.random.randn() learning_rate = 1e-6 for t in range(2000): # Forward pass: compute predicted y # y = a + b x + c x^2 + d x^3 y_pred = a + b * x + c * x ** 2 + d * x ** 3 # Compute and print loss loss = np.square(y_pred - y).sum() a -= learning_rate * grad_a b -= learning_rate * grad_b c -= learning_rate * grad_c d -= learning_rate * grad_d print(f'Result: y = {a} + {b} x + {c} x^2 + {d} x^3') Total running time of the script: ( 0 minutes 0.000 seconds) Gallery generated by Sphinx-Gallery
https://pytorch.org/tutorials/beginner/examples_tensor/polynomial_numpy.html
CC-MAIN-2021-21
refinedweb
195
66.03
Code. Collaborate. Organize. No Limits. Try it Today. View the source online at.. Celerity was an entry in the App Innovation Contest. It is a game inspired by: If you're unfamiliar with Celerity, check out this brief video to get the basic idea: This article is divided into the overall tasks which went into making the game, followed by a reflection on the competition experience and other notes. To enable some of these tasks to be done in parallel and hit the deadline I brought a few friends in to help; @Dave_Panic (3D trickery guru), @BreadPuncher (game theorist & graphic designer) and @PatrickYtting (maestro).: And specifically having the following features: As I was familiar with XNA and C# I wanted to use them to build the game, however there are a number of obstacles in having them work smoothly on Windows 8. There were some immediate obstacles which had to be overcome to make the project viable: To enable XNA Game Studio 4 I used Aaron Stebner's solution, which is essentially to: To get Visual Studio 2012 to recognise XNA projects I used Steve Beaugé's solution: extension.vsixmanifest <SupportedProducts> <VisualStudio Version="11.0"> <Edition>VSTS</Edition> <Edition>VSTD</Edition> <Edition>Pro</Edition> <Edition>VCSExpress</Edition> <Edition>VPDExpress</Edition> </VisualStudio> </SupportedProducts> If this isn't the first time you're running VS2012 you'll probably find that VS has cached the available extension list. You can tell it to refresh this list by entering this in the VIsual Studio Command Prompt: "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" /setup A nice little trick for opening the VS Command Prompt within a particular folder is to use this shell script: Failing that, create a new XNA project in VS2010 and open it in VS2012. Now, not only do XNA projects open and play nicely, but the standard Content Pipeline works perfectly. If you've ever developed your own game then you'll appreciate how dead and flat the experience can be until sound music and sounds are added. I was very fortunate in having a first rate professional composer on board, but for most people you will most likely be looking at sourcing stock sound and music. I would recommend sticking with the stock sound effect options and advise against recording your own sound effects unless you either have some experience or find there is no other way to get a sound effect that works. Poorly rendered sound can really destroy the immersion in a game. A simple web search for "royalty free music" or "royalty free sound effects" should return you plenty of options. It might cost a small amount, but the quality will give your game a boost. Remember to always double-check the license. Many libraries of "royalty free" files often contain files which actually have restrictions on them, and the last thing you want is a company taking you to court. Another approach might be to join an online game-making community and network with music and audio experts who may be willing to help for free or for a cut of profits. When working with a technology like XNA almost all aspects of UI layout are co-ordinate based. With no friendly vector panels to work with it is especially challenging to create a responsive UI, that is a UI which works well on different target screen resolutions, Part of the Intel AppUp testing process is to ensure that there is no clipped text at several different resolutions, so we had to bear this in mind. The approach for Celerity was to divide the UI into 3 distinct logical panels: A very simple approach to making the layout responsive was taken, which was to anchor TL to the top left corner, TR to the top right corner and UI to the centre of the screen. However simple the approach, the UI always looks like it fits the screen well.Even though the overall layout is slightly fluid, a traditional grid was used to layout elements within the panels. I chose a 25x25 pixel grid but use whatever works for you. Using a grid means that UI elements within a panel will appear orderly and aligned. Once you have the basic layout described you'll need to work out the co-ordinates of the origin and size of each UI element. I chose to do this on paper, on a printed out Grid. It was an invaluable reference when I was actually building the UI in code as it gets very messy very quickly. Here's the sheet as I had it: Whilst settling on this particular grid system, I created some wireframes for the UI. You'll notice that the final UI varies from these slightly, being condensed from several screens to one. This was just to keep the app as simple as possible, but also partly the result of natural evolution during software development. It's normal to discover a better way of doing things later on, and the initial design is only a guide not a contract. I brought @BreadPuncher (a.k.a. Lorc) on board to handle vector icon design. His brief was very much to fit into the Microsoft Design Language style so that everything would look consistent. For those of you who are not fortunate enough to either have graphic skills or a friend who can provide them your most likely options are either to network and find an artist/designer or to use stock graphics. Again, just search the internet for royalty free icons or graphics to suit your needs. There may be a small one-off fee but it will often give your app the visual edge it needs. If your budget permits you can always commission a professional, of course. I did encounter a nasty issue when importing the graphic .png files. The files rendered from Inkscape were appearing with alpha artefacts when rendered by XNA. .png this didn't seem to be the case in practice. Running the images through PixelFormer did the trick. Whilst this application is relatively small, there is still a benefit to dividing the codebase into logical elements or modules. I'll make no claims that I have achieved a perfect example of separation in this rushed project but the principle is sound. 95%+ of the code fell neatly into the following categories: I created a folder and namespace for each. The Game class does little on its own other than to instantiate and co-ordinate activity between the modules based on the above categories: This gives us a very tidy Game class. The constructor simply contains: public CelerityGame() { // Content Content.RootDirectory = CeleritySettings.ContentRootDirectory; // Set Graphics Device graphics = GraphicsDeviceUtil.Create(this); // Modules & layers audio = new AudioModule(); cv = new CVModule(); input = new InputModule(this.Window.Handle); logic = new GameLogic(audio, input); ui = new UILayer(logic); world = new WorldModule(graphics, audio, input, logic); // Events ui.OnClose += (s, e) => { this.Exit(); }; } Then in each of the event methods the Game class calls the same method on any child modules which need processing. For example, in the LoadContent() method, the UILayer and WorldModule are told to load their content: LoadContent() UILayer WorldModule protected override void LoadContent() { // SpriteBatch spriteBatch = new SpriteBatch(GraphicsDevice); // Modules & Layers ui.Load(GraphicsDevice, spriteBatch, Content); world.Load(Content); } The one part of the code which did get somewhat untidy was the UI layer. The code for this isn't the best, but it works and for small changes isn't too bad to deal with. A major UI change could well bring tears to my eyes, however! Take this section as an idea which didn't quite pan out as well as I envisaged. The classes I used for the UI layer were as follows: UIGeometry UIControlHierarchy UIEntity UIEntityItem UIDrawCondition ImageLibrary .resx First, create a resource file and define all your image paths: Now create a static class called ImageLibrary, or something similar, and have one private static variable as follows: // Gfx static GraphicsDevice graphics; Add the following simple helper method: static Texture2D Get(string path) { return Texture2D.FromStream(graphics, TitleContainer.OpenStream(path)); } Now, for each image you want to use add a public static Texture2D variable, e.g.: public static Texture2D // Input device images public static Texture2D InputKeys; public static Texture2D InputGamepad; public static Texture2D InputTilt; public static void Load(GraphicsDevice graphicsDevice) { // Keep graphics device for Get functions graphics = graphicsDevice; // Input InputKeys = Get(ResxImg.InputKeys); InputGamepad = Get(ResxImg.InputGamepad); InputTilt = Get(ResxImg.InputTilt); // ... etc. } InputKeys var InputKeys = ImageLibrary.InputKeys; One last trick is that you can create flat-colour general purpose textures on the fly by using this alternative code in the load method for a given texture: TextureGrey = new Texture2D(graphics, 1, 1); TextureGrey.SetData(new[] { Palette.OverlayGrey }); using Microsoft.Xna.Framework; namespace Celerity.ColourPalette { public static class Palette { public static Color Accent = new Color(0, 204, 255, 255); public static Color SecondaryAccent = new Color(255, 51, 0, 255); public static Color AccentPressed = new Color(0, 204, 255, 128); public static Color MidGrey = new Color(128, 128, 128, 255); public static Color OverlayGrey = new Color(76,76,76, 165); public static Color SemiTransparentWhite = new Color(255, 255, 255, 128); public static Color White = Color.White; public static Color Black = Color.Black; } } The problem of creating a tunnel was broken down into two classes: one to deal with the section of the tunnel we can actually see, TunnelSection, and one to deal with the tunnel as a whole, Tunnel. TunnelSection Tunnel TunnelSection will have the following responsibilities: Tunnel will: A section of tunnel made from triangles has the following properties: public float Radius { get; set; } // Radius of the tunnel walls public int NumSegments { get; set; } // # of segments in wall (5 = pentagonal tunnel) public int TunnelLengthInCells { get; set; } // # of rings of vertices in the tunnel section private float cellSize; // Distance between the rings of vertices++; } } } First new vertex is created with an x and z coordinate of zero, and a y coordinate equal to the desired radius. That point is then rotated around the origin by the appropriate angle and moving on to the next point. Once this has been done for a full circle the process is repeated, but the point is moved further away by the distance defined by cellSize. cellSize Since the square sections that make up the tunnel ought to remain looking square it is necessary to work out the distance between 2 points in the ring of vertices. This is done by creating a point at (0, radius, 0) rotating around the z axis appropriate angle (2 * (float)Math.PI / NumSegments) then measuring the distance between the 2 points. As follows: (0, radius, 0) (2 * (float)Math.PI / NumSegments) float CalculateSectionSize() { Vector3 point1 = new Vector3(0.0f, this.Radius, 0.0f); Vector3 point2 = Vector3.Transform(point1, Matrix.CreateRotationZ(2 * (float)Math.PI / NumSegments)); return Vector3.Distance(point1, point2); } With the vertices in place the next step is to fill the index buffer. The index buffer tells the GPU which vertices to use in which triangle. It’s a list that points to the index of each vertex in the vertex array. the code loops though the vertices in the same order they were created, wiring up the triangles as it goes. The trick is to have them all winding clockwise so backface culling will not make the triangles invisible, which requires a little mental visualisation to work out which vertices ought to be wired into the triangle based on a given point in the triangle. Also, notice there is a special case at the end of the ring of vertices. If this special case were not present the code would create triangles that corkscrewed along the tunnel and ended up leaving a single triangle gap at the start and end of the tunnel section. Here is a TunnelSection: And here are several TunnelSections sewn together to form a Tunnel, with a nice curve for good measure: The tunnel and obstacles are rendered using the same basic texture, only the colour can be altered. This supports a white tunnel with a variety of coloured obstacles. Different colours are either defined in code or calculated at run-time without having to generate a huge number of identical texture files. This requires some simple mathematics, which you have most likely encountered before. Firstly a base greyscale texture is required: In a shader program colours are represented using a value of 0.0 to 1.0 for each component. So, for example, white would be { Red = 1.0, Green = 1.0, Blue = 1.0 } and black would be { Red = 0.0, Green = 0.0, Blue = 0.0 }. { Red = 1.0, Green = 1.0, Blue = 1.0 } { Red = 0.0, Green = 0.0, Blue = 0.0 } Given that anything multiplied by 1.0 remains unchanged and anything multiplied by 0.0 will always be 0.0 the colour of the texture map may be transformed to have any base colour by simply multiplying their components. Taking all white pixels from the base texture { R = 1.0, G = 1.0, B = 1.0 } and multiplying each component by the 100% red { R = 1.0, G = 0.0, B = 0.0 } gives 100% red. Conversely, multiplying by an all black pixel from the texture { R = 0.0, G = 0.0, B = 0.0 } results in a black output colour. { R = 1.0, G = 1.0, B = 1.0 } { R = 1.0, G = 0.0, B = 0.0 } { R = 0.0, G = 0.0, B = 0.0 } Here you can see the results of multiplying each pixel in the texture by a shade of blue { R = 0.0, G = 0.5, B = 1.0 }: { R = 0.0, G = 0.5, B = 1.0 } This is very simple to implement into a shader program. First add a variable to the shader’s parameters to hold the colour: float4 Color; texture TunnelTexture; sampler2D textureSampler = sampler_state { Texture = (TunnelTexture); MipFilter = LINEAR; MagFilter = LINEAR; MinFilter = LINEAR; AddressU = Wrap; AddressV = Clamp; }; If you are unfamiliar with texture samplers check out one of the many tutorials available online, for example here. The next step is simply a matter of multiplying the value retrieved by the texture sampler by the value that was passed into the Color parameter. Like so: float4 output = Color * tex2D(textureSampler, input.TexUV); output.a = 1.0f; // Make sure alpha is always 1.0 Depth Cueing or fading to black/fog colour is an important part of giving scenes depth, subtly helping the player judge distance and hiding objects coming into view. Fortunately it’s very easy to add to the shader code. Celerity took the dead simple approach of fading to black based on the distance to the far clipping plane, which should be defined when the projection matrix is created. For example: projection = Matrix.CreatePerspectiveFieldOfView((float)Math.PI / 4.0f, graphics.GraphicsDevice.Viewport.AspectRatio, 0.01f, farClip); The value of far clip is passed into the shader program so a variable is added to the shader’s parameters. float FarClip; The vertex shader output struct is modified to carry depth information like so: struct VertexShaderOutput { float4 Position : POSITION0; float2 TexUV : TEXCOORD0; float Depth : TEXCOORD1; }; The vertex shader output function is then modified to write the depth information to the struct: VertexShaderOutput VertexShaderFunction(VertexShaderInput input) { VertexShaderOutput output; float4 worldPosition = mul(input.Position, World); float4 viewPosition = mul(worldPosition, View); output.Position = mul(viewPosition, Projection); output.TexUV = input.TexUV; output.Depth = output.Position.z; return output; } // Fade to black based on distance to FarClip float dist = saturate(input.Depth / FarClip); Dividing input.Depth by FarClip gives a value between 0.0 and 1.0, 1.0 being the result if the current pixel is at or beyond the FarClip distance. The saturate intrinsic function will make sure the value does not exceed 1.0. input.Depth FarClip FarClip As the desired effect is fading to black at the maximum distance each component is multiplied by 1.0 minus the result of our division. dist = 1.0f - dist; output.r *= dist; output.g *= dist; output.b *= dist; Without Depth Cueing (no fade): With Depth Cueing (fading to black at maximum distance): Collision detection can be very challenging, especially within a 3D environment. The mathematics can be mind-bending in some cases. There is almost always a trade-off between accuracy and efficiency of the calculation, and the balance must always be based on the context. Fortunately, in Celerity matters can be greatly simplified by the realisation that, although the game appears to be in 3 dimensions, it’s actually really only operating in 2 dimensions. The player's ship only ever either travels forward down the tunnel or around the outside of the tunnel. The ship never moves along the Y axis, only the Z and X axes. The ship travels down an infinitely long tunnel. Representing this literally, a computer would quickly run into floating point error problems as the magnitude of some variables will increase rapidly, leading to large differences in precision, in turn resulting in large errors in calculations. In short, things would break. Instead the ship and camera remain fixed, oriented around the origin. The tunnel itself is moved, towards the camera. To simplify the tunnel motion even further the tunnel sections are only advanced in the Z direction. This approach requires translating the tunnel through X and Y in order to centre it about the origin. It is also necessary to rotate the camera to point down the tunnel, to make it appear as though the player is looking down the tunnel. Tunnel and objects are first created straight with no curves Vertices are then perturbed to create the curves The important thing about this is that the front and backs of the obstacles remain parallel to the XY plane. This means that a complex 3D non-axis-aligned collision detection can be performed by an easy 2D axis-aligned collision detection. As the player only moves along 2 dimensions, in order to determine if a collision has taken place only 3 pieces of information are required: To visualise how the tunnel unwraps, imagine that the Celerity tunnel is a grid drawn on the inside of a toilet roll. Take a pair of scissors and cut along the roll so that it unfolds flat, showing you a flat grid: The tunnel surface, unwrapped to form the new 2D coordinate system The width of each obstacle can be calculated simply. As the obstacles are cubes the same size as each grid square in the tunnel wall, their width is equal to 2p/10. It’s 2p as we’re working in radians, with 10 being the number of sub-divisions in the tunnel. The Z coordinate is the same Z coordinate as used in the 3D representation of the tunnel. 2p/10 The CollisionRect class was created to hold collision data for each obstacle: CollisionRect class CollisionRect { // 0 -- 1 - -- + // | | | // 2 -- 3 + public Vector2[] points; public bool zUnset = true; // Angle and z are the centre point public CollisionRect(float tunnelCellSize, float tunnelNumSegments, float angle, float z) { float rads = (float)(2 * Math.PI); float widthOver2 = (float)Math.PI / tunnelNumSegments; float heightOver2 = tunnelCellSize / 2; points = new Vector2[4] { new Vector2(rads - angle - widthOver2, z - heightOver2), new Vector2(rads - angle + widthOver2, z - heightOver2), new Vector2(rads - angle - widthOver2, z + heightOver2), new Vector2(rads - angle + widthOver2, z + heightOver2) }; } public void SetZ(float z) { for(int i = 0; i < 4; i++) { points[i].Y += z; } this.zUnset = false; } } The class is fairly simple. There is an array of type Vector2 to hold the coordinates of each corner of the box, and a constructor which creates the box. Vector2 An important consideration when updating the positions of the collision boxes is to copy the Z coordinate from the 3D world position rather than calculating the new position. If a new position were to be calculated then minute differences in the numbers would accumulate and the positions would quickly become out of sync. A similar class is used to maintain the player’s position in the world. As there is no easy way to determine the angular size of the ship model, as the data is implicit and tucked away inside the .fbx model, the width and height were determined through trial and error. .fbx With all these elements in place collision detection becomes possible. In the 2D abstraction, this process is simple as the process is only concerned with Axis Aligned Bounding Boxes, or AABBs. 2 intersecting AABBs The algorithm for detecting intersection is as follows: For each point in the green box, if x > A.x and x < B.x and y > B.y and y < A.y then the point is inside the orange box. If any points are inside then they intersect, or "collide". x > A.x x < B.x y > B.y y < A.y Due to the earlier simplification of unwrapping the tunnel from a tube to a flat sheet, there are a couple of special cases to consider. The coordinates must wrap around. This is achieved by performing 2 detections on boxes that are on the join/seam, at positions 0 or 9 in a zero-based tunnel of 10 segments. One detection in the boxes' normal position and one transposed by ±2p depending on what side of the join the box is located. I used XACT, Microsoft's cross-platform audio library and toolset, to power Celerity's layered music and sound effects. It is both reasonably straight-forward and fairly powerful. XACT in this project, but even with the basics we have a dynamic music score. Here's a walkthrough of the AudioModule, the class used to handle audio logic in the game. Note the difference between Play (for one-shot SFX) and PlayCue (for looping song WAVs). AudioModule Play PlayCue To code with XACT you'll first need the following using statement: using using Microsoft.Xna.Framework.Audio; Now some simple instance members: // Startup logic bool hasMusicStarted = false; // XACT objects AudioEngine engine; WaveBank waveBank; SoundBank soundBank; // Channels AudioCategory musicChannel1; AudioCategory musicChannel2; AudioCategory musicChannel3; AudioCategory musicChannel4; AudioCategory ambienceChannel; AudioCategory sfxChannel; The bool is just a flag we can check to see if we've already started the music playing so we only do it once. The XACT objects contain most of the functionality, and the various AudioCategory objects represent the different channels. bool AudioCategory The Initialize method is self-explanatory, initialising the instance variables: public void Initialize() { // Init XACT objects engine = new AudioEngine(AudioLibrary.PathEngine); waveBank = new WaveBank(engine, AudioLibrary.PathWaveBank); soundBank = new SoundBank(engine, AudioLibrary.PathSoundBank); // Init channels musicChannel1 = engine.GetCategory(AudioLibrary.ChannelMusic1); musicChannel2 = engine.GetCategory(AudioLibrary.ChannelMusic2); musicChannel3 = engine.GetCategory(AudioLibrary.ChannelMusic3); musicChannel4 = engine.GetCategory(AudioLibrary.ChannelMusic4); ambienceChannel = engine.GetCategory(AudioLibrary.ChannelAmbience); sfxChannel = engine.GetCategory(AudioLibrary.ChannelSFX); } The Update method is a little more interesting: public void Update(float chaosFactor) { // All sounds will be multiplied by this allowing a global mute function float muteMultiplier = GlobalGameStates.MuteState == MuteState.Muted ? 0f : 1f; // Set looping music playing first time only if (!hasMusicStarted) { hasMusicStarted = true; if (CeleritySettings.PlayMusic) { soundBank.PlayCue(AudioLibrary.Music_Layer1); soundBank.PlayCue(AudioLibrary.Music_Layer2); soundBank.PlayCue(AudioLibrary.Music_Layer3); soundBank.PlayCue(AudioLibrary.Music_ShortIntro); soundBank.PlayCue(AudioLibrary.Ambience); } } // Set the volumes float normalVolume = 1f * muteMultiplier; ambienceChannel.SetVolume(normalVolume); musicChannel1.SetVolume(normalVolume); musicChannel2.SetVolume(DynamicVolume(chaosFactor, 0.3f) * muteMultiplier); musicChannel3.SetVolume(DynamicVolume(chaosFactor, 0.7f) * muteMultiplier); musicChannel4.SetVolume(normalVolume); sfxChannel.SetVolume(normalVolume); // Update the engine engine.Update(); } Here I multiply all volumes by a mute multiplier, allowing me to globally silence all channels at will. The next section is where the music is initially triggered with the PlayCue method. Then the volumes of the various channels are set, some dynamic to the level of in-game tension, known as the "Chaos Factor". Finally we call Update() on the AudioEngine object. Update() AudioEngine Here's the DynamicVolume helper method: DynamicVolume float DynamicVolume(float chaosFactor, float threshold) { if (threshold >= 1f) { throw new ArgumentException("Audio Module - Dynamic Volume: Threshold must be less than 1."); } float off = 0f; return chaosFactor > threshold ? (chaosFactor - threshold) / (1f - threshold) : off; } Next follows a number of publicly exposed individual PlayCue-based methods for different in-game sound effects, for example: public void PlayCrash() { soundBank.PlayCue(AudioLibrary.Ship_HitsBlock); } The Game Logic class is very simple. It provides a means of triggering and responding to game events, tracking timings and most importantly of all, managing the Chaos Factor, the abstract numeric value which represents the current global degree of tension. The Chaos Factor informs things such as the density at which blocks are generated, the speed of the player's ship and the complexity of the music. As it rises over time, the game becomes increasingly harder. This value is reset when the player crashes. The Chaos Factor is calculated as: public float ComputeChaos(double time) { return (float)(1.0 - (1.0 / Math.Exp(time / 20.0))); } It was not as straight-forward to access the sensors as I'd hoped. Another surprise in developing for Windows 8 was that the Sensor namespace was exclusive to WinRT, and therefore unavailable to Desktop applications. Thankfully Intel provided the answer. The trick was to open up the .csproj file with a text editor and simply add a target platform version number. This allows you to now add a reference to "Windows" from Visual Studio, which would otherwise be unavailable. Inside this library is the Windows.Devices.Sensors namespace. .csproj Windows.Devices.Sensors I had problems combining this directly with my XNA project, however simply putting the sensors in a separate project, which in turn referenced System.Runtime.WindowsRuntime.dll, allowed everything to build and inter-operate smoothly. I put any direct reference to any WinRT objects encapsulated within a proxy class, so my XNA project was only interacting with simple data types from the other project. System.Runtime.WindowsRuntime.dll. Whilst basic use of the library is fairly simple, this aspect of the program was not without its challenges. Performance of EMGUCV within XNA was initially terrible due to the basic single-threaded approach taken by XNA. Rather than get too complex, I chose to limit the polling rate and also place calls to my QueryCamera() method like this: Parallel.Invoke(() => QueryCamera(elapsedMilliseconds)); This worked really well for my desktop development machine but not so well on the Ultrabook™. The reason would appear to be the lack of drivers for the prototype Ultrabook™, as using a 3rd party webcam with drivers rather than the Ultrabook™'s own integrated device worked fine. Using a 3rd party webcam was impractical for the competition and the head tracking was a major selling point of our entry so I instead made a workaround. I offered 3 "modes" of operation, which were in effect 3 polling speeds for the camera; off, slow and fast. The Ultrabook™ could only handle frame requests coming in about 8 times per second, whereas the desktop's "fast" mode operated at a much smoother 30 requests per second. Here is the main method of interest in the CVModule. Don't be too alarmed by the formulae towards the end, they're just turning absolute rectangle positions into relative positions. All the tricky face detection itself is handled by the library in the DetectHaarCascade() call. CVModule DetectHaarCascade() void DetectFaces() { if (minFaceSize == null || minFaceSize.IsEmpty) { minFaceSize = new DR.Size(grayframe.Width / 8, grayframe.Height / 8); } // There's only one channel (greyscale), hence the zero index var faces = grayframe.DetectHaarCascade( haar, scaleFactor, minNeighbours, HAAR_DETECTION_TYPE.DO_ROUGH_SEARCH, minFaceSize )[0]; IsFaceDetected = faces.Any(); if (IsFaceDetected) { foreach (var face in faces) { if (isFirstFaceCapture) { // If first time then set entire history to current frame isFirstFaceCapture = false; currentEMA.Width = face.rect.Width; currentEMA.Height = face.rect.Height; previousEMA.Width = face.rect.Width; previousEMA.Height = face.rect.Height; } lastX = face.rect.X; lastY = face.rect.Y; lastWidth = face.rect.Width; lastHeight = face.rect.Height; // New smoothing stuff currentEMA.Width = (int)(alphaEMA * lastWidth + inverseAlphaEMA * previousEMA.Width); currentEMA.Height = (int)(alphaEMA * lastHeight + inverseAlphaEMA * previousEMA.Height); previousEMA.Width = currentEMA.Width; previousEMA.Height = currentEMA.Height; } } // Draw an ellipse round the face DR.PointF ellipseCenterPoint = new DR.PointF(lastX + lastWidth / 2.0f, lastY + lastHeight / 2.0f); DR.SizeF ellipseSize = new DR.SizeF(currentEMA.Width, currentEMA.Height); FaceEllipse = new Ellipse(ellipseCenterPoint, ellipseSize, 0); // Public stats FaceCentrePercentX = 1 - ellipseCenterPoint.X / (float)grayframe.Width; FaceCentrePercentY = ellipseCenterPoint.Y / (float)grayframe.Width; FaceSizePercentWidth = ellipseSize.Width / (float)grayframe.Width; FaceSizePercentHeight = ellipseSize.Height / (float)grayframe.Height; // Head Pos for feeding into world camera (range of -1f to 1f) HeadPos.X = -1f + (2f * FaceCentrePercentX); HeadPos.Y = -1f + (2f * FaceCentrePercentY); HeadPos.Z = -1f + (2f * FaceSizePercentHeight); } This step nearly prevented our submission. For those unfamiliar with creating installers, a fiddly and arcane world of scripting awaits. The slightest fault at this stage and your target store will reject your submission. If you have the time and patience I'd recommend those looking to publish an XNA game look into WiX, but I only had a few hours to produce the installer so opted for an expensive but simple solution, Advanced Installer professional. The beauty of it for XNA developers is that it understands what a dependency on XNA GS 4 is out of the box, so supporting XNA is as easy as checking a box. Here is a visual guide to some simple settings in Advanced Installer which worked for me: This form is very simple but don't forget to give your installer an icon on this screen: I believe Intel have changed their policy on requiring Silent Installs now, but use these settings to be on the safe side: One of the nice perks of having Advanced Installer is that you can simply hand it your certificate and tell it to sign the installer for you. I find this much simpler and quicker than using SignTool.exe via a command line. SignTool.exe This is the screen which made Advanced Installer worth its money for me. Here you tell it that the app is dependent on the user already having XNA GS 4 installed, and as a result it will automatically install it for them if they don't have it. The flip-side of the pre-requisites is preventing the app from installing if the user has an incompatible operating system. This is where you add the files and folders which you want installed on your target machine. This is usually just a dump of your Release folder. Also, you can add a shortcut to the application to put on the user's desktop. Release Since full blown XNA is desktop-only and won't work on WinRT, the Windows Store is not an option. Intel's AppUp store provides a good desktop alternative. The AppUp SDK provides options for license keys, upgrade mechanisms and all the goodies you'd expect. To limit the chances of Celerity being rejected just before the deadline I opted to keep things very simple and did not implement the SDK. Whilst the SDK is potentially very handy, nothing in Celerity relied on it. Whilst I won't advise on working with the SDK, here are a few tips for keeping the submission simple and upping your chances of acceptance: You need to test your installer on a completely fresh install of the target operating system(s). It's so easy to forget to tell the installer that the app requires the .NET Framework or something similar. These easy-to-make problems are also easy to catch, so don't be lazy and test the installer on a fresh install. If you have the software to do it, you can test in a VM. Test on a spare PC. Test on your friend's PC. Everywhere you can. Also, for hardware-dependent code make sure you test on the hardware. It's obvious, but so easy to skip. "Of course my gamepad code works! Look at it, it's so simple!". We caught ourselves thinking the same thing. A quick test revealed that the left and right were reversed on the DPad. Oops. The code looks fine with or without that little *-1, so test it with the actual hardware. *-1 The principle isn't just to make your program as good as possible. A small installer flaw which your users may tolerate might mean rejection from the store. In the Application Description and Keywords sections in the AppUp Submission pages you have a chance to expose your app in the store's search results. Describe your app accurately and succinctly, but also bear in mind how your users are going to find your app in the store. Your image is at stake every time you type something your user will see. Double check it, and have someone else check it. This goes for both store descriptions of your app, and any text in your app, too. Not only will this irritate your users and cause them to think less of you but many mistakes may lead to rejection from the store. Your app may have limited visuals, but make sure the screenshots give your users an indication of what the app does and how. They will most likely look at the screenshots and decide based on those whether they want to give up their time and or money to download your app. If the screenshot has virtually nothing on it they have no reason to take the gamble. AppUp apply a semi-transparent sheen to the image you provide to give all the store apps a consistent look. I didn't realise until it was too late, but if you have a mostly white background (as we do) the effect its lost slightly, and the look of your icon will suffer alongside vivid, colourful icons. Don't get me wrong, I love our current icon, but only with hindsight do I recognise the opportunity to play into the visual filtering which will take place later down the line. Worth considering. Be honest about your app. Should you really be charging in the top 5% of apps in the store? Does your app offer functionality and quality in the same league as Acid Music? If it's your first app consider giving it away. It's difficult to do when you've put your heart and soul into an app, but at the same time which would you prefer. A very limited number of sales and small income, or zero income but loads of people enjoying and talking about your app. You can use your first launch to test the water with an idea, for the vanity of it or perhaps to show people what you're capable of. It's not such a tragedy if you don't take any money for people enjoying your app. It goes without saying that the more operating systems you support and the more countries you offer then the more people stand to encounter your app. The flip side, is that I'll repeat you must test on every operating system you offer. I found filling in this section of the submission tremendously difficult. How do I, as a developer, know what Windows Experience Index numbers to attribute to my app? All I can offer as advice is start high, get your app accepted, and then expand outwards with future updates. When you get rejected you know you've gone too low. It worked for us! Not ideal, but what's a dev to do? If anyone has better advice on this issue please post a comment below as I'm genuinely interested.." This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Musician turned Software Engineer (turned professional around 6 years ago). Mainly interested in games & mobility. Sometimes I do real work, too. General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/523468/Celerity-How-it-was-all-done
CC-MAIN-2014-23
refinedweb
5,985
56.05
Form::Processor::Model::DBIC - Model class for Form Processor using DBIx::Class You need to create a form class, templates, and call F::P from a controller. Create a Form, subclassed from Form::Processor::Model::DBIC package MyApp:Form::User; use strict; use base 'Form::Processor::Model::DBIC'; # Associate this form with a DBIx::Class result class sub object_class { 'User' } # Where 'User' is the DBIC source_name # Define the fields that this form will operate on # Field names must be column or relationship names in your # DBIx::Class result class sub profile { return { fields => { name => { type => 'Text', label => 'Name:', required => 1, noupdate => 1, }, age => { type => 'PosInteger', label => 'Age:', required => 1, }, sex => { type => 'Select', label => 'Gender:', required => 1, }, birthdate => '+MyApp::Field::Date', # customized field class hobbies => { type => 'Multiple', size => 5, }, address => 'Text', city => 'Text', state => 'Select', }, dependency => [ ['address', 'city', 'state'], ], }; Then in your template: For an input field: <p> [% f = form.field('address') %] <label class="label" for="[% f.name %]">[% f.label || f.name %]</label> <input type="text" name="[% f.name %]" id="[% f.name %]"> </p> For a select list provide a relationship name as the field name, or provide an options_<field_name> subroutine in the form. (field attributes: sort_order, label_column, active_column). TT example: <p> [% f = form.field('sex') %] <label class="label" for="[% f.name %]">[% f.label || f.name %]</label> <select name="[% f.name %]"> [% FOR option IN f.options %] <option value="[% option.value %]" [% IF option.value == f.value %]selected="selected"[% END %]>[% option.label | html %]</option> [% END %] </select> </p> For a complex, widget-based TT setup, see the examples directory in the Catalyst::Plugin::Form::Processor CPAN download. Then in a Catalyst controller (with Catalyst::Controller::Form::Processor): package MyApp::Controller::User; use strict; use warnings; use base 'Catalyst::Controller::Form::Processor'; # Create or edit sub edit : Local { my ( $self, $c, $user_id ) = @_; $c->stash->{template} = 'user/edit.tt'; # Validate and insert/update database. Args = pk, form name return unless $self->update_from_form( $user_id, 'User' ); # Form validated. $c->stash->{user} = $c->stash->{form}->item; $c->res->redirect($c->uri_for('profile')); } With the Catalyst controller the schema is set from the model_name config options, ($c->model($model_name)...), but it can also be set by passing in the schema on "new", or setting with $form->schema($schema). You can also set a config values for whether or not to use FillInForm, and the form namespace. This DBIC model will save form fields automatically to the database, will retrieve selection lists from the database (with type => 'Select' and a fieldname containing a single relationship, or type => 'Multiple' and a many_to_many pseudo-relationship), and will save the selected values (one value for 'Select', multiple values in a mapping table for a 'Multiple' field). This package includes a working example using a SQLite database and a number of forms. The templates are straightforward and unoptimized to make it easier to see what they're doing. The schema method is primarily intended for non-Catalyst users, so that they can pass in their DBIx::Class schema object. my $validated = $form->update_from_form( $parameter_hash ); This is not the same as the routine called with $self->update_from_form. That is a Catalyst plugin routine that calls this one. This routine updates or creates the object from values in the form. All fields that refer to columns and have changed will be updated. Field names that are a single relationship will be updated. Any field names that are related to the class by "many_to_many" are assumed to have a mapping table and will be updated. Validation is run unless validation has already been run. ($form->clear might need to be called if the $form object stays in memory between requests.) The actual update is done in the update_model method. Your form class can override that method (but don't forget to call SUPER) if you wish to do additional database inserts or updates. This is useful when a single form updates multiple tables, or there are secondary tables to update. Returns false if form does not validate, otherwise returns 1. Very likely dies on database errors. The place to put validation that requires database-specific lookups. Subclass this method in your form. This is where the database row is updated. If you want to do some extra database processing (such as updating a related table) this is the method to subclass in your form. This routine allows the use of non-database (non-column, non-relationship) accessors in your result source class. It identifies form fields as 1) column, 2) relationship, 3) other. Column and other fields are processed and update is called on the row. Then relationships are processed. If the row doesn't exist (no primary key or row object was passed in), then a row is created using "create" and the fields identified as columns passed in a hashref, followed by "other" fields and relationships. This subroutine is only called for "auto" fields, defined like: return { auto_required => ['name', 'age', 'sex', 'birthdate'], auto_optional => ['hobbies', 'address', 'city', 'state'], }; Pass in a column and it will guess the field type and return it. Currently returns: DateTimeDMYHM - for a has_a relationship that isa DateTime Select - for a has_a relationship Multiple - for a has_many otherwise: DateTimeDMYHM - if the field ends in _time Text - otherwise Subclass this method to do your own field type assignment based on column types. This routine returns either an array or type string._order". The currently selected values in a Multiple list are grouped at the top (by the Multiple field class). This method returns a field's value (for $field->value) with either a scalar or an array ref from the object stored in $form->item. This method is not called if a method "init_value_$field_name" is found in the form class - that method is called instead. This allows overriding specific fields in your form class. For fields that are marked "unique", checks the database for uniqueness. arraryref: unique => ['user_id', 'username'] or hashref: unique => { username => 'That username is already taken', } This is called first time $form->item is called. If using the Catalyst plugin, it sets the DBIx::Class schema from the Catalyst context, and the model specified as the first part of the object_class in the form. If not using Catalyst, it uses the "schema" passed in on "new". It then does: return $self->resultset->find( $self->item_id ); It also validates that the item id matches /^\d+$/. Override this method in your form class (or form base class) if your ids do not match that pattern. If a database row for the item_id is not found, item_id will be set to undef. Initializes the DBIx::Class schema. User may override. Non-Catalyst users should pass schema in on new: $my_form_class->new(item_id => $id, schema => $schema) Returns a DBIx::Class::ResultSource object for this Result Class. This method returns a resultset from the "object_class" specified in the form, or from the foreign class that is retrieved from a relationship. These methods from Form::Processor are subclassed here to allow combining "required" and "optional" lists in one "fields" list, with "required" set like other field attributes. Form::Processor Form::Processor::Field Form::Processor::Model::CDBI Catalyst::Controller:Form::Processor Rose::Object Gerda Shank, gshank@cpan.org Based on Form::Processor::Model::CDBI written by Bill Moseley. This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/dist/Form-Processor-Model-DBIC/lib/Form/Processor/Model/DBIC.pm
CC-MAIN-2017-39
refinedweb
1,221
55.24
Followers of the series may also want to take a peek at Part XVII, covering management of the journal. Poettering: systemd for Administrators, Part XVIII (controllers) Posted Oct 24, 2012 14:57 UTC (Wed) by anatolik (subscriber, #73797) [Link] Posted Oct 24, 2012 19:07 UTC (Wed) by mjh (guest, #87431) [Link] Posted Oct 24, 2012 19:18 UTC (Wed) by Cyberax (✭ supporter ✭, #52523) [Link] Posted Oct 24, 2012 22:04 UTC (Wed) by rgmoore (✭ supporter ✭, #75) [Link] So you prefer it when developers just dump a bunch of code out there and don't bother to document it? I actually like it when a developer bothers to explain what their code does and how to use it. Posted Oct 24, 2012 22:35 UTC (Wed) by rahulsundaram (subscriber, #21946) [Link] Posted Oct 24, 2012 22:57 UTC (Wed) by dlang (✭ supporter ✭, #313) [Link] Posted Oct 24, 2012 23:30 UTC (Wed) by cry_regarder (subscriber, #50545) [Link] Posted Oct 24, 2012 23:46 UTC (Wed) by Cyberax (✭ supporter ✭, #52523) [Link] Should we stop doing all this unix-y crap and return to clean and pure world of AUTOEXEC.BAT and config.sys? Posted Oct 25, 2012 11:21 UTC (Thu) by k8to (subscriber, #15413) [Link] Posted Oct 25, 2012 12:15 UTC (Thu) by rahulsundaram (subscriber, #21946) [Link] Posted Oct 25, 2012 15:59 UTC (Thu) by Cyberax (✭ supporter ✭, #52523) [Link] SysV scripts were never simple. They are almost always brittle and unreliable pieces of crap. Especially cross-distribution scripts (LSB? Ha!). Posted Oct 25, 2012 18:26 UTC (Thu) by akeane (subscriber, #85436) [Link] Well spoken Mr Lang! To be fair though, I do like the Roman numerals, it gives a nice classical feel to the whole proceedings! akeane@superfrog-dev: man XVIII systemd No manual entry for XVIII No manual entry for systemd akeane@superfrog-dev: Ah, man; echo $? I pity the fool who uses systemd, and keep your new fangled Init "systems" AWAY from MR T's van and BINS! akeane@superfrog-dev: :-( Posted Oct 26, 2012 21:39 UTC (Fri) by jond (subscriber, #37669) [Link] Posted Oct 25, 2012 18:09 UTC (Thu) by akeane (subscriber, #85436) [Link] No, just writing "too much" code. Where "too much" is #defined as any... Posted Oct 25, 2012 0:16 UTC (Thu) by nix (subscriber, #2304) [Link] Posted Oct 25, 2012 15:39 UTC (Thu) by Kit (guest, #55925) [Link] Posted Oct 26, 2012 9:20 UTC (Fri) by jezuch (subscriber, #52988) [Link] "Install. It works." I'd also like every CPU to have a DWIM instruction. Posted Oct 26, 2012 21:10 UTC (Fri) by intgr (subscriber, #39733) [Link] I believe systemd actually comes the closest of all init systems. Many upstream packages already ship systemd units -- just "make install" and possibly "systemctl enable foo" required. Compared to SysV where your distro's package maintainer duplicated a shell script for each package, and assigned a "priority number" on an arbitrary scale to order service startup. It also replaces several other pieces that had to be manually configured before. As the article mentiones, systemd services share CPU time equally by default, not depending on the number of processes they have like before. And many more I can think of: Most systemd users probably don't even realize that it includes a readahead tool for speeding up system startup. It works without any hacks and configuration within LXC/namespace containers. If you want a serial console, you only need to configure it in one place (on the kernel command line). Instead of distros supplying acpid and a maintainer-written script for power button events, systemd has a simple built-in default policy -- so shutting down VMs from the host works out of the box. And many more that I can't remember right now. So, many things that seem like duct-taped together in other systems (usually by distro package maintainers), or things that required unnecessary amounts of fiddling and configuration -- now systemd does The Right Thing using a sensible built-in policy and provides straightforward configuration options. Posted Nov 2, 2012 14:53 UTC (Fri) by knobunc (subscriber, #4678) [Link] I have an external SATA drive that I use for backups. Occasionally I have need to do: > umount /backup > e2fsck /dev/sde1 However, the fsck fails because systemd has locked the device. I have tried systemd stop of various unit names, but have never found the right one to make systemd not hold a lock on the device. Posted Nov 2, 2012 15:22 UTC (Fri) by raven667 (subscriber, #5198) [Link] Posted Nov 2, 2012 15:45 UTC (Fri) by knobunc (subscriber, #4678) [Link] Posted Nov 2, 2012 16:45 UTC (Fri) by rahulsundaram (subscriber, #21946) [Link] Posted Oct 28, 2012 16:19 UTC (Sun) by nix (subscriber, #2304) [Link] Posted Oct 25, 2012 6:07 UTC (Thu) by davidstrauss (subscriber, #85867) [Link] Posted Oct 26, 2012 21:17 UTC (Fri) by JEFFREY (subscriber, #79095) [Link] Posted Oct 27, 2012 12:17 UTC (Sat) by akeane (subscriber, #85436) [Link] Sir, my apologies, but it is imperative that I correct you in your above assertion: It should be: The XXII installment of Lennart Poettering's "How to dismiss UNIX's core values and philosophy, and ruin it for everyone" Other than that, I believe a "HIGH FIVE" is in order! Posted Oct 27, 2012 15:44 UTC (Sat) by raven667 (subscriber, #5198) [Link] To be serious for a second though, UNIX is a computer operating system, not philosophy. If you let your preconceived ideas prevent you from making practical, rational decisions then you are going to be less successful at your goals, running software, than someone who is self critical and isn't locked in a culture of dogma. Making the system work technically better, IMHO, isn't "ruining" it just because it's a little different. Posted Oct 29, 2012 16:28 UTC (Mon) by akeane (subscriber, #85436) [Link] Let's be serious, and, hence quite, quite boring for III+ seconds... UNIX is an implementation of a philosophy; that rascal ESR even wrote a book a bit about it, and he's got guns! >If you let your preconceived ideas prevent you from making practical, rational decisions Well, they are "preconceived" (google translation:(well thought out)), because a lot of very clever people, thought about them way before you and I, and you know what? I respect that, do you really want to discard that knowledge and learning for something else just cause it's new? There's like, OMG! a billion Android devices out there right now, not including all the other embedded linux devices out there, just ticking away nice and reliably, they just work. Not a bad philosophy, I reckon! Posted Oct 29, 2012 17:06 UTC (Mon) by raven667 (subscriber, #5198) [Link] Posted Oct 29, 2012 17:26 UTC (Mon) by anselm (subscriber, #2796) [Link] I respect that, do you really want to discard that knowledge and learning for something else just cause it's new? People don't go for systemd because it is new. They go for systemd because in many respects it works better than what was used before. It is funny how most of the arguments the SysV-init proponents use against systemd today (it is too complicated, it solves problems that don't exist, the existing solutions are powerful enough, …) might have been used against SysV init when that was new in the 1980s. The only argument against systemd that would not have applied to SysV init at the time seems to be »it was written by Lennart Poettering«. Posted Oct 29, 2012 17:49 UTC (Mon) by Cyberax (✭ supporter ✭, #52523) [Link] And you might note, that these Android devices got rid of most of that UNIX stuff you're talking about. X11 - gone, UNIX service infrastructure - gone, shell-based design - gone, etc. Posted Oct 29, 2012 19:58 UTC (Mon) by raven667 (subscriber, #5198) [Link] Posted Oct 28, 2012 18:25 UTC (Sun) by rgmoore (✭ supporter ✭, #75) [Link] Linux is a registered trademark of Linus Torvalds
http://lwn.net/Articles/520929/
CC-MAIN-2013-20
refinedweb
1,347
62.01
Sorry, but there are conditions which sending data from the Nextion where this will fail. Not every 0xFF is a byte belonging to a data terminator sequence. I'll try and expand on this rather than a simple sorry. At some point your program will need to expand from your base above. The moment you use sendCommand to send back to the Nextion, incoming bytes are moved to the buffer for function NexLoop. These bytes of course now read from serial are not present in loop - so that is possibly a missed command or data. Your 0xFF counter is based on 3rd 0xFF encountered - but Nextion isn't based on every 3rd occurrence of 0xFF - Nextion termination is based on three 0xFFs running consecutively. - getting a number such as white in a 0x71 return will contain 5 0xFFs Hi Patrick, You are right, I do get sometimes errors. And indeed, checking for the 3rd 0xFF is a risk... It is a brute way and some workarrounds/limitations will be needed (thanks for noticing the problem 'white') . It is a base, which in my case works ok, but I hope somebody will further optimize ( the compactness is a pro) Agreed, indeed! compactness is desired. My point is you are on the right path, attempting to better existing - many such considerations are required - now with such in mind, you get further than you originally thought. @Karl Lambrechts It may also be a good idea to use an input buffer, because you don't know if your microcontroller receives all bytes inside the same loop. You will find some explanations on these two websites: Karl Lambrechts Hi guys, this is a really short and easy way to retreive the button data, absolutely interesting if you have many buttons. Succes! /*nextion brute shortcut to data that matters! * I slimmed and optimized this code for 2560 Mega board, with thanks to Gideon Rossouwv, * * (for arduino Uno) * Just tested for buttons, but much shorter than the Itead Library (fe. my 21 key keypad) * Works with nearly every HMI file, if it has buttons */ #include "Nextion.h"// needed for sendCommand int numBytes, endBytes; byte inByte, pageNum, buttonNum; void setup() { endBytes = 0; //initialise counter variables pageNum, buttonNum = 255;//initialise page number. It is unlikely that you'll have 255 pages. Serial.begin(9600); //open the serial port while (!Serial) { // wait for serial port to connect. Needed for native USB port only; } Serial.println("Serial On"); Serial2.begin(9600); // set the data rate for the SoftwareSerial port sendCommand("page 0");// to page 0 of nextion LCD sendCommand("dim=100");// intensity LCD=100% } void loop() { // The loop will determine which page and which button was tapped. if (Serial2.available()) {//Is data coming from the Nextion? inByte = Serial2.read(); //Serial.print(" inByte=");Serial.print(inByte); if (inByte > -1 && inByte < 255) { //The component ID message mostly consists of between 0 and 255 numBytes = numBytes + 1; //Keep track of the number of data bits received. } if (inByte == 255) {//Is it an end byte? endBytes = endBytes + 1;//Increment the number of end bytes } if (numBytes == 2) {//The second data bit is always the pageID in "Send component ID" pageNum = inByte; Serial.print(" pageID=");Serial.print(pageNum); } if (numBytes == 3) {//The 3rd data bit is always the buttonID in "Send component ID" buttonNum = inByte; Serial.print(" buttonID=");Serial.print(buttonNum); } if (inByte == 255 && endBytes == 3) { //Has the entire message been received. endBytes = 0;//Re-initialise counter variables numBytes = 0; Serial.println(); } } }
http://support.iteadstudio.com/support/discussions/topics/11000010939
CC-MAIN-2018-39
refinedweb
576
62.78
python how word - Fastest way to check if a value exist in a list As stated by others, in can be very slow for large lists. Here are some comparisons of the performances for in, set and bisect. Note the time (in second) is in log scale. Code for testing: import random import bisect import matplotlib.pyplot as plt import math import time def method_in(a,b,c): start_time = time.time() for i,x in enumerate(a): if x in b: c[i] = 1 return(time.time()-start_time) def method_set_in(a,b,c): start_time = time.time() s = set(b) for i,x in enumerate(a): if x in s: c[i] = 1 return(time.time()-start_time) def method_bisect(a,b,c): start_time = time.time() b.sort() for i,x in enumerate(a): index = bisect.bisect_left(b,x) if index < len(a): if x == b[index]: c[i] = 1 return(time.time()-start_time) def profile(): time_method_in = [] time_method_set_in = [] time_method_bisect = [] Nls = [x for x in range(1000,20000,1000)] for N in Nls: a = [x for x in range(0,N)] random.shuffle(a) b = [x for x in range(0,N)] random.shuffle(b) c = [0 for x in range(0,N)] time_method_in.append(math.log(method_in(a,b,c))) time_method_set_in.append(math.log(method_set_in(a,b,c))) time_method_bisect.append(math.log(method_bisect(a,b,c))) plt.plot(Nls,time_method_in,marker='o',color='r',linestyle='-',label='in') plt.plot(Nls,time_method_set_in,marker='o',color='b',linestyle='-',label='set') plt.plot(Nls,time_method_bisect,marker='o',color='g',linestyle='-',label='bisect') plt.xlabel('list size', fontsize=18) plt.ylabel('log(time)', fontsize=18) plt.legend(loc = 'upper left') plt.show() I'm searching for the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is? I know that all values in the list are unique like my example. The first method I try is (3.8sec in my real code): a = [4,2,3,1,5,6] if a.count(7) == 1: b=a.index(7) "Do something with variable b" The second method I try is (2x faster:1.9sec on my real code): a = [4,2,3,1,5,6] try: b=a.index(7) except ValueError: "Do nothing" else: "Do something with variable b" Proposed methods from user (2.74sec on my real code): a = [4,2,3,1,5,6] if 7 in a: a.index(7) In my real code, first method takes 3.81sec and the second method takes 1.88sec. It's a good improvement but: I'm a beginner with Python/scripting and I want to know if a fastest way exists to do the same things and save more process time? More specific explication for my application: In the API of blender a can access to a list of particles: particles = [1,2,3,4...etc.] From there, I can access to its location: particles[x].location = [x,y,z] And I test for each particle if a neighbour exists by searching in the location of each particle like: if [x+1,y,z] in particles.location "find the identity of this neighbour particles in x:the index of the particles array" particles.index([x+1,y,z]) You could put your items into a set. Set lookups are very efficient. Try: s = set(a) if 7 in s: # do stuff edit In a comment you say that you'd like to get the index of the element. Unfortunately, sets have no notion of element position. An alternative is to pre-sort your list and then use binary search every time you need to find an element. It sounds like your application might gain advantage from the use of a Bloom Filter data structure. In short, a bloom filter look-up can tell you very quickly if a value is DEFINITELY NOT present in a set. Otherwise, you can do a slower look-up to get the index of a value that POSSIBLY MIGHT BE in the list. So if your application tends to get the "not found" result much more often then the "found" result, you might see a speed up by adding a Bloom Filter. For details, Wikipedia provides a good overview of how Bloom Filters work, and a web search for "python bloom filter library" will provide at least a couple useful implementations. this is not the code, but the algorithm for very fast searching if your list and the value you are looking for are all numbers, this is pretty straightforward, if strings: look at the bottom: - -let "n" be the length of your list - -optional step: if you need the index of the element: add a second column to the list with current index of elements (0 to n-1) - see later - order your list or a copy of it (.sort()) - loop through: - compare your number to the n/2th element of the list - if larger, loop again between indexes n/2-n - if smaller, loop again between indexes 0-n/2 - if the same: you found it - keep narrowing the list until you have found it or only have 2 numbers (below and above the one you are looking for) - this will find any element in at most 19 steps for a list of 1.000.000 (log(2)n to be precise) if you also need the original position of your number, look for it in the second, index column if your list is not made of numbers, the method still works and will be fastest, but you may need to define a function which can compare/order strings of course this needs the investment of the sorted() method, but if you keep reusing the same list for checking, it may be worth it present = False searchItem = 'd' myList = ['a', 'b', 'c', 'd', 'e'] if searchItem in myList: present = True print('present = ', present) else: print('present = ', present) Or use __contains__: sequence.__contains__(value) Demo: >>> l=[1,2,3] >>> l.__contains__(3) True >>>
http://code.i-harness.com/en/q/7388b3
CC-MAIN-2019-09
refinedweb
1,008
62.27
This class implements LSQR. More... #include <ClpLsqr.hpp> This class implements LSQR. LSQR solves Ax = b or min ||b - Ax||_2 if damp = 0, or min || (b) - ( A )x || otherwise. || (0) (damp I) ||2 A is an m by n matrix defined by user provided routines matVecMult(mode, y, x) which performs the matrix-vector operations where y and x are references or pointers to CoinDenseVector objects. If mode = 1, matVecMult must return y = Ax without altering x. If mode = 2, matVecMult must return y = A'x without altering x. ----------------------------------------------------------------------- LSQR uses an iterative (conjugate-gradient-like) method. For further information, see 1. C. C. Paige and M. A. Saunders (1982a). LSQR: An algorithm for sparse linear equations and sparse least squares, ACM TOMS 8(1), 43-71. 2. C. C. Paige and M. A. Saunders (1982b). Algorithm 583. LSQR: Sparse linear equations and least squares problems, ACM TOMS 8(2), 195-209. 3. M. A. Saunders (1995). Solution of sparse rectangular systems using LSQR and CRAIG, BIT 35, 588-604. Input parameters: atol, btol are stopping tolerances. If both are 1.0e-9 (say), the final residual norm should be accurate to about 9 digits. (The final x will usually have fewer correct digits, depending on cond(A) and the size of damp.) conlim is also a stopping tolerance. lsqr terminates if an estimate of cond(A) exceeds conlim. For compatible systems Ax = b, conlim could be as large as 1.0e+12 (say). For least-squares problems, conlim should be less than 1.0e+8. Maximum precision can be obtained by setting atol = btol = conlim = zero, but the number of iterations may then be excessive. itnlim is an explicit limit on iterations (for safety). show = 1 gives an iteration log, show = 0 suppresses output. info is a structure special to pdco.m, used to test if was small enough, and continuing if necessary with smaller atol. Output parameters: x is the final solution. *istop gives the reason for termination. *istop = 1 means x is an approximate solution to Ax = b. = 2 means x approximately solves the least-squares problem. rnorm = norm(r) if damp = 0, where r = b - Ax, = sqrt( norm(r)**2 + damp**2 * norm(x)**2 ) otherwise. xnorm = norm(x). var estimates diag( inv(A'A) ). Omitted in this special version. outfo is a structure special to pdco.m, returning information about whether atol had to be reduced. Other potential output parameters: anorm, acond, arnorm, xnorm Definition at line 76 of file ClpLsqr.hpp. Default constructor. Constructor for use with Pdco model (note modified for pdco!!!!) Copy constructor. Destructor. Assignment operator. This copies the data. Set an int parameter. Call the Lsqr algorithm. Matrix-vector multiply - implemented by user. diag1 - we just borrow as it is part of a CoinDenseVector<double> Definition at line 125 of file ClpLsqr.hpp. Row dimension of matrix. Definition at line 86 of file ClpLsqr.hpp. Column dimension of matrix. Definition at line 88 of file ClpLsqr.hpp. Pointer to Model object for this instance. Definition at line 90 of file ClpLsqr.hpp. Diagonal array 1. Definition at line 92 of file ClpLsqr.hpp. Constant diagonal 2. Definition at line 94 of file ClpLsqr.hpp.
https://www.coin-or.org/Doxygen/Clp/classClpLsqr.html
CC-MAIN-2017-04
refinedweb
534
61.83
Opened 7 years ago Closed 7 years ago Last modified 13 months ago #13088 closed New feature (wontfix) Template range filter Description (last modified by ) def range( value ): """ Filter - returns a list containing range made from given value Usage (in template): <ul>{% for i in 3|range %} <li>{{ i }}. Do something</li> {% endfor %}</ul> Results with the HTML: <ul> <li>0. Do something</li> <li>1. Do something</li> <li>2. Do something</li> </ul> Instead of 3 one may use the variable set in the views """ return range( value ) Change History (2) comment:1 Changed 7 years ago by comment:2 Changed 13 months ago by Note: See TracTickets for help on using tickets. My impression of this idea is that it is trying to lead to programming in the template. If you have a list of options that need to be rendered, they should be computed in the view, not in the template. If that's as simple as a range of values, then so be it.
https://code.djangoproject.com/ticket/13088
CC-MAIN-2017-17
refinedweb
169
76.76
Technical Debt: A Definition A detailed explanation of what technical debt is and isn't. Join the DZone community and get the full member experience.Join For Free. He’s certainly right about that! But just prior to that, he says, “Technical debt doesn’t exist”, and sort of wanders around that idea for a bit. Here’s the rub: he then tries to define what technical debt actually is: - “Maintenance work.” - “Features of the codebase that resist change.” - “Operability choices that resist change.” - “Code choices that suck the will to live.” - “Dependencies that resist upgrading.” I’ll leave you to read his descriptions of each. Critique Unfortunately, a lot of the definitions he raises there are highly subjective and extremely difficult to understand, except at a base, emotional, almost visceral level. I mean, when you explicitly use the phrase “suck the will to live” as one of your definitions, it’s hard to really put a concrete discussion around that. Consider, for example, that particular point: “A significant percentage of what gets referred to as technical debt are the decisions that don’t so much discourage change but rather discourage us from even wanting to look at the code. ….” I’m sure every single person reading this has an immediate reaction, akin to the screams through the Force that Obi-Wan felt when Alderaan was destroyed. Everybody remembers That One Project, or That One Class, or That One File…. Nobody wanted to touch it, it was a mess, and people would look for every reason under the sun to avoid opening it, as if there was some kind of icky black ichor that could ooze out of the screen and keyboard and infect us with its ugliness. And yet, if we compare the stories, we will all have very different concrete-terms descriptions of what that thing was. And I’ll even bet that if you cast the net wide enough, and we spend enough time comparing stories, we’ll even find that one man’s “suck the will to live” is another man’s “Whoa, man, that’s actually kind of a cool hack.” Case in point: in the earliest days of my career, I was a contractor working on some C/Win16 code at Intuit. A really cool 3-month gig (and in those days, it was way cool to have Intuit on your resume). I was working as part of the “Slickrock” team, which was the code-name for Intuit’s nascent electronic banking section of Quicken 5 for Windows. It was some cool stuff. Except... Well, first of all, everything was written in C. Not C++, as was the leading-edge of the day, but using Intuit’s home-grown C/Windows library that they’d put together since the earliest days of the product. At the time, I was kinda bleah on the whole idea. (In retrospect, hey, if it still works, you know?) And there was this one dialog box to which I was assigned, which had a bunch of bugs in it that needed fixing, that nobody else on the team wanted to touch. Eager to prove to all these grizzled veterans that I was capable of handling the toughest stuff, I leapt at the chance to get into this thing. (If you get this picture of the eager young Private fresh from boot camp, volunteering to go out on that mission that the grizzled old Sargeant knows will just crush the life out of him, you’re probably not too far off the mark.) And here’s what I found: this dialog box code was one, giant, four-page-long function, where three-and-three-quarters of it was wrapped in one giant-ass do-while loop. But not just any do-whileloop; no, this one was the most bizarre thing I’d ever seen. It looked something like this: do { /* do one thing */ /* do another thing */ /* check that thing */ /* what about the thing over there */ } while (0); It was my own private “WTF?!?” moment. No wonder everybody wanted to stay clear of this thing! This was the craziest code I’d ever seen, and clearly it was because they weren’t using C++! (Yeah, I kinda was that stupid back then.) But when I showed this to one of the other engineers and said the 90’s equivalent of “Dude, seriously?”, he pointed out that I’d missed an important part of the whole thing: int result = -1; /* Not OK! */ do { /* do one thing */ if (!thing-worked) break; /* do another thing */ if (!another-thing-worked) break; /* check that thing */ if (!thing-checked) break; /* what about the thing over there */ if (!thing-over-there-checked) break; result = 0; /* OK! */ } while (0); return result; In other words, this incredibly idiotic thing actually served a useful purpose: it obeyed the old C rule of “single entry, single exit”, and more importantly, it was rather elegantly obeying the fail-fast principle. (Why bother doing all these other checks if you’ve already failed at the first step?) Now, I grant you, this could’ve been solved using C++ using exceptions; instead of the (not-really-a-)loop, he could just have done a “try”, and then each step could’ve thrown their own new exception type, and there’d have been either a single “catch” to return the appropriate error code (since this block was returning either -1 or 0, depending on success), or even maybe a separate “catch” block to handle each different error condition, and— But you know what? Today, looking back at it, I don’t know if that would’ve been much clearer, or much shorter, or what-have-you. Is this still life-sucking-code? Or is this an elegant hack? I’ll be honest, I’m not sure anymore, of either position. Technical Debt: A Definition I don’t have one. Seriously. Not one I particularly like, anyway. Google it, and you get: Technical debt (also known as design debt or code debt) is a metaphor referring to the eventual consequences of any system design, software architecture or software development within a codebase. “...eventual consequences”? You mean, like “it works”? Seriously, consequences are not always bad, which is why the Gang-of-Four used that same word to describe the results of a particular solution applied to a particular problem within a certain context. Consequences can be positive, and they can also be negative. The use of the Strategy pattern can allow for varying an algorithm at runtime—but with it comes an added cost in complexity of determining which Strategy to load, for example, or the additional cognitive load of having to realize that now the Strategy being executed may be nowhere local to the code actually executing it (which would at some level seem to violate the principle of locality, depending on the situation). Wikipedia goes on to say: The debt can be thought of as work that needs to be done before a particular job can be considered complete or proper. Now that’s interesting, because that certainly doesn’t jibe with what @kellan was alluding to earlier—this sounds like things like documentation and tests and such. And yes, that definitely could create a problem, if a company/team/programmer goes off and writes a whole bunch of untested, undocumented code; I’d call that indebted code, probably, sure. Unless, you know, it doesn’t really need documentation. Or tests. Like, for example, a module composed of much smaller functions, each of which are effectively small primitives that really don’t need testing, a la: def calcuate(lhn, op, rhn) return op(lhn, rhg) end def add(lhn, rhn) return lhn + rhn end def sub(lhn, rhn) return lhn - rhn end puts calculate(1, add, 2) Do these really require comments? Tests? Wouldn’t it actually add to the technical debt to put those into place, since now they must be maintained and kept up to date should something change in here? I’m obviously reaching here, but I don’t think the point is entirely invalidated by the simplicity of my example—after all, well-written methods are supposed to be small and focused, and we prefer classes not to be large, and so on, for precisely these kinds of reasons. Technical Debt: It’s a Metaphor, Stupid Go back to Wikipedia for a second; there, they finish the definition’s first paragraph with this: If the debt is not repaid, then it will keep on accumulating interest, making it hard to implement changes later on. Unaddressed technical debt increases software entropy. See, this is the heart of the matter: technical debt is a metaphor. That’s it. That’s all it is. It’s a literary mechanism designed to help people who are not programmers understand that there are decisions made during the development process of a project, decisions which are deliberate choices to take a shortcut or avoid a more generic solution in the interests of getting past the obstacle quickly. Except that nothing ever remains “just” a metaphor in our industry. Inevitably, we have to dissect it, treat as if it were a real, in-the-room-with-us kind of thing, and start crusades “for” or “against” it. Because REASONS. And I admit, I’m not immune to this tendency myself. Because in examining a metaphor, so long as we recognize it’s a metaphor and therefore bound to fail at some point (the model is not reality), we can actually find some interesting edge-cases that may or may not apply, and that leads us to some interesting conversations about the concept, even if it doesn’t fit the metaphor anymore. Technical Debt: A Fowlerian Definition Martin Fowler has gone into great detail about the different kinds of technical debt in the form of a debt quadrant, arranged along two axes of “Deliberate vs Inadvertent” against “Reckless vs Prudent”. I like this, simply by virtue of the fact that it captures the mindset of the developer or the team at the time they were making that decision. But I don’t like it because, well, because who cares what they were thinking, or why? Isn’t technical debt just technical debt? I mean, that $50 purchase on your credit card, was it a measured and thoughtful purchase, perhaps some tools at the local hardware store, so that you can perform some home repais, or was it a reckless and idiotic purchase, perhaps some tools at the local hardware store, so that you can pretend to yourself that you’re actually going to take this weekend and perform some home repairs, but deep down you know you’re just fooling yourself, you’ll never get it done, and the tools will now be left to rust in a quiet corner of the garage (or worse, you’ll leave them out in the backyard and it rains and and and)? Seriously: the guy who wrote that do-while loop at Intuit? I have no idea what he was thinking—and did that intent really make a helluvalot of difference to me (or the rest of the team) as I (we) tried to pick it up and extend/modify/debug it? I won’t speak for the rest of the team, but to me, it made not a single whit of difference. But here’s the vastly more important thing to realize about debt: At the end of the day, you still owe $50. Wherever that debt appears on Fowler’s quadrant, you still have to pay it off. Or it will gather interest, and eventually (if you leave it long enough) bankrupt you. Granted, this is perhaps where that metaphor starts to wear a little thin. In a codebase, where we perhaps deliberately chose not to use a Strategy pattern, but instead just coded the algorithm by hand directly into the code, because we don’t really see any need for any greater degree of flexibility, we have potentially amassed some (perhaps small) amount of technical debt. The $50 hammer, if you will. In a traditional credit card scenario, that $50, compounded at 5% or 10% interest, will, without exception, eventually turn into a monstrous pile of debt that you cannot pay off, assuming you leave it unpaid for that long. But that non-Strategized algorithm? So long as the client requirements don’t change, there’s not a thing wrong with it. It can continue to run, and run, and run, until the heat death of the universe, and nothing happens. This suggests to me that technical debt isn’t just about what the developers on the team at the time were thinking about. This suggests that technical debt has two more components to it: - The thoughts of the developer(s) who have now inherited the code. - The requirements (or lack thereof) of the project for which the code was written. See, if the client never changes their requirements, there is no technical debt. So long as the code continues to run, without problem, then what the code looks like is entirely irrelevant. It’s only when the client says, “OK, now we need to do this other thing with this codebase” that it becomes a problem. Although, now that I write this, I realize that’s not entirely accurate, either. If the client’s requirements haven’t changed, but the code doesn’t run, or runs into errors while running? Those are bugs, and the code needs to change (to remove the bug). And that’s the other case where now, a developer struggling to understand the code in which the bug may (or may not) live will be running into difficulty. Enter technical debt again. Which now suggests that technical debt is essentially “a developer’s cognitive difficulty in understanding and/or modifying a codebase”. Nothing to do with the decisions made at the time of the codebase’s creation, and everything to do with the developer who is attempting to understand what the code is trying to do or how to modify it. Technical Debt: Moving On So does @kellan (and Peter Norvig) have it right, that “code is a liability”? On the surface of it, maybe: if I write code, it is potential technical debt. See, it’s not technical debt yet, because it won’t actually be a debt until we trigger the “understanding and/or modifying” clause of the above. The Ruby script I hacked together to transform my old blog’s XML over to Markdown files for the new system, I won’t know whether that code is technical debt until I (or anybody else who wants to use or modify it) go back into it again and face the cognitive load of understanding it or modifying it. So it’s like the infamous cat in the box, neither debt nor not, until the box is opened. Published at DZone with permission of Ted Neward, DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/technical-debt-a-definition-1
CC-MAIN-2021-04
refinedweb
2,518
66.78
Interquartile Mean pure-Python module Project description python-iqm Interquartile Mean pure-Python module. It contains two classes: - DictIQM - MovingIQM DictIQM This class is efficient for datasets in which many numbers are repeated. It should not be used for large datasets with a uniform distribution. The trade-off between accuracy and memory usage can be manged with its round_digits argument. Usage from iqm import DictIQM import sys diqm = DictIQM(round_digits=-1, tenth_precise=True) for line in open("source1_numbers_list.txt", "r"): diqm("source1", line) print "# {:12,.2f} Dict IQM".format(diqm.report("source1")) MovingIQM This class sacrifices accuracy for speed and low memory usage. Usage from iqm import MovingIQM import sys miqm = MovingIQM(1000) for line in open("source1_numbers_list.txt", "r"): miqm("source1", line) print "# {:12,.2f} Moving IQM".format(miqm.report("source1")) License See LICENSE.txt (MIT License). Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages. Source Distribution python-iqm-0.2.1.tar.gz (4.4 kB view hashes)
https://pypi.org/project/python-iqm/
CC-MAIN-2022-05
refinedweb
175
62.95
The cache management we have with ObjectAdapter, might be simplified such that we just work with java.lang.Object so far as possible. We would have a "disposable" ObjectAdapter that we instantiate around an Object whenever we need it - to access into the metamodel - and then throw it away after. Or perhaps eventually we might not need ObjectAdapter at all, just simply use #getClass() to look up the ObjectSpecification. ~~~ The main objective is to get rid of these two maps: and As their name suggests, these map: oid -> adapter (look up an adapter from an oid) pojo -> adapter (look up an adapter from a pojo) The adapter itself has a reference to its oid (getOid()) and to its pojo (getObject()). Most, though not all, objects have Oids. Certainly DN persistent objects do, in fact they do even if they are not yet persisted (prior to calling RepositoryService#persist(...). These will have a RootOid, which will indicate if the object is persistent or still transient. The same is true of view models, these also have a RootOid. They also have a RecreatableObjectFacet which is used to actually manufacture the Oid (because the oid for view models is basically a serialization of the state of the domain object). The RootOid for view models will indicate that they are view models. Values (ints, strings etc), do NOT have an oid. This also means that - obviously - they don't get saved in the OidAdapterHashMap; and they probably aren't saved in PojoAdapterHashMap. Value objects will have a ValueFacet. There's one other subtype of Oid (apart from RootOid), namely ParentedCollectionOid. That's because the Set or List that holds "child" objects is also managed as an adapter; ie: public class Order { @Getter @Setter Set<OrderItem> orderItems = Sets.newTreeSet(); ... } Why is this done? Because a long time ago (before DN) the framework did its own persistence, so this was for lazy loading etc. The "ensureMapsConsistent" method in PersistenceSessionXxx is there to ensure that these are maintained correctly; it's rather paranoid because if these get out of sync, then bad things would happen; eg: There's also some rather horrible "remapRecreatedPojo" methods that hack this stuff All this stuff is a legacy from the original client/server architecture that the framework used to have; it was probably needed then but I really don't think it's needed now. ~~~ At the moment the object adapters are created eagerly, typically using PersistenceSession#adapterFor(...). For domain services, we eagerly create an adapter around every service before each session, "just in case" it gets interacted with. This could be removed This also requires the ability to infer the Oid from the pojo, on the fly. There are two different ways this is done: - for DN entities, there is the JdoObjectIdSerlaizer - for view models, there's RecreatableObjectFacet, already mentioned. Ideally the code to recreate/rehydrate the object should define a consistent API to the rest of the framework. My thinking is that it could perhaps be a pluggable service so that we can then support other persistence runtime stores ... The idea is that the framework encounters a pojo and then asks for a service (via an SPI) to see which can extract/infer an Oid from it, using the usual chain-of-responsibility pattern. Out-of-the-box the framework would provide two default implementations, one for DN entities (JdoIdHelper), the other for view models. ~~~~~~ Looking forward, ideally, PersistenceSession shouldn't need to use ObjectAdapter at all; the ObjectAdapter really exists only for the viewer(s) etc to obtain the ObjectSpecification to know how to render the object. Ultimately, we could get rid of ObjectAdapter completely and just uses pojos (=domain objects) everywhere. ObjectSpecification would remain, though. I think this is for other tickets, though, not this one. ~~~~~~ OK, hopefully some the above makes sense!!! - is related to - - relates to - - links to - - mentioned in -
https://issues.apache.org/jira/browse/ISIS-1976
CC-MAIN-2020-29
refinedweb
645
60.85
As you settle into tax season, you may not be shocked to hear that the Internal Revenue Service has about 800 different forms. For some of them, the instructions literally state that to determine whether you need to fill out the form, you first need to fill out the form. Each form is interlinked with many others, so that you can work your way down a form only to be halted in your tracks by a line demanding that you fill out three other forms first and then bring the results back to this one; and each of those three can send you down other wormholes, so that your desktop is littered with dozens of open and partially filled-out documents. By the time you make it back to the original document, you’ve usually forgotten what it was about. It’s no wonder that an entire tax-preparation industry has arisen in the United States, but the real madness is that, for tens of millions of Americans, none of this is necessary. For many taxpayers, the government already has the information that you “provide” to it on your tax forms: Employers send wage information to the Internal Revenue Service, and financial institutions send information about financial accounts. Why tell the government what it already knows? To borrow an analogy from the tax scholar Joseph Bankman: Imagine if, instead of sending you a statement in the mail, your bank required you to keep all your receipts and fill out forms about what you bought. But in the United States, filing taxes is painful by design. The tax-collection system as we know it is the outcome of three forces: corporate lobbying, a stubborn resistance to borrowing good ideas from other Western nations, and the Republican Party’s decades-long campaign against taxation itself. Mark Mazur: Taxpayers are very confused. In Denmark and Spain, the proportion who ask for their returns to be adjusted is less than a quarter, and in Sweden, 72 percent of taxpayers say filing taxes is easy. Nothing is keeping the United States from copying these countries. More than two-thirds of American households do not itemize their returns—and estimates are that after the 2017 tax law, which raised the standard deduction, this number will rise to 90 percent. So on both the income side and the deductions side, the calculations are straightforward for the government. Some scholars suggest that for perhaps 40 percent of taxpayers—those who receive income from only one source, have only one bank account, and do not itemize—the government could simply calculate what is owed. There will always be some taxpayers with complicated financial situations and a large number of deductions, and some whose situations have changed since their last return (for example, because of the birth of a child). And there will always be some who simply prefer to do their own taxes. But since it’s lower- and middle-income Americans who have the least complicated financial situations, and higher earners who have the most complicated situations, making tax returns easier to file would be a progressive reform. Read: The golden age of rich people not paying their taxes Even reducing the costs of tax filing by one-third would save time, money, and aggravation. Americans spend about 2 billion hours collectively preparing for and filling out taxes, or about 12.5 hours per taxpayer, and spend billions of dollars out of pocket on tax-preparation costs. Having the government fill out taxes would completely remove the fear of making a mistake and getting audited, and the trauma that can arise from that. It would also reduce the rate of errors in submitted returns, some of which are substantial. For example, about 20 percent of people who qualify for the earned-income tax credit don’t receive it. California has experimented with providing automated returns for state taxes. An early pilot version of the program found that those who used it loved it, with 97 percent planning to use it again the next year. It also reduced error rates by nearly 90 percent. And that—the fear that the government might do a good job of collecting taxes, that people might come to appreciate this, and they might come to view paying taxes as anything other than an onerous burden—explains exactly why we don’t have automatic returns, despite all the benefits. Ideas for automatic returns have been floated, most prominently by Barack Obama during his 2008 presidential campaign and by Senator Elizabeth Warren in 2016. These initiatives are opposed by the tax-preparation industry, of course, which donates to both Democrats and Republicans. But opposition to automatic tax filing runs deeper among Republicans. As Ronald Reagan once put it, “Taxes should hurt.” He meant that when paying the taxes you owe is a painful process, you are very aware that government is taking your money. Then the governor of California, he was resisting the introduction of state-tax withholding, which, he felt, made it too easy for government to take money and too easy for taxpayers to miss what was happening. Reagan himself changed his mind over time, and even advocated a version of prefilled tax returns as president. But the Republican Party stuck with his earlier position. After all, those numbers about hours and dollars spent filing taxes come in handy in campaigns against taxes in general. Read: Why Americans don’t cheat on their taxes The stance that paying taxes should be painful has metamorphosed into a strange insistence among Republicans that everyone should pay taxes. Mitt Romney famously complained that “47 percent of Americans pay no income tax. So our message of low taxes doesn’t connect … I’ll never convince them they should take personal responsibility and care for their lives.” Rick Perry railed at the “injustice that nearly half of all Americans don’t even pay any income tax.” It’s an odd position for a party that’s been vehemently, and successfully, anti-tax for decades. Indeed, it’s Republican tax cuts that have excluded many people from paying tax. But it makes its own sense. As Romney realized, after decades of slow but steady cuts, the Republican policy of reducing taxes no longer resonates with most voters. In the early 1970s, about two-thirds of Americans thought their taxes were too high, and they were very receptive to Ronald Reagan’s low-tax message. Decades of tax cuts later, the proportion of Americans saying their taxes are too high is at or near an all-time low. In other words, by acting on their tax-cut promises, Republicans have destroyed the basis for the popularity of their main proposal. Where does a party go without its signature policy? Perhaps it desperately turns to other issues that can rally the base, such as racism and xenophobia. Perhaps it thrashes around and divides itself trying to figure out its stance on popular spending programs. And perhaps it digs in to its old ways, trying to make sure that paying taxes still hurts. We want to hear what you think about this article. Submit a letter to the editor or write to letters@theatlantic.com.
https://www.theatlantic.com/ideas/archive/2019/04/american-tax-returns-dont-need-be-painful/586369/?utm_source=Master+List&utm_campaign=029421584a-Sidney%27s+Picks+-+1%2F4%2F19_COPY_01&utm_medium=email&utm_term=0_f29e31a404-029421584a-
CC-MAIN-2019-26
refinedweb
1,203
58.42
Rebuilding a Flex Mobile App as an Alexa Skill Many, many moons ago I created a ridiculous Flex Mobile app called TBS Horoscope. This was for the Nook platform, eventually moved to Amazon Android App store (where it still sits actually) and one of my few commercial apps. The app was fairly simple. It generated a fake horoscope when an astrological sign was requested and persisted it for the day. That way it would be a bit more “realistic”. I thought it would be fun to rebuild this for the Amazon Alexa. So I did it. Because I have a great job and I’m very lucky. Before I talk about how I built it, here’s a video of it in action. New Alexa skill - driven by @openwhisk of course. Previously a Flex Mobile app. pic.twitter.com/8uloEMRPi4— Raymond Camden (@raymondcamden) October 4, 2017 Ok, so how did I build this? I began by creating a service just for the horoscope generation itself. Initially this was going to be its own OpenWhisk action, but I ran into some issues where that wouldn’t make sense. I’ll explain why later. Here’s the code. const signs = ["Aries","Taurus","Gemini","Cancer","Leo","Virgo","Libra","Scorpio","Sagittarius","Capricorn","Aquarius","Pisces"]; function getAdjective() { return adjectives[randRange(0,adjectives.length-1)]; } function getNoun() { return nouns[randRange(0,nouns.length-1)]; } function getSign() { return signs[randRange(0,signs.length-1)]; } function getFinancialString() { let options = [ . ", "Consider selling your " + getNoun() + " for a good return today. ", "You can buy a lottery ticket or a " + getNoun() + ". Either is a good investment. " ]; return options[randRange(1,options.length-1)]; } function getRomanticString() { let options = [ "Follow your heart like you would follow a "+getAdjective() + " " + getNoun() + ". It won't lead you astray. ", "You will fall in love with a " + getSign() + " but they are in love with their " + getNoun() + ". ", )]; } function getRandomString() { var options = [ "Avoid talking to a " + getSign() + " today. They will vex you and bring you a " + getNoun() + ". ", "Spend time talking to a " + getSign() + " today. They think you are a " + getNoun() + "! ", "Dont listen to people who give you vague advice about life or your " + getNoun() + ". ", . ", "Something something you're special and important something something." , "A " + getAdjective() + " " + getNoun() + " will give you important advice today. ", "A " + getAdjective() + " " + getNoun() + " has it out for you today. ", "Last Tuesday was a good day. Today - not so much. ", "On the next full moon, it will be full. ", "Today is a bad day for work - instead focus on your " + getNoun() + ". ", "Today is a good day for work - but don't forget your " + getNoun() + ". ", "A dark stranger will enter your life. They will have a " + getAdjective() + " " + getNoun() + ". " ]; return options[randRange(1,options.length-1)]; } function randRange(minNum, maxNum) { return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum); } let nouns, adjectives; function create(args) { //see if we have a cache noun list if(!nouns) { nouns = require('./nouns'); } if(!adjectives) { adjectives = require('./adjectives'); } let horoscope = ""; horoscope += getRandomString(); horoscope += getFinancialString(); horoscope += getRomanticString(); horoscope += "\n\n"; horoscope += "Your lucky numbers are " + randRange(1,10) + ", " + randRange(1,10) + ", and " + getNoun() + "."; return horoscope; } exports.create = create; A horoscope is generated by combining a few random strings. I realized many horoscopes focused on money and love, hence the specific functions for them. To make things super random, I used a noun list with over 4500 words and an adjective list nearly 1000 words long. I had to convert these to JSON files as I didn’t know how to read text files in an OpenWhisk action. (Now I do.) If you’re curious, I actually copied the entire word list into my clipboard, pasted it into Chrome Dev tools with backticks before and after, then converted it into an array. Finally I did copy(s) to copy it back to my clipboard and then I saved it to the file system. Oh - and rewriting ActionScript to JavaScript was simple as heck - all I did mainly was remove the types. That made me feel a bit sad and I thought about maybe using TypeScript for my code, but I’d have to transpile it before sending it to OpenWhisk and I didn’t want to worry about that. So that’s that. The Alexa part is pretty simple. Once again I’ll say I’m not happy with how I write my skills. It works. It isn’t difficult. I just think I can do better. function main(args) { if(args.request.type === 'IntentRequest' && ((args.request.intent.name === 'AMAZON.StopIntent') || (args.request.intent.name === 'AMAZON.CancelIntent'))) { let response = { "version": "1.0", "response" :{ "shouldEndSession": true, "outputSpeech": { "type": "PlainText", "text": "Bye!" } } } return {response:response}; } //Default response object let response = { "version":"1.0", "response":{ "outputSpeech": { "type":"PlainText" }, "shouldEndSession":true } }; //treat launch like help let intent; if(args.request.type === 'LaunchRequest') { intent = 'AMAZON.HelpIntent'; } else { intent = args.request.intent.name; } // two options, help or do horo if(intent === "AMAZON.HelpIntent") { response.response.outputSpeech.text = "I give you a completely scientifically driven, 100% accurate horoscope. Honest."; } else { let horoscope = require('./getHoroscope').create(); response.response.outputSpeech.text = horoscope; //console.log('Response is '+JSON.stringify(response)); } return response; } exports.main = main; Basically this boils down to two things - help and the horoscope. You’ll notice I don’t actually persist the horoscope for the day. I was going to make this skill be a bit more advanced. It would ask you for your sign if you didn’t give it, and heck, even let you give it a birthday and it would tell you your sign. I’d then persist the horoscope in Cloudant and everyone (of the same sign) would get the same horoscope. Then I remember horoscopes are bull shit and this is for fun and as a user, I’d rather have it just always be random. So you might be wondering - where’s the skill verification stuff? Back in August I released a package for that so you no longer have to write the code yourself. Given that my Alexa skill action is called tbshoroscope/doHoroscope, I made my public API like so: wsk action update tbshoroscope/getHoroscope --sequence "/rcamden@us.ibm.com_My Space/alexa/verifier",tbshoroscope/doHoroscope --web raw I then grabbed the URL ( wsk action get tbshoroscope/getHoroscope --url) and supplied that to Amazon. I’m currently waiting for verification from Amazon and when it goes live, you’ll be able to find it via its skill name, “TBS Horoscope”. Note - the name may change as “TBS” is a television channel here. Also, if they find a bug, obviously the code may change a bit too. If the name changes, I’ll add a comment below so please check it, and if the code changes, the GitHub repo will always have the latest. You can find this demo here:
https://www.raymondcamden.com/2017/10/04/rebuilding-a-flex-mobile-app-as-an-alexa-skill
CC-MAIN-2018-34
refinedweb
1,120
68.77
Registering component process in react native, open your project folder. In root you can see index.js and App.js . In older version files name are index.ios.js and index.android.js. But it does not matter if you are coding for android you can use index.android.js and if you are coding for IOS you can use index.ios.js In updated installation index.ios.js and index.android.js are removed and index.js and app.js is added as root file So If you have index.android.js , please use this file as your root android file and as i have index.js and app.js i will use app.js as root file Index.js : This file use to import App component from app.js file App.js: this file has code which is used to display landing screen of app So I am going to use app.js to start our application . in app.js remove all code and write following code import React, { Component } from 'react'; This code is importing React and Component from react which we will use later in our app. Use of importing Component is to extends class of our component. Now we will import design element component View and text using react native so we will write second line import { View, Text } from 'react-native'; View and Text these component help us to design our application. We can apply css to it . View work as container and text work as to write text in it Now we will register our component so class YoutubeVideo extends Component { render() { return ( <View> <Text>Youtube Video</Text> </View> ) } } Now we will export this component by adding line blow export default YoutubeVideo; So your complete code will look like this import React, { Component } from 'react'; import { View, Text } from 'react-native'; class YoutubeVideo extends Component { render() { return ( <View> <Text>Youtube Video</Text> </View> ); } } export default YoutubeVideo; In above code you can see we created a component YoutubeVideo and export it for import on another file, If you will not use export you can’t import it on another file for use Now we will import and register this component in index.js file Open index.js file Now change App import to YoutubeVideo You will see code like this import App from './App'; Change to import YoutubeVideo from './App'; One important thing is here as you can see code is written … from ‘./App’; . Actually we do not use .js extension when we import any component from any file . we just write file name only so App.js is written only as App Now we will register our component to our application So now you can see code below AppRegistry. AppRegistry use to register component with app . like we have main component YoutubeVideo so we will register this main component with our app. So to do this we will change last line of AppRegistry AppRegistry.registerComponent('youtube_video', () => App); You can see line like this . But we have imported our component as YoutubeVideo so we will change App to YoutubeVideo. Now our line should look like this AppRegistry.registerComponent('youtube_video', () => YoutubeVideo); youtube_video this is our project name which we created using react init command above Now our main component is created and registered to app Open simulator and click r button two times Now you can a your text on screen which we added in app.js file using <Text></Text> So your screen is ready with your component to move further
http://blog.stw-services.com/registering-component-react-native/
CC-MAIN-2019-18
refinedweb
587
66.44
SYNOPSIS #include <unistd.h> char *getcwd(char *buf, size_t size); DESCRIPTION The PARAMETERS - buf Points to the buffer to copy the current working directory to, or NULL if getcwd()should allocate the buffer. - size Is the size, in bytes, of the array of characters that buf points to. RETURN VALUES If successful, - EACCES A parent directory cannot be read to get its name. Read or search permission was denied for a component of the path name. - EINVAL The size parameter is zero, and the buf parameter is a non-null pointer. - ENOMEM Insufficient memory exists to allocate a buffer to hold the path name. - ERANGE size is less than 0 or is greater than zero but less than the length of the path name plus 1. CONFORMANCE POSIX.1 (1996). MULTITHREAD SAFETY LEVEL MT-Safe. PORTING ISSUES The returned path name is in NuTCRACKER Platform format. You can use Path names are returned as multibyte sequences and are converted from Unicode (UTF-16) before returning: _NutPathToWin32(), _NutPathToWin32FS(), free(), malloc(), xlocale() PTC MKS Toolkit 10.3 Documentation Build 39.
https://www.mkssoftware.com/docs/man3/getcwd.3.asp
CC-MAIN-2021-39
refinedweb
178
57.06
RationalWiki:Saloon bar/Archive366 Contents - 1 It's pure luck that we haven't had a truly catastrophic cyberdisaster because no one takes cybersecurity seriously - 2 PSA - 3 Some editing required - 4 Herman Cain has just died - 5 Vaush - 6 Interpretation? - 7 Just what the USA needs: another disaster - 8 The COVID-19 pandemic and Trump decimating the US, I swear to a God that likely does not exist, it is taking a toll on my mental health - 9 Shocking tales from the Aspie side! - 10 Brighteon - 11 Horrible Youtube channel - 12 <3? - 13 Eviction crisis - 14 I tried to decipher this - 15 Trump interviewed on Axios - 16 Something interesting I noticed on the state election ballot - 17 When your sword in minecraft breaks and you are forced to defend yourself with a shovel - 18 Feedback appreciated - 19 Concentration camps in China - 20 "Shared disinformation"? - 21 The best political compass test by far. - 22 Something I didn't know about Marx - 23 Cuomo Begs Fleeing New Yorkers To Return From Connecticut, Hamptons After Revealing Top 1% Pay 50% Of State Taxes - 24 About a person who is a thorough anti-communist but is classified as "Libertys" and "Left of Reason" - 25 How many active users are on the site? - 26 Help with Coast to Coast AM “Area 51 caller” - 27 Maybe I can get a job digging plague pits - 28 I wonder if Mike Pence will run for President in 2024 - 29 Help - 30 Figuring out the number of digits in extremely large numbers - 31 Friendly reminder to US citizens on the wiki who are 18 or older - 32 Favourite action movies of the 80's? - 33 ~On dropping in to the Saloon Bar * - 34 This site is actually the perfect place to ask this and since I don't get any results when typing it in the search bar... - 35 Damning expose on CHAZ/CHOP It's pure luck that we haven't had a truly catastrophic cyberdisaster because no one takes cybersecurity seriously[edit] The Twitter "hack" was some random kid. Let me say that again for emphasis. The Twitter "hack" was some random kid. Using basic social engineering hacks. What if it had been Russia, who got into only Trump's account, and tweeted "The time for freedom is now--rise up and kill any Democrats you can!"? Can you imagine the chaos and impact that would have? Or, Russia has too many reasons to disincentivize that--what if a random alt-right troll did it? For the lulz. Basic social engineering. Sure, Twitter will be on alert for it now... somewhat. For a little while. Until they get lax again. Twitter is hardly the only vulnerability. That's not even getting into REAL hacking. Not that it's needed. A large portion of the US power infrastructure is controlled by hardware that is STILL SET TO DEFAULT LOGINS. Like your router, when it comes set to "admin/admin". It's not QUITE that bad, because the default is dependent on the model of the hardware and not easy to just guess, but if you know the model, you can find the default, and bam you're in. Some of these are only accessible by hardline, so there's a physical presence needed, but it's not like every utility tunnel is guarded against access. Not remotely like that. Hell even our nuclear reactors are barely guarded. Nobody in power understands the problem so nothing gets done. I wonder if someone might do something like cause a week long power outage in a major city, just so people realize the scale of the problem, before it ends up in something much much worse. Glitch (talk) 20:04, 31 July 2020 (UTC) - The problem really is how you can stop this. These kinds of hacks rely on a human element (hence social engineering), which is fundamentally unfixable unless we start using biological data exclusively which has all sorts of concerns involving privacy. Other solutions like physical authentication exist, but similarly can be social engineered. Technologically, we have the right measures in place, 2FA and in some cases physical authenticators go a long way. Sociologically, we have a borderline unfixable issue. We can tell people "hey, don't be an idiot", but that message can take a while to land. A big part of that has to do with the fact that PCs have to accommodate for the worst possible user. You may understand how to use 2FA for security, but the elderly (who often hold management in corporations) and folks who aren't super interested won't and often refuse to understand/use it. Password reuse is a good example. Most people nowadays know that reusing your password across services is setting up a ticking timebomb for a big compromise. However most people also don't think they "need" a password manager, since that is for tech nerds. Instead, they rotate a few passwords around and think that makes them safe enough. This will be an on-going issue and as stated, it's not possible to remove it without creating a major privacy concern. Techpriest (I am Alpharius! / / / ) 21:15, 31 July 2020 (UTC) - I think there's a lot of catastrophes we're unprepared for that are going to fuck us over. COVID-19 really makes you rethink how stable our society is-Hastur! (talk) 21:18, 31 July 2020 (UTC) - How can it be stopped? Obviously it can never be stopped 100%. Nothing ever can. But we can make it a hell of a lot harder and less likely. - A random 17 year old was able to effectively impersonate a former US president and the Democratic nominee in an election year and address millions of viewers. That's how badly we're secured. I feel like the implications of the huge bullet we dodged that he was just stupid and greedy are going completely unnoticed. Which is exactly why the one that's coming, that's going to actually be really bad, won't be stopped. Humans only learn that fire is hot after they get burned. Sometimes not even then. - Everything is fundamentally unfixable, until you figure out how to fix it. At the very LEAST, as a complete brain dead reform, we could have a corporate security culture such that if you ever give anyone (even the CEO) your login credentials to anything, you are immediately fired on the spot, no exceptions, and blacklisted. With modern software there is absolutely 0 reason for that to ever be necessary. ZERO. Yeah no policy is ever followed 100%. But we're a long, long way from 100%. We can't even SEE 100% from here. - The problem is not the technology. It hasn't been for years. The problem is that even when good security policies are in place, they aren't followed. That has to stop, now. Frankly, Twitter should be shitting their pants in terror of serious and dire consequences because Trump's Twitter was on the table for being compromised. I'm pretty sure some law on the books makes it a criminal offense to impersonate a sitting president, or aid in the commission of said crime. I know that's not the case, because corporations and their higher ups are above the law and thus have no fear of any consequences, but it SHOULD be. - This is not a privacy issue. This is a "people are fucking stupid and that's compounded by a culture that incentivizes them to be that way" issue. And it's not going to get fixed. Anyone with even passing knowledge of the situation has been ringing the alarm for about 2 decades now. The vulnerabilities are obvious and well known, and nobody cares. People are going to die over this. I have to stop thinking about it before I get depressed. Glitch (talk) 00:08, 1 August 2020 (UTC) - Some script kiddie hacking twitter to do a bitcoin scam hardly qualifies as a "truly catastrophic cyberdisaster." Governments are spending untold millions (billions?) of dollars on cybersecurity to not only protect their systems, but actively attack their adversaries' systems. This isn't focused on military systems alone, but critical infrastructure like the power grid and utilities and public health infrastructure. Also, state and local systems are targets from targets both domestic and foreign threats, for example, people trying to fuck up elections. No matter what protections we put in place, it's not a matter of if, but when, a "catastrophic" event occurs. The best prepared authorities will not only have a good protection system in effect, but a good system that can recover from an attack while minimizing the impacts on the people they serve. We, the public, need to make sure that the people responsible for protecting all these systems are sufficiently and transparently funded and managed. —cosmikdebris talk stalk 02:04, 1 August 2020 (UTC) - Did... did you read what I wrote? Because the fact this wasn't a disaster is my ENTIRE point, as it very easily COULD have been. And it doesn't matter how much money their spending if the policies are bad and not even being followed anyway. It's completely irrelevant actually. Oh, great, so this system is completely hardened against all forms of attack, to great expense--too bad they left the password on the default setting, or gave it away to someone on the phone who claimed to be a Government Password Inspector. It's like putting the key to your fortress under your doormat. It doesn't matter how good the security is if it's easily bypassed. Glitch (talk) 02:32, 1 August 2020 (UTC) - @Glitch I was mostly replying to RZ's original post, and I concur with what you wrote above. Your point "it's not the technology, it's the people" is spot on. I wanted to chime in with an observation that it's not if these things are gonna happen, it's when, and these technology companies need to learn from their mistakes quickly and put controls in place to prevent a recurrence, or their whole business could be placed in serious jeopardy. It's slightly different with government organizations, when peoples' lives are at stake. In this case, these organizations need to be open and honest about the threats and how they manage them, so their stakeholders (us) can give them the resources and expertise they need. —cosmikdebris talk stalk 16:12, 1 August 2020 (UTC) - I apologize for my misunderstanding of what you meant. I'm so used to either being misunderstood in what I'm saying (whether the fault for that is mine or the reader's is immaterial, but I'm very actively trying to work on minimizing the chance of the former) and having to continually clarify or else being disagreed with that I forget there's a possibility of being both understood and agreed with, hah. Mea culpa. Glitch (talk) 19:57, 1 August 2020 (UTC) - I have gone through a couple usernames. Not exactly by choice, but I don't backdoor here. I've had this one for a long time, and as long as I keep logging in my password is set, but I would have to make a new username if my password ever got ditched, because at this point I have no idea what it is. This site is good in the sense that you don't have to tie a username to an email address. I would never try to recover a password from a place that I don't know is secure, or at least protected. In bad faith, if somebody tried to track me down, maybe they could find out who I am from my posts and statements, but that wouldn't give them my credentials. And I think ultimately, they'd be very disappointed. Gol Sarnitt (talk) 05:59, 2 August 2020 (UTC) PSA[edit] I won't single anyone out, but I read and edited Ayaan Hirsi Ali. And I am quite shocked by the poor job being applied to the initial quote. From: [1], the supposed quote: Now, to be clear, this is sourced from: [2] What does the full quote say? I don't care what your opinion on her is; this is a ridiculous case of cutting up a quote in pieces without even properly signalling it to the reader. If you are going to - for whatever reason that may be - cut up a quote, make sure to introduce this: [...]. So the reader knows that this is not the exact sequence of words stemming from the original quote and, if they are interested, they can pursue the full quote by going to the source linked. But this? This is a shit salad, and I am not even a fan of hers. Worse, I think the full quote in itself is incriminating against her, there was no need to make it look worse because it reads like a fearmongering, bigoted piece. If you are going to cut up the quote, do it fucking correctly: I am sorry for sounding angry, but this is a mistake I have to make sure doesn't happen regularly here. This quote was written in March of 2014 [3] and stood for more than 6 years, guys, and nobody noticed? I happen to be familiar with Hirsi Ali because I used to be an anti-Muslim bigot of the Sam Harris kind for multiple years, and editorial "tricks" like these, which the anti-SJW community loved to point out, didn't help and made it worse, because it made me by default assume that every critic of Hirsi Ali is this dishonest. And it doesn't have to be, and I am a different person today. Okay, whatever. — Godless Raven talkstalkwalkbalk 🌹 00:09, 1 August 2020 (UTC) - Yes that's bad style to the point of inaccuracy, but I also see why they chose to abbreviate the quote, because the context doesn't really alternate the intended meaning. ikanreed 🐐Bleat at me 01:10, 1 August 2020 (UTC) - It's likely the quote was mistaken for non-quote text or the editor didn't see the end of the quote and beginning of the regular-text and chopped it up, likely not on purpose. While it's nice that you corrected it, I would say aggressively bitching about your "disappointment" on the saloon is seriously the worst way you could possibly try to encourage other users to be more careful when editing. WTF? ShabiDOO 02:09, 1 August 2020 (UTC) - I don't know Shabidoo. It seems like some pretty hacky writing on the part of the original transcriber of that quote. ☭Comrade GC☭Ministry of Praise 02:39, 1 August 2020 (UTC) - It's quite possible that they didn't know how to properly write quotes with omissions. I, too, consider it a basic writing skill, but it is a skill that a lot of people nonetheless lack the same way many people butcher poor, defenseless commas. ikanreed 🐐Bleat at me 04:24, 1 August 2020 (UTC) - (edit conflict) @Shabidoo I am not sure what tone of mine would please you, but I confess that I was quite frustrated. shrug The presentation of the quote comes off as hacky, but you're right that it could've been oversight. Although I can't help but think it's unlikely to have been accidental. - @Ikanreed I politely disagree; the reason is that the quote came off as weird to me. It felt like it was cut in rather disconnected pieces, that's why I got suspicious of it in the first place. Or, in other words, the "flow" of argumentation came as weird to me. I don't know how to explain it properly. — Godless Raven talkstalkwalkbalk 🌹 04:27, 1 August 2020 (UTC) - I think your intuition has little credibility against a pretty reasonable assumption about writing on a wiki anyone can edit. I'd be happy to overturn that assumption for something more substantive, like clearly dishonest edit history on the page. ikanreed 🐐Bleat at me 04:59, 1 August 2020 (UTC) - My intuition that the initial quote was weirdly constructed that raised my suspicion? Or what else are you referring to? — Godless Raven talkstalkwalkbalk 🌹 06:11, 1 August 2020 (UTC) - I don't see the problem here. — Oxyaena Harass 07:29, 1 August 2020 (UTC) - There absolutely was a problem that they fixed. It's potentially libelous(it'd take a pretty serious case though) to ascribe a quote in a manner that doesn't clearly denote omissions. The imagined sneaky liar doing it on purpose is almost certainly entirely in their head. ikanreed 🐐Bleat at me 23:40, 1 August 2020 (UTC) Template:Verygood — Godless Raven talkstalkwalkbalk 🌹 00:18, 2 August 2020 (UTC) Some editing required[edit] I just created a draft on the New Eden School. It needs some serious work though.— Jeh2ow Damn son! 20:00, 1 August 2020 (UTC) - @Jeh2ow I did a little expansion and reorganizing. Mainly (In terms of expanding), I mentioned the creationist courses. One of the required textbooks is by dear ole ICR drone Brian Thomas. --George Soros Puppet (talk) 01:43, 2 August 2020 (UTC) Herman Cain has just died[edit] He never caught them all.— Jeh2ow Damn son! 17:45, 31 July 2020 (UTC) - Rest in peace Fowler (talk) 17:59, 31 July 2020 (UTC) - I see now that the circumstances of one's birth are irrelevant, it is what you do with the gift of life that determines who you are. ikanreed 🐐Bleat at me 13:55, 2 August 2020 (UTC) Vaush[edit] Can someone who knows about Vaush have a look at the latest, not minor, edit as it seems to affect the general tone of the article. I don't know the gentleman so can't tell if it's right or wrong. Scream!! (talk) 19:52, 31 July 2020 (UTC) - Some of it looks good from what I've seen of him, some of it looks bad. The "don't actually say the bad words" bit is stupid. We literally link to articles on these words and terms for fuck's sake. ☭Comrade GC☭Ministry of Praise 20:05, 31 July 2020 (UTC) - Godless Raven talkstalkwalkbalk 🌹 20:56, 31 July 2020 (UTC)All you need to know about vaush. Or, shorter: he is a sexual harasser, predator and basically a far-left copy of destiny who gained prominence because younger people online like that sort of gross stuff. — - Ah, I see you've done zero research on anyone to your left, as per usual. No, I'm not a fan of him. ☭Comrade GC☭Ministry of Praise 21:15, 31 July 2020 (UTC) - ok, prove me wrong — Godless Raven talkstalkwalkbalk 🌹 21:58, 31 July 2020 (UTC) - On what? That the Dusty video is all you need to watch in order talk about Vaush? Prove it is. I'm sure he's said other dumb shit as well. He's also said non-stupid shit, which while it doesn't exonerate him for saying stupid shit, means that there's more than just "dumb wannabe edgelord" That he's not a Destiney ripoff? I mean, that's pretty easy. Vaush's stream and style is pretty clearly derived from both Destiny and PewDiePie, plus probably other shows I don't know of. Note I said "derived from" and not "rip off of". ☭Comrade GC☭Ministry of Praise 22:10, 31 July 2020 (UTC) - Ok so basically nothing I said was wrong. Congrats for playing yourself. — Godless Raven talkstalkwalkbalk 🌹 22:24, 31 July 2020 (UTC) - "All you need to know about vaush." "basically a far-left copy of destiny" Eat crow. ☭Comrade GC☭Ministry of Praise 22:27, 31 July 2020 (UTC) - Raven is socdem capitalist pig complaining about a fat autistic man sexually harassing someone years ago on Destiny's discord. Eat raven. HairlessCat (talk) 01:24, 1 August 2020 (UTC) - Huh? ☭Comrade GC☭Ministry of Praise 01:33, 1 August 2020 (UTC) - @HairlessCat Not only did he sexually harass someone, he also tried to coerce the victim to shut up and use the mods on destinys discord to cover it up ( this isnt to mention that he also harassed other women, mostly with mental disabilities. ( so yeah, fuck that guy. — Godless Raven talkstalkwalkbalk 🌹 03:07, 1 August 2020 (UTC) - He also lied about apologizing to the victim, blocking that person instead. ( — Godless Raven talkstalkwalkbalk 🌹 03:09, 1 August 2020 (UTC) - He ain't perfect. HairlessCat (talk) 12:25, 1 August 2020 (UTC) - Would you say the same thing if he was an Alt-Righter?? Gunther1987 (talk) 19:16, 2 August 2020 (UTC) Interpretation?[edit] I was listening to ac\dc's back in black the other day and was wondering what the fuck he was taking about, can anyone enlighten me? Fowler (talk) 17:39, 1 August 2020 (UTC) - The song is a tribute to a band member that died. 192․168․1․42 (talk) 19:19, 1 August 2020 (UTC) - If you play it backwards, it’s about how we should all worship Satan. Chef Moosolini’s Ristorante ItalianoMake a Reservation 19:27, 1 August 2020 (UTC) - If you play it backwards it sounds better too. Cardinal Chang (talk) 15:56, 2 August 2020 (UTC) Just what the USA needs: another disaster[edit] Nature just loves piling shit on top of a major pile of shit that has killed over 155,000 people. Now we got Hurricane Isaias --George Soros Puppet (talk) 01:59, 2 August 2020 (UTC) - Functional cultures produce resilient societies that can weather disasters with minimal disruption. This is probably a good time to take stock of what went wrong and how that can be prevented in the future. 192․168․1․42 (talk) 17:14, 2 August 2020 (UTC) The COVID-19 pandemic and Trump decimating the US, I swear to a God that likely does not exist, it is taking a toll on my mental health[edit] I am not exactly sure how to put it but I guess the outside pressure of everything is messing with my thought process. --George Soros Puppet (talk) 14:15, 2 August 2020 (UTC) - Turn off telecommunications, and go do something unrelated and enjoyable like reading a book, watching a movie, exercise, or a productive hobby. After you’ve relaxed, detach yourself emotionally from what’s been troubling you before returning to the Internet. Getting upset or preoccupied doesn’t help anything. 192․168․1․42 (talk) 17:13, 2 August 2020 (UTC) Shocking tales from the Aspie side![edit] I was looking for anecdotes about hyposensitivity to pain this morning after remembering how much I enjoyed the shock from joke gum: a shipmate bought one for his kid and brought it into work one day and pretty soon after the first shock I'd worked out how to keep it triggered in my right hand (until he took it back for his kid, the philistine). I couldn't find examples of similar behavior, and have gotten that a lot of other folks here are on the spectrum, has anyone else experienced this (or something similar)? Artificius (talk) 10:09, 2 August 2020 (UTC) - When I was little I used to constantly run into the flatscreen TV we had. I don't remember doing so, but my mom does. It was because I liked the pressure. — Oxyaena Harass 17:12, 3 August 2020 (UTC) - I know that feeling. I sleep under two wool blankets I stole from my last ship even in the summer (then I use a fan, and I have to wash everything every few days). It's all about the pressure. Artificius (talk) 23:51, 3 August 2020 (UTC) - Y'know, it's funny. No one there liked those blankets (wool tarps), and yet I still care that I stole the stupid things. Artificius (talk) 23:57, 3 August 2020 (UTC) Brighteon[edit] I found a YouTube rip off promoting "free speech". Later, I did some research and found out that it's CEO is Mike Adams.— Jeh2ow Damn son! 17:44, 3 August 2020 (UTC) - Yeah, there's one for infowars too. ikanreed 🐐Bleat at me 21:09, 3 August 2020 (UTC) Horrible Youtube channel[edit] Check this out.HairlessCat (talk) 20:46, 2 August 2020 (UTC) - Fuckers are using elephants in combat. Fowler (talk) 14:08, 3 August 2020 (UTC) - you really have to make me look like an idiot, don't you? Fowler 11:50, 4 August 2020 (UTC) <3?[edit] What does this mean? I would have thought it was a willy Fowler (talk) 09:47, 3 August 2020 (UTC) - Seriously? It's a heart. ikanreed 🐐Bleat at me 13:55, 3 August 2020 (UTC) - >:( Fowler (talk) 14:02, 3 August 2020 (UTC) - It's a heart. Gunther1987 (talk) 17:04, 3 August 2020 (UTC) - It means "less than 3". — Godless Raven talkstalkwalkbalk 🌹 17:16, 3 August 2020 (UTC) - Apart from "heart" - statistics are often lumped together where there is <3 replies to a survey or similar, so as not to obviously identify individual responses. Aloysius the Gaul 21:16, 3 August 2020 (UTC) - A willy should look like a rocket ship. That looks like the thing astronauts crash land back on Earth (formal) in, what is that called? They gotta go pull em out of the ocean because they landed in it? That's what it looks like. Gol Sarnitt (talk) 02:54, 4 August 2020 (UTC) - Do you mean this Gol, 8=====D? Fowler (talk) 07:40, 4 August 2020 (UTC) - cock is as diverse as the people they are connected to. open your hearts and your legs for all the dicks of the world and leave your penis-facism at the door AMassiveGay (talk) 07:49, 4 August 2020 (UTC) Eviction crisis[edit] Is it an exagerration to say that America is literally fucked? Nebuchadnezzar7658 (talk) 21:57, 28 July 2020 (UTC) - There are some subsidies being doled out in my state. Not sure how much of an impact it will have, though-Hastur! (talk) 22:03, 28 July 2020 (UTC) - Hopefully some of those numbers can be curbed, but it's still going to be catastrophic. Nebuchadnezzar7658 (talk) 22:16, 28 July 2020 (UTC) - Right? That's a lot of money being asked for that just doesn't exist. We might end up like in 2008. Or there'll be a massive bailout. Which I'm not thrilled about, because it's not going to come from taxes on the wealthy.-Hastur! (talk) 23:15, 28 July 2020 (UTC) - Oddly, the mass evictions are going to screw over the landlords, as there's going to be a huge number of empty apartments that can't be filled... CoryUsar (talk) 23:33, 28 July 2020 (UTC) - It'll be a double whammy. People can't afford rent or mortgages and get evicted creating a homelessness crisis, then landlords and banks default on the loans because people can't pay. Need government intervention, pay the rent and mortgages for Americans through at least July 2021. Though the sum is likely astronomical, it is a small price to pay to keep the societal fabric of the US from literally falling apart. I mean the number of horrible things that come from losing housing security, it too long a list to even document.RipCityLiberal (talk) 23:55, 28 July 2020 (UTC) - Don't forget that with increased homelessness- it will be more difficult to keep track of COVID-19 cases. --George Soros Puppet (talk) 00:00, 29 July 2020 (UTC) - And yet, if we let the landlords default, home prices will finally fall to a level affordable to the masses. CoryUsar (talk) 00:32, 29 July 2020 (UTC) - This is what is so freaking shortsighted about caving to landlords (who correctly want to be paid for someone inhabiting their property, if perhaps exorbitantly): very few of the millions of people facing eviction are doing so in a stony, lackadaisical vacuum. Their jobs all ceased to exist simultaneously as a result of COVID-19. If no one is eating out because they don't want to spend their last week on a respirator, that fancy restaurant your tenants comp your drinks at can't stay open long enough to require the services of the accounting firm who blew off a week in a cubicle's worth of steam at concerts and movies or shopped the Bass Pro (where they often lingered perhaps too long in the formerly staffed gun department). Every one of those businesses laid low by the invisible hand paid people who likely didn't own the places where they lived, and unless you're willing to drop your rent to compete with the other dons for a miserly government stipend then who exactly will be moving onto your property? How does this go in any direction other than appropriation of your property by People's Committees? Artificius (talk) 03:07, 29 July 2020 (UTC) - Hold up @Artificius, before you bust your ass on that slippery slope. Though I do believe that after 45 is out, the Federal Government will likely need to embark on a massive buying spree of a lot of property, the primary focus will be more on keeping people in their homes, on their farms, though many banks will likely want to offload a lot of mortgages, not just for residential property but commercial as well. People's Committees implies something common to force land distribution like in Venezuela or Cuba, which isn't gonna happen because as much as I'm a Democrat, they still are funded by rich white people. I think we are going to be a little shocked about how much money we're about to spend, however the full faith and credit of the United States is backed by the labor of every American, which still is a tremendous amount.RipCityLiberal (talk) 03:55, 29 July 2020 (UTC) - That's a fair damned point, though I was more in a Doctor Zhivalgo and Russian/October Revolution headspace than Venezuela/Cuba (honestly no idea how closely they've hewn to the old Soviet model). I meant to imply that there's only so many nights that property would sit vacant while its former inhabitant slept in a tent among thousands more like in my city. Whether that's from a more sane, rational approach such as the government section 8'ing the homes in question, buying them up en masse, or from the whole thing going unattended by Congress long enough to boil over with the social contract and grease the slippery slope into something suspiciously like Communism (since the original term would never play here, maybe "I can't believe it's not Bourgeois!") is where we should start a pool. Artificius (talk) 04:25, 29 July 2020 (UTC) The solution is simple: abolish private property. I recommend you all read Proudhon's masterpiece What is Property? (1840). — Oxyaena Harass 03:57, 29 July 2020 (UTC) - And then what? Also, and though this certainly doesn't cover everybody, Americans in general are terrible as saving and it's not just due to expenses; it's actually a good thing to try to save something up for a crisis. Although no one wants to hear it, some people are in this spot from their own making (like a few idiots I work with who run air conditioners with windows open and bitch about not being able to pay their electric bills); now how to sort them out is another matter, but there will be some who are evicted because they should be. There's no good solution, just a least worst one. The Blade of the Northern Lights (話して下さい) 04:10, 29 July 2020 (UTC) - Housing is a human right, I fundamentally disagree with this in every way. Capitalism has created the homelessness crisis America (honestly the Western world) is experiencing. Previously banks manipulative practices created the 2008 crisis. Now a global pandemic has brought the system to its knees. It's time to explore a new system.RipCityLiberal (talk) 04:16, 29 July 2020 (UTC) - Living beyond your means is not a human right, however, nor is refusing to make good on legally binding contracts. To go to the obvious example, I have no sympathy for sovereign citizens getting tossed out of places and arrested for playing stupid games with their rental or mortgage agreements. And while the banks absolutely are responsible for the mess that was 2008, if you think this housing crisis is bad, look what Eastern Europe was dealing with in the 80s; while it's certainly a goal to reduce it as much as possible, I highly doubt any economic system can totally eliminate that problem. The Blade of the Northern Lights (話して下さい) 05:21, 29 July 2020 (UTC) - Interesting rant, but oddly specific and very reliant on a weird direct relationship that maybe you have with your landlord? Like, who comps their landlord's drink? I've lived in a house where the rent was cheap and there was no such thing as a late fee. Squirrels in the walls in winter, bats in my attic room in summer, but hey, the rent was five guys cheap. I now live in an apartment, very nice, no contact with the management besides "sign the lease, here's the rent, oh pool is closed still? whatever." Am I missing something? Like, this is some caricature of French nobility? Who comps their landlord's drinks!?! Gol Sarnitt (talk) 04:14, 29 July 2020 (UTC) - If that was too ranty, I feel comfortable blaming alcohol if you do (this is the Saloon). "Comping the landlord's drinks" wasn't a reference to anything historical so much as a snide reframing of the relationship between some hypothetical mogul of a property owner's luxurious lifestyle and their ever-more impoverished tenants. As far as he's concerned, this hypothetical jerk is well within his rights to throw the deadbeats out on the street if they won't go back to work. And he totally is! It's also myopic, cruel, and likely to fuel social changes more catastrophic to his empire than if he and others had embraced reform (here I'm definitely referencing Theodore Roosevelt's "The Right of the People to rule" speech and its bit on Turgot, partly cause you got me thinking about French aristocrats and the decades of continent/world-spanning joy brought about by bread riots and short men in funny hats). Artificius (talk) 04:53, 29 July 2020 (UTC) endorsed, I'm with ya. Gol Sarnitt (talk) 03:14, 30 July 2020 (UTC) - Ok, so many things. - @oxyaena Didn't you once say you were incapable of holding a job? I don't think you should be able to tell others what they are and are not allowed to own. - @RipCityLiberal I don't agree that housing is in itself a "right", as it fails the Desert Island test. However, what I will say is that if someone does productive work, a job that is necessary for society to function, no matter how menial the task, society does owe this person some bare minimum of food, shelter, dignity, etc. Enough to be a part of the society that depends on this person. A "living wage". We can disagree on what jobs actually are critical for society, or how much the living wage should be, but we should all agree there should be something. - @Blade Going to agree with you wholeheartedly. - Side note, being homeless and unemployed is not exploitation, it's the exact opposite of exploitation. You are making absolutely no one else rich by being on the street (Prison-Industrial Complex notwithstanding). If the most sociopathic shadow-government corporatist were to create a paradise/dystopia, you would work your ass off doing the most complex tasks you can possibly do, in a squalid but otherwise safe and secure home, having just enough food and health care that your productivity and health is maximized, with little savings left over for yourself. So, basically, being a young college graduate in NYC or San Francisco. - I don't know how it is in the rest of the country, but in NYC and California, the landlords don't get to toss people whenever they want to, eviction proceedings have to go through the courts. The courts are already more or less shut down (the judges tend to be older and thus are finding an excuse not to be in crowded indoor rooms), so no matter how deserving or undeserving the tenants are, even when the courts reopen the backlog is going to prevent a lot of the evictions. I'm more concerned about the financial wizardry of how the landlords acquire the buildings in the first place; buildings that have more debt than they are actually worth tend to have... "faulty wiring". CoryUsar (talk) 10:13, 29 July 2020 (UTC) - The reason I`m incapable of "holding a job" is because the capitalist system inherently favors neurotypicals over neurodivergent people. As for property, read What is Property by Proudhon and then get back to me. — Oxyaena Harass 15:25, 29 July 2020 (UTC) - There are many ways to solve homelessness that don't involve getting rid of property rights lol. — Z 16:53, 29 July 2020 (UTC) - Good, then use them or shut up. Ok? Ok. ☭Comrade GC☭Ministry of Praise 16:56, 29 July 2020 (UTC) - "Good, then use them or shut up. Ok? Ok." @GrammarCommie My country did and we don't have this problem, I'm just watching America do American things. — Z 17:45, 29 July 2020 (UTC) - Norway: Adequate and secure housing for all No need to get rid of capitalism. — Godless Raven talkstalkwalkbalk 🌹 17:34, 29 July 2020 (UTC) - America: Property over people. Fix it or shut up. That's not a debate. Make real world effects, or shut up. ☭Comrade GC☭Ministry of Praise 17:37, 29 July 2020 (UTC) - Me, with my bare hands? I am not American to begin with. What's your plan? — Godless Raven talkstalkwalkbalk 🌹 17:40, 29 July 2020 (UTC) - (edit conflict) I will vote in favor of legislators and referendums who promote affordable housing. Happy now, or do you still feel the need to tell me to shut up?-Hastur! (talk) 17:41, 29 July 2020 (UTC) - Goody for you. They'll ignore your intentions, fuck us all over, and kill our kids so they can win their stupid elections. Better solution. We elect people, and if they don't improve shit we kill them. We keep doing that until either shit improves or we run out of bodies. Seems better than a system that wants to kill my Nieces and Nephews so a fucking moron can desperately try to win an election, so he can validate his insecure ego. All while people say "both sides". Great, if both sides want to kill me and my family, I say kill them both. Kill them all and burn the entire stupid ass system to the ground if that's what it takes to fucking fix the problems. Because pushing that stupid voting button sure as hell ain't doing it. Fuck all of you who think that's ok. Fuck you all. Fuck every last shit that's ok with my fucking family dying for such petty fucking shit. Now, if you'll excuse me, I have to emotionally prep myself to possibly bury my fucking nieces and nephews because the president is a fucking idiot, and everyone is too stupid to kill him and be done with it. ☭Comrade GC☭Ministry of Praise 17:50, 29 July 2020 (UTC) − - What a bizarre thing for GC to say. You can’t make an observation if you aren’t capable of personally taking over a government and making things happen? Just bizarre. I guess none of us can speak on anything. Or is it just a means of silencing people you don’t agree with? Chef Moosolini’s Ristorante ItalianoMake a Reservation 17:51, 29 July 2020 (UTC) - I don't fucking care. All you all do is talk talk talk. None of you have any fucking effect. Nothing has any fucking effect. The fucking system is fucking broken and it's going to fuck us all over to survive. FUck you all!! ☭Comrade GC☭Ministry of Praise 17:53, 29 July 2020 (UTC) - (ec) I am genuinely sorry to hear this GC, I hope the affected family members recover safely and soon. Not a fan of yours personally but our petty mutual hate is not an impediment for me to wish your family members good health and recovery. And yeah, fuck Trump. — Godless Raven talkstalkwalkbalk 🌹 17:57, 29 July 2020 (UTC) - What are you doing now, GC? Chef Moosolini’s Ristorante ItalianoMake a Reservation 17:56, 29 July 2020 (UTC) - (edit conflict) I find myself wanting to know what GrammarCommie is doing to dismantle/improve the current system, besides clumsily removing other peoples' comments and yelling at us-Hastur! (talk) 17:58, 29 July 2020 (UTC) - (edit conflict) He is understandably upset about Trump's Covid-19 response affecting his family. Let's not be too harsh now. — Godless Raven talkstalkwalkbalk 🌹 17:59, 29 July 2020 (UTC) - Screaming into a void while we all do nothing, and are nothing. And the fucking system grinds us under like grain under a millstone. Or, if you want the really graphic answer, thinking about suicide and then realizing I'm too much of a coward to actually follow through, and that it wouldn't do anything anyway, and that everything is going to go to shit and there's nothing I can do about it. That's what I'm doing, isn't it great? Really improving the fucking world aren'td I? What are you doing? Is your little debate solving anything? Any fucking policy changes resulting from it? No? Fuck it then. ☭Comrade GC☭Ministry of Praise 18:03, 29 July 2020 (UTC) @GrammarCommie If you are feeling suicidal right now, please give the hotlines a try. It can't hurt and can only help. — Godless Raven talkstalkwalkbalk 🌹 18:07, 29 July 2020 (UTC) - I told you, I'm too much of a coward to actually do it. I know, I've tried before. I can list the ways. Attempted to hang self, Attempted to choke self, attempted to slit own wrists. Each time I fucking broke down before I could do the deed. My problem isn't suicide, it's what makes me want to kill myself. ☭Comrade GC☭Ministry of Praise 18:12, 29 July 2020 (UTC) - And my family isn't sick, yet. But, while you all 1-80 because I mentioned suicide, think on this. I live in the US, in the South. I live deep in the red area. None of my neighbors wear masks, and both my sisters and my brothers in law are Trump supporters. If he does open those schools, I'm betting they'll send their kids there, especially my eldest sister, who has four kids to manage. And guess what the effects of cutting funding to education and then demanding a resource intensive curriculum during a pandemic are? Yeah. Fun times ahead. And the real fun part? The CDC says the real big wave of infections hasn't hit yet! Round two! Guess what happens if those kids go out into that maelstrom? Yeah. Best case scenario, they die. Worst case, we suddenly have a fuck ton of kids with a severely decreased quality of life, who maybe die anyway because every part of our system is shit, including the healthcare system. So, it's not that my family is affected yet, it's that Trump wants to pretend to solve the pandemic so he can up his re-election chances. It's basically his version of declaring a war to win an election. ☭Comrade GC☭Ministry of Praise 18:43, 29 July 2020 (UTC) - GC, I get the feeling of hopelessness, and suicidal depression has been going up and down for me often in the past couple of years, so in that you and I are aligned. I cannot however let the argument from @The Blade of the Northern Lights cosigned by @CorruptUser. Fundamentally, what America has is not Capitalism, it Kakistocracy bordering on Kleptocracy. Those who have accumulated large amounts of wealth did not get it from hard work, they got it from an exploitative system and luck. You cannot tell me, that a family where the primary breadwinner, working two jobs and over 60 hours a week, is lazy. You cannot tell me that a system that allows for 60% occupancy of housing while literal millions are on the streets is fair. Nor can you say with an absolute straight face, that "people living beyond their means" are dedicating more than 50% of their income for rent and mortgages. What we have in America no longer works, in '08 we had an opportunity to fundamentally change the way we think about housing, and we failed because we lacked the imagination of a world where housing is guaranteed.@GR Most Scandinavian countries I think have found a healthy balance with capitalism, but the control over the market and these countries (and indeed many European countries) far exceeds the control in the US. I would 100% support modeling government control similar to these systems, but it requires dispelling from the bullshit arguments that people alone are responsible for their economic situation. Fundamentally, the system is rigged against them.RipCityLiberal (talk) 18:58, 29 July 2020 (UTC) - Who said lazy? The amortization tables for mortgages are readily available, getting a mortgage that's above your means is certainly not a good thing for the banks but you don't have to sign up for it. I didn't say all people are completely responsible for their situations, but certainly not everyone is blameless either. You can be hard working and still not use good financial judgment. The Blade of the Northern Lights (話して下さい) 20:04, 29 July 2020 (UTC) - Fun tidbit, the President who did the most to curb homelessness in recent years? George W Bush of all people. Really, if it wasn't for Iraq and Katrina and doing virtually nothing to prevent the housing bubble and the handling of Afghanistan and the alienation of foreign countries especially Iran when they were willing to have outreach and the open hostility to Putin and the gutting of public schools and the inability to control health care costs and the doubling of national debt in spite of starting off with the last time in US history when the US had a budget surplus and the exorbitant tax cuts for the rich while doing little to go after tax evasion and the continuing outsourcing of manufacturing to China, he wouldn't have been all that terrible. CoryUsar (talk) 20:15, 29 July 2020 (UTC) - @GC While I don't want to argue with someone who is going through a crisis, the death rate for children from COVID is far lower than for other diseases that we simply put up with. Obviously that doesn't mean that absolutely no kids will die, but approximately speaking, the total mortality rate for everyone under 65 including healthy people, is .1%. Source here It's the people over 65, especially with other health problems, that are dropping like flies. Of the people under 65 that die, 90% had an underlying condition, and given that around 1 in 5 people under 65 have an underlying condition, ok hold on a sec gotta math something, around a 1 in 200 chance of death if you are under 65 and have a serious condition, and a 1 in 8000 chance of death if you are under 65 and otherwise healthy. Again, rates vary quite a bit by age and which condition in particular, these are rough averages. Unless your sister's kids have health problems they are more likely to die in a car crash than from COVID. Always buckle up, and please people, wear a facemask. CoryUsar (talk) 21:28, 29 July 2020 (UTC) - My eldest sister has high blood pressure. So I suppose I'll probably be burying her instead. Fun. Although one of my nephews has asthma if I recall. So I might have to deal with that after all. All so Trump can pretend to fix this problem, instead of actually fixing it. ☭Comrade GC☭Ministry of Praise 21:58, 29 July 2020 (UTC) - @CorruptUser The evidence we have on children is scant, we shouldn't be spiking the football saying they are safer. And what kids do very well is spread the disease the others, say to an immuno-compromised parent/adult. Already examples of this happening [4]. - @The Blade of the Northern Lights why do they offer those mortgages to people that can't afford them? Because they profit from them. Banks pay sales people to deceptively offer services to juice revenue in the short term, to increase capital. People are only to blame for wanting to improve their living situation.RipCityLiberal (talk) 22:07, 29 July 2020 (UTC) - @Grammar No, you probably won't be burying your sister. Like I said, she has a 199 in 200 chance of surviving. Most likely to survive, but chance of complications which, yes, can cause permanent damage. She and her kids should definitely wear masks. As for the asthmatic kid, again, most likely will survive, but still a risk of complications. - @Rip No... we have plenty of evidence for children. Virtually everyone in the Chassidic and Haredi communities around NYC got Covid already, and as far as I'm aware there's been almost no child mortality in spite of their communities being 8 kids per family with no possibility of isolation. Unless genetically, Ashkenazi Jews are naturally resistant to Covid (which is a possibility), I think we can extrapolate that everyone else has similar odds. As for kids being snot and germ factories, yes, yes this is true. Again, the schools should be requiring masks. - @Rip ok double @, but needs to be said. The banking industry is not in the business of lending you money. The banking industry is in the business of selling your loans to other, larger banks. They don't give two shits if you can't pay it back, because that's not their problem. The bigger banks got fucked hard back in the 1970's when the smaller banks lent like drunken sailors and resold the loans to the big guys, so they stopped doing cocaine every once in a while to actually vet the occasional loan. Then the US decided that there wasn't enough money flowing from the big banks to the little banks to help people buy homes, so they repealed Glass-Stiegel, so now the big banks could sell the loans again to an even bigger dumbass, hedge funds. But to convince the hedge funds that the Brooklyn Bridge was such an amazing investment deal, the big banks went over to S&P and Moody's to do some financial wizardry, and voila, everything got rubberstamped and the hedge fund managers were too fuqtarded to do any do diligence, because after all, why would S&P be paid huge amounts of money to claim something was good if there was the possibility it wasn't? And, well, you all live the rest of the story. Happy ending, it won't happen ever again because we've never made the same mistake twice, so long as you ignore all the obvious fact that if we never made that mistake we wouldn't have had Glass Stiegel in the first place.CoryUsar (talk) 23:17, 29 July 2020 (UTC) - @CorruptUser On banking, why do we accept that banks operate like that. The purpose of financial institutions should be to hold and distribute capital. If that isn't what they are doing, don't we need to evaluate that? On Covid and children, there are several things people are overlooking in this whole debate. The first is how it spreads among children, most schools (in America at least) closed schools in March, before the spread of Covid reached it's spring peak. It's difficult then to have clear evidence that children behaving normally (with their dirty disgusting selves) wouldn't spread the disease. South Korea, Australia, and Israel thought they had a hold on the virus, re-opened schools, then had to close them recently, because of spikes. The second is that the threat to children dying from the disease is low, but mortality shouldn't be the only metric we use to evaluate. Children's bodies react to the disease differently, and the long term consequences from being infected are completely unknown. Why are we willing to risk our future on what amounts to a guess. Lastly, children are not the only ones in school. Teachers, administrators, counselors, janitors are all at risk. Let's say a child gets infected, and has mild symptoms. Two weeks treating it no problem. But they infect a teacher and a janitor, who now put their family at risk. How would you explain to a child, that when they got sick, they also got their teacher sick and then they died. Is that something you want on a child's conscious? Or let's say a child get's sick enough they require medical treatment in an ICU, which diverts resources from another older person who is sick. The obvious choice is to treat the child, but if the child never got infected, they could use those resources. We must get this under control before we can even consider bringing children back to school.RipCityLiberal (talk) 23:36, 29 July 2020 (UTC) - 1) We shouldn't accept that the banks operate that way, but the reason they do is because we the public fucked up and decided that "homes = investment". Factories and bridges are investment. Homes are consumption. Want to fix the problem? Start by getting rid of the home mortgage deduction from income taxes. - 2) The uninfected are like a giant lake of gasoline, you can keep putting out the fires but that lake is still there, ready to ignite so long as there is a spark somewhere. No matter when you lift the lockdown, those little snot-factories will spread the disease. While the shutdown barely created herd immunity (the disease spread too slow to sustain itself), the shutdown couldn't last forever and even it did there's no way to prevent some pocket of disease from re-spreading everything a year from now. What we can do is enact enhanced policies that can be in place indefinitely (e.g., masks and limited seating at restaurants) that either create herd immunity or causes the disease to have such a slower spread that herd immunity only requires relatively few people catching the disease. - 3) As for guilt? Kids have been spreading the flu since forever, I don't think there's any more reason for blaming a kid for a coronavirus death than for last year blaming those kids for flu deaths, there's just slightly more deaths now.CoryUsar (talk) 00:30, 30 July 2020 (UTC) - @CorruptUser I can't believe I need to say this, but you cannot compare seasonal influenza to Covid-19. In any fashion. Seasonal influenza has vaccines, has decades of historical study, and although highly infectious tends to not be fatal (.01% in the US). Covid has no vaccine, six-ish months of study, and is highly infectious as well as being at least 10 to 15 times more fatal. We cannot gamble children's lives like this. Masks are a duh, but class sizes need to be way smaller (before my mother died in 2017, her third grade class had 32 kids, physical distancing was impossible), remote learning must be an option, and there must be preparation for full remote learning if there is an outbreak. We quite literally cannot afford to fuck this up.RipCityLiberal (talk) 15:50, 30 July 2020 (UTC) - You can compare anything to anything. I absolutely can compare apples and oranges; oranges are better for adding to mixed drinks, apples can be turned into booze directly. The question is whether the comparison is actually useful; you can compare the nutritional value of carrots to steak, but it wouldn't make sense to compare King Lear to toenail clippers. As both are spread in the same manner and have similar symptoms, it does make sense to compare COVID and Flu. In fact, you already did compare them, as I will be doing further. - The mortality rate of the seasonal flu is on average .1%, not .01%. The mortality rate of COVID is on average .5%, making it about 5 times as deadly. But I agree that that's not the biggest problem... - You are correct in that there is no vaccine. This is, yes, the real issue with COVID. While anywhere from a third to a half of people get flu vaccines each year, and more importantly the people who are the most socially interactive with the vulnerable (nurses, doctors, etc) are more likely to get the vaccine, barring any actual conspiracies, absolutely no one had a vaccine for COVID-19. Thus, unmitigated, the disease would spread incredibly rapidly, and far more people would get COVID than would get the flu. - "Gambling children's lives" is absolutely a thing we've been doing since forever. Otherwise, schools wouldn't have existed before the Polio or MMR vaccines, yet, they did, and often in more unsanitary conditions than today. If the lockdown is put back in place, and the government collapses entirely (a remote but very real possibility), a lot more children are going to suffer than from COVID. Those free lunches don't just appear out of nowhere, nor do their teachers' salaries, nor the bricks assembled into an elementary school. "Think of the children" is a phrase used by people who usually haven't been thinking of the children at all. CoryUsar (talk) 18:51, 30 July 2020 (UTC) - The comparison literally has no function. It isn't like apples and oranges, it's literally a disease we know, study, and have a general grasp of how it works, versus one we do not. I admit mistaking flu mortality rate, but you are also off for Covid by at least a factor of 10.[5] Your implication that I am being disingenuous about my concern is frankly insulting. There are two factors that generally determine a functioning society; children in schools and sports entertainment. Presently the US cannot do either effectively. The collapse of government (which is frankly absurd, federalism insulates virtually all Americans from anarchy) is entirely because of the failure to control the virus. It didn't need to be this way, in every single way the Federal response has been a failure, and because of that children cannot return to school the way they were before. Rushing to get this semblance of normality back, when the pandemic is accelerating, isn't just dangerous, it's irresponsible. And you have failed to refute the underlying argument in all my statements; Kids will get infected with Covid. There will be outbreaks, kids will die, kids will fatally infect their parents, teachers and friends. And then we will have to stop completely and refocus our resources to address those outbreaks, instead of taking the time now to control the current outbreak so schooling can return next year in some form. The financial numbers we received today [6] make it even more important, we get this right the first time.RipCityLiberal (talk) 20:04, 30 July 2020 (UTC) - You are way, way off in terms of mortality. The rate you cited was the case fatality rate, not the actual mortality rate. The key difference is that the CFR is only from confirmed cases, and thus excludes the asymptomatic people or those with minor symptoms who never got tested in the first place. My original cite that I used for estimating the death rate of people under 65 puts the overall rate at 1.4%, not 6% as your cite does. More importantly, that citation is a bit outdated and it turns out to still be a massive overestimate. What you want is the infection mortality rate, not the case fatality rate. The current CDC estimates of the IFR are between .5% and .8%, with a best estimate of .65%. The center for global development puts it at .7% for the US. The Lancet puts it at around .66%, though this cite is positively ancient coming from March. It's possible that the CDC and others are in on some conspiracy, but I generally doubt that. CoryUsar (talk) 21:34, 30 July 2020 (UTC) - Grand Opening, Grand Closing.[7][8] -RipCityLiberal (talk) 22:00, 3 August 2020 (UTC) - The real problem with children getting sick is that for the most part, children CAN'T be isolated from their families. 200 kids getting sick means 200 families getting sick. That's 800-1000 people, possibly more depending on the area, and a lot of those are going to be among the most vulnerable. You are right that "kids will infect and kill others" is a strong argument, strong enough to support the reduction if not outright temporary closure of entire school districts. The argument that "kids are going to die in droves", however, is not quite as strong. CoryUsar (talk) 20:05, 4 August 2020 (UTC) - Never was concerned about droves of children dying now, the issue as always has been and should be: - We don't know enough about how the disease affects children - We don't know enough about how children spread the disease - We don't have an effective strategy of testing, tracing or isolation - Schools do not have enough resources to create a virus free enviornment - Children in the US do not yet need to return to school in any large fashion. -RipCityLiberal (talk) 21:57, 4 August 2020 (UTC) - I think we know enough about how the disease affects children, and how they spread it. However, I absolutely agree that we don't have any effective strategies on this (or anything else, these days), and also that schools don't have the resources for, well, nearly anything they need even without a pandemic. As for the need to return to school, well, I get the impression that if the pandemic goes on much longer, Gen Z is going to be permanently educationally damaged from this. Yes yes, remote learning blah blah, but that's just not the same. We are consciously making the decision to sacrifice Gens Y and Z in order to protect Gen X and Boomers. Again, we are in a world where there are no right answers, merely least-awful answers. CoryUsar (talk) 22:14, 4 August 2020 (UTC) - Considering that Gen X and Boomers are in charge, and currently fucking everything up I'd say this is mostly accurate. Remote learning isn't good enough, but that's more a resources being unequal problem, then an everyone learns enough problem. Anyway, in Oregon, no schools are coming back until January at the earliest.-RipCityLiberal (talk) 23:38, 4 August 2020 (UTC) I tried to decipher this[edit] Thinking that there was some grand point to be made about reality, but the first line kind of blew that thought up. I don't know why some assume what happens during a drug fueled experience has some insight about reality. I tried to read through it but it made no sense at all.Machina (talk) 23:28, 2 August 2020 (UTC) - I'm not going to read that wall of text but I will say that in my experience psychedelics give the sensation of epiphany, truth, and realization without necessarily giving you those things-Hastur! (talk) 23:44, 2 August 2020 (UTC) - It's true that drugs can help to escape some of the filters that help humans make sense of the world (or at least perceive it through different filters). In that sense, yes having a psychedelic experience can help you understand reality better...but not in the way that some say. That is, a difference sense of reality is not "more true" but that the very experience of seeing the world through different filters should give you insight into the fact that everything IS experienced through many filters in the first place and it ought to help you see what "truth" means. I would say a good psychedelic experience is just as useful as a good course in metaphysics/ontology or a very good work of art/literature/theatre/cinema that tries to demonstrate how filtered our experiences and construction of reality are. ShabiDOO 00:32, 3 August 2020 (UTC) - This was a methamphetamine experience. There is nothing psychedelic about methamphetamine. Psychedelics target the serotonin systems (such as 5HT2A, the primary receptor of LSD / mushrooms / etc.). MDMA is a stimulant that also targets the serotonin system. Methamphetamine does not. The text is tweaked word salad made by repeating "deep" words like "abstract", "reality", etc. I had fun with pasting the text in a Markov chain text generator.] It gave me "deep" lines, like "That we understand thought in itself in asking that it know can be may being with idea has and the other paradoxes" that made as much sense as the original poster. It made me want to put the text on a soap bottle. Soundwave106 (talk) 03:29, 3 August 2020 (UTC) - I’m not a scientist or whatever (just a druggo) so I might b wrong but I’m p sure meth is slightly serotonergic as well isn’t it? I heard that’s also part of the reason that it’s Legit Neurotoxic (like MDMA vs., say, regular amphetamine). That’s also why higher doses and/or low tolerance can sometimes give meth a vaguely enactogenic feel to it. 203.111.4.57 (talk) 14:07, 3 August 2020 (UTC) - What I find from Googling seems to suggest that methamphetamine does damage the serotonin transporter neurons. But papers I find like this suggest methamphetamine has no role for the 5-HT2 (serotonin) receptor, which is the classic "psychedelic" target. Of course, science is a living process so the information is subject to change. Soundwave106 (talk) 19:32, 3 August 2020 (UTC) - im not quite sure what the purpose of the distinction being made here is. the average drug user will be using psychedelics simply to mean acid and mushrooms etc. they wont be classing drugs on what biological systems they hit but on the kind of high they produce and the what they want from a night out. if you want a more psuedo spiritual experience you wont be reaching for a meth pipe. no one smokes t and expects mad visuals they'll be smoking t to be able to fuck for 24 hours solid. maybe throw in a little k or g for kind of speedball effect. you'll not likely have any kind of epiphany smoking t or visit a higher plane of existence, but make no mistake meth is a seriously mind altering drug, and no one ever has picked up a pipe and thought this will end well. - oddly though, after a few days of debauchery, i'll struggle putting a sentence together and i'll look like golem, but ive found im super good at the crossword in that state. swings and roundabouts AMassiveGay (talk) 23:13, 3 August 2020 (UTC) - The biological action drives the high, and I tend to think that way. That's just me. It helps you understand why LSD and mushrooms are similar-ish experiences, for instance, and helps you understand recent phenomenon like "spice", "bath salts", etc. Certainly my level of understanding isn't enough to actually invent new compounds, but some people are at that level (mostly making medicine, but occasionally making recreationals), and on the medical end, to give an example (COVID-19), when it comes to potential treatments, I'd certainly place more bets on, say, someone who knows what ACE-2 is than someone who thinks Bill Gates created COVID-19 to depopulate the planet. - From a "high" perspective, from what I've seen in trip reports, the quasi religious experience comes from two main classifications of drugs: psychedelics (LSD, mushrooms, but also including others like mescaline and DMT) and dissociatives (ketamine, DXM, MXE). To some degree, entactogenic stimulants (MDMA) give a bit of that effect too, but not as much... although entactogen stimulants exist that hit serotonin more (Vice apparently wrote last year that 2-CB is kind of getting popular, surprisingly, and this is one of them)... so "your mileage may vary". - If a stimulant doesn't hit serotonin, you can't call it psychedelic. Therefore those who value "psychedelic insights" will not find a lot of value in a tweaked out meth rant. Some in the beginning of this discussion were comparing a meth session to a psychedelic experience, and it's not. The closest equivalent to the "meth experience" would be those that have done some Adderall (amphetamine), as meth works similarly. (Only there is no danger with Adderall of getting any impurities, so you won't experience any shitty impurity side effects.) Soundwave106 (talk) 16:33, 4 August 2020 (UTC) Lol, there's only one way for you to find out, and you'll discover that one of the sides is right. You can recontextualize it however you want. HairlessCat (talk) 14:43, 3 August 2020 (UTC) - No I'm pretty sure it's just nonsense that seemed profound at the time but when you write it down it's nothing new, special, or even that smart and can often be wrong. In short you shouldn't trust people who had drug experiences about any sort of revelation. I asked for a translation to see what he meant by his words but I guess that's not really needed.Machina (talk) 01:43, 5 August 2020 (UTC) Trump interviewed on Axios[edit] This world is proper fucked, with cretins like this at the helm and their ribald, frothing supporters at the stern. Good lord, it's nearly as car crashy as Prince Andrew saying he doesn't sweat and loved Pizza Express Cardinal Chang (talk) 08:19, 4 August 2020 (UTC) - Swan tries so hard to lead him to show even a shred of human decency or compassion, and every single time he chooses to obfuscate, assign blame or self-praise. He has blood on his hands, and he can't even acknowledge there might have been any sort of failure.RipCityLiberal (talk) 16:49, 4 August 2020 (UTC) - It's getting to the stage where I feel bad about mocking the afflicted. But, he didn't care about doing so himself, so fuck 'im. (To this day I am still surprised how his description of Serge Kovaleski did not kill his political aspirations outright and immediately.) Cardinal Chang (talk) 18:19, 4 August 2020 (UTC) - Not that I do mock the afflicted. It's just that mocking Clownface Von Fuckstick is indeed heading into mocking the afflicted territory Cardinal Chang (talk) 18:21, 4 August 2020 (UTC) - It's been a while (maybe 2 - 3 years) since I've watched an entire Trump interview. Jesus Christ that was painful to sit through......--NavigatorBR (Talk) - 00:31, 5 August 2020 (UTC) The interview reminds me of an "all gas no breaks" or early louis theroux episode. Junfa (talk) 01:05, 5 August 2020 (UTC) - I had to wait till the end of the of the interview and watch the credits with my fingers crossed, hoping Armando Iannucci's name would appear as creative consultant or scriptwriter. Honestly, it's one depressing interview. Narcissism meets positive thinking (is there really much of a difference?) it's the new earnest half-wit in comedy character creation. Cardinal Chang (talk) 09:23, 5 August 2020 (UTC) Something interesting I noticed on the state election ballot[edit] Each August here is Michigan there is a vote for either state reps, county level officials and local millage's. During this type of election there is no splitting the ticket between parties as always. Now here is where is gets interesting- on the Democrat side of the ballet almost all the proposed reps had more than one candidate. On the Republican side there were no other choices for reps or county workers. Have Republicans become so lazy that they cannot offer more than one candidate for state elections? How does a political party get so lazy that they cannot be bothered to have more candidates? Unless there is some sort of ulterior motive? Either way it is just sad. --George Soros Puppet (talk) 21:37, 4 August 2020 (UTC) - It is not implausible that the locla Republican organization met in some kind of caucus ore even an informal meeting and doled out the candidacies to avoid splitting the Republican vote while allowing the Democrats to split theirs. Smerdis of Tlön, wekʷōm teḱsos. 00:16, 5 August 2020 (UTC) - It's also common for both parties to not put much effort into winning elections in seats they consistently lose. The skew of national partisan politics often make local elections downright unwinnable for one party. It's my opinion that this fact generally increases corruption a lot. ikanreed 🐐Bleat at me 15:12, 5 August 2020 (UTC) - Fun part, the state rep for Michigan has kept his seat for years. He is also a Republican with no other Republican candidates but worse yet, the democrat candidate almost always loses. I can smell corruption from miles away. That was my thought yesterday at the polls. --George Soros Puppet (talk) 17:26, 5 August 2020 (UTC) When your sword in minecraft breaks and you are forced to defend yourself with a shovel[edit]— Godless Raven talkstalkwalkbalk 🌹 02:14, 6 August 2020 (UTC) - he should've accepted salvation 196.53.0.186 (talk) 06:37, 6 August 2020 (UTC) - Trident Drowns should be nerfed! The Sqrt-1 talk stalk 13:23, 6 August 2020 (UTC) - Wouldn't be so easy if this was a leaping great white. HairlessCat (talk) 14:09, 6 August 2020 (UTC) - @Sqrt-1 Yeah the Trident Drowned are a nightmare. Before they existed I could safely pass a night on a boat, now it's suicidal to do so. — Godless Raven talkstalkwalkbalk 🌹 15:07, 6 August 2020 (UTC) Feedback appreciated[edit] Help_talk:Manual_of_style#Vertical_A-Z — Godless Raven talkstalkwalkbalk 🌹 20:36, 6 August 2020 (UTC) Concentration camps in China[edit] — Godless Raven talkstalkwalkbalk 🌹 17:25, 30 July 2020 (UTC) - The world needs to take a stand against the Chinese government's human rights abuses.-Hastur! (talk) 17:27, 30 July 2020 (UTC) - It seems to me that the US, Russia, and China all need to be roundly condemned and held to account by the rest of the world, but considering how much military and economic power each of the three hold in comparison to everyone else, I'm not going to hold my breath. I'm not sure which way the correlation goes, if being at the top of the power heap leads a state to be awful or if being awful leads to being on the top of the power heap, probably a complex inter-relationship, but anyway. Regardless, I only have so much energy for so many causes, so I'm focusing on holding the US to account from the inside for now. Still I certainly support stamping out authoritarian violence wherever it is found. Glitch (talk) 17:48, 30 July 2020 (UTC) - I don't think that'll ever happen, since these 3 countries are Great Powers and these 3 have never trully felt accountable for any of the shitty things that they've done. Also, good luck trying to make Putin feel sorry and kick Xi Jingpin from his dictatorial throne. Gunther1987 (talk) 19:21, 30 July 2020 (UTC) - The US might have bigger problems. ☭Comrade GC☭Ministry of Praise 21:43, 30 July 2020 (UTC) - That they do. One of our reporters who reports (yeah, that's a sentence) for America (I'm European) had an interview with some MAGA's who literally claimed that if Trump doesn't win the elections, another civil war will break out. Just what is it with the US and Wars? Gunther1987 (talk) 22:26, 30 July 2020 (UTC) - I grew up in a conservative household in the 80s, and they've been saying there's going to be a new civil war if a Democrat gets elected for literally every election since I can remember. It's just what they do. I'm pretty sure one is coming, but not from those blowhards. Glitch (talk) 22:55, 30 July 2020 (UTC) - The only way that the US can even have a chance to lead the world again for human rights, is to get the orange fuck out of office. He literally doesn't care.RipCityLiberal (talk) 23:44, 30 July 2020 (UTC) - Given that tRump personally encouraged Xi to build Uyghur reeducation camps,[9] I think 'actively opposed to human rights' would be a more accurate characterization than 'literally doesn't care', particularly since there are quite a few other examples of tRump violating humans rights, e.g. refugee child separation and imprisonment in the US. Bongolian (talk) 00:33, 31 July 2020 (UTC) - Trump also praised the Tiananmen Massacre as an act of “strength”. Chef Moosolini’s Ristorante ItalianoMake a Reservation 00:51, 31 July 2020 (UTC) - It shouldn't end with Trump out of power. He's just the end point of the process, its most obvious manifestation. No, the corruption must be ripped out, root and branch. Else it'll just happen again, and the next guy might be smarter. ☭Comrade GC☭Ministry of Praise 01:22, 31 July 2020 (UTC) Just out of curiosity, how exactly is the world going to pressure China to stop torturing minorities? The Chinese officials are murdering prisoners for organs not because they want to have organ-throwing contests, but because they or their families need an organ to survive, a small boycott won't change their mind. I'm not sure how credible this source is, but supposedly Uyghur women are being forced to marry Han men, and given the lack of women in China due to poorly thought out social policies, well, I don't think a boycott is going to be enough to convince the Chinese government to stop making minority men "disappear". CoryUsar (talk) 01:42, 31 July 2020 (UTC) - Unless there's been another source, the only ones claiming that China is stealing organs are the right-wing cult Falun Gong who believe God sent Trump to destroy communism. I'm not saying that means they're wrong (about organ stealing, pretty sure they're wrong about Trump), and China sure isn't trustworthy either, but I'm not inclined to take their word for it. They just lack that certain credibility, you know? Glitch (talk) 02:40, 31 July 2020 (UTC) - "Just out of curiosity, how exactly is the world going to pressure China to stop torturing minorities?" The other two major world powers can't, Russia is an ally and about 50K people died in Chechnya in the 1990's, so they don't give a hoot about this stuff. The USA is too economically intertwined with them to condemn this stuff. China now has real "soft power" in the USA. An enormous number of companies changed their policies, donated billions to BLM, fired people, and pledged support to political causes over the death of one man, George Floyd. No such dissent or activism is possible in China, and for American firms that want access to that giant Chinese market, one peep, and they could be cut off. You want to broadcast the NBA in China, show a Marvel movie, make sure your patents are protected? You don't criticize what you aren't supposed to. It's really quit a good system if you're a dictator. China has its domestic situation on total lockdown with nothing getting in it doesn't want and can at the same time exercise soft power in the USA and other nations. My family grew up in the USSR and we're witnessing China pull off what the KGB and Soviet hierarchy could have only dreamed of. Neo Stalinist (talk) 03:13, 7 August 2020 (UTC) - There was that China tribunal thing which claimed it was happening to the Uyghurs, not just the Falun Gong. Here's an earlier, different report. - I don't particularly care for the Falun Gong either, but if we only care about human rights for people we like, we don't really care about human rights in the first place. CoryUsar (talk) 02:58, 31 July 2020 (UTC) - I'm not saying that at all. I'm saying that when I looked into it only a few days ago, it LOOKED like every claim ultimately sourced back to the Falun Gong, via people taking their word for it. Did I come to the wrong conclusion? Maybe so. Could I have been intentionally fooled? Definitely. But your first link is to somebody's blog that's just hosted on Forbes, I think. In any case they claim the China Tribunal as their source. That source ultimately leads to the Falun Gong and the Epoch Times, their English propaganda wing. Your CNN link only says that some OTHER people claim it's happening--people who have ties to the Falun Gong, if you look into it. If it's real, and it could be, of course it's abominable and should be stopped. But it might be nice if ANYONE not tied to the Falun Gong claimed to have any evidence at all. Glitch (talk) 03:32, 31 July 2020 (UTC) - Here's an article from way back in 2006. Basically, China admits that they harvest organs from executed prisoners, so long as the prisoner signs a written consent form. If you believe those forms are legit, I have a bridge you might be interested in. Here's an old, old article from HRW, from the mid-90's, before the Falung Gong had any real power. If you are wondering why these sources are so old, I've been Googling and excluding anything involving the words "Falun" or "Epoch", and since the Falun Gong are allegedly the source of most of the organs these days, well...CoryUsar (talk) 05:10, 31 July 2020 (UTC) - I think you are ascribing to me some sort of faith in the Chinese government that I assuredly do not have. I don't trust them at all--but I also don't trust the Falun Gong. And, in light of the frequent false positives about what horrific things "the Chinese" are doing that turned out to be nothing but Western right wing fever dreams, I'm very skeptical about the whole thing. Is it happening? I have no idea. I can say that if I was the Chinese government and I wanted to steal organs from somebody, I would pick a group who had serious credibility issues of their own in hopes no one would believe them. But that doesn't mean I trust the guy in the alley about the CIA microchip in his head, either. Consent form or no consent form, it's obvious China has the ABILITY to take organs from anyone they can get their hands on. Some ability to hush it up, too. But that isn't proof they're murdering people FOR their organs. The organs could well be nothing but a nice bonus. Frankly if they're going to be killing people anyway, I'd rather the organs go to somebody instead of rotting in the ground. - Although honestly the numbers the Falun Gong are talking about strike me as awful low, even taken at face value. A few ten thousands over a couple decades? If I was China, I wouldn't even get out of bed to murder fewer than a million dissidents and steal their organs. More of a nuisance than its worth, especially with having to hear Western human rights groups nagging me about it forever after. If this is the worst they're doing right now, maybe we should just call that a blessing. But maybe I'm more pessimistic about China than you are. - More than anything I'm saying, until we have much better verification, I'd prefer we stick to the awful things we KNOW China has already done or is doing, rather than what they MIGHT be doing. By we, I mean those of us with no investigative power to look into it for ourselves. If you're involved in a human rights group that can get you into a Chinese prison to look for evidence of (more than usual) wrongdoing, by all means take a look. Just try to make sure you come back with all your parts. Glitch (talk) 06:22, 31 July 2020 (UTC) - Corrupt user asks, "how exactly is the world going to pressure China to stop torturing minorities?" - See Global Magnitsky Act (Sadly, Wikipedia does not have a Global Magnitsky Act article, but the basic premise of the law targeting Russian oligarchs was extended to apply against Iranian Ayatollahs, the Chinese Central Committee, etc., as well. The law was just invoked against the CCP entity controlling Xinjiang, as explained in this short vid where 17% of the world's ketchup and other commodities come from. nobsTo Bob Mueller:Every dog has his day. 18:12, 7 August 2020 (UTC) - Incidentally, what a coincidence that the Independent China Tribunal released it's final report on March 1, 2020 (they announced in June 2019 it would be released on that date) just weeks after its findings were obscured by the release of covid on January 23, 2020. nobsTo Bob Mueller:Every dog has his day. 18:23, 7 August 2020 (UTC) [edit] ." I'm pretty confused here. Disinformation is information that is intentionally incorrect... IE, lies. Isn't it? Are they just talking about mixing accurate information with lies to give it more of the appearance of credibility? The article implies that somehow the Russian could "gain" valuable disinformation from hacking the Biden campaign, and share it with Trump. If the information is accurate, then it's not disinformation. Right? Glitch (talk) 19:33, 2 August 2020 (UTC) - We're long past the point where narratives need to be cohesive to be pushed in the media or believed by much of the public. 192․168․1․42 (talk) 19:55, 2 August 2020 (UTC) - I mean, yes, although you would be hard pressed to support the position that humans of the past were smarter or did more critical thinking in general. As a species we've been deeply stupid from the start. That's why what we do here to counter that is so important. I'm just confused as to what they're even trying to say. I can write it off as nonsense, but I don't learn much from doing so. Glitch (talk) 20:00, 2 August 2020 (UTC) - Given the rest of the article, this looks more like poor phrasing than anything else. ☭Comrade GC☭Ministry of Praise 21:19, 2 August 2020 (UTC) - "I'm just confused as to what they're even trying to say." It's stringing together talking points to score goals for the favored political team. In this case, I'd say it's of the "preaching to the choir" variety intended to strengthen support rather than to convince unaligned people. Any factual content is beside the point, and though it may be nonsense, it's important to keep track of what narratives are being pushed, since that tends to influence actual policies. And this sort of thing is a reversion to normalcy. Naked partisanship and advocacy has been the default state of "news" media for nearly its entire existence. The conditions underlying a brief period of relative trustworthiness in the US have changed, so we don't get to have that nice thing any more. - And it's not a phrasing issue. The underlying problem that Glitch pointed out (an incoherent conceptual basis) is there. This has been a recurring issue with Russia-related "hacking" narratives. 192․168․1․42 (talk) 19:48, 7 August 2020 (UTC) The best political compass test by far.[edit] I got specked as a syndicalist, see here: Spekr — Oxyaena Harass 23:15, 2 August 2020 (UTC) - Some of those are kinda weird. "Access to abortion should be regulated by the government," for example. I think all medical services ought to be subject to regulation. Another one was about the government needing to be transparent. Very few people, regardless of their political position, are openly against government transparency, at least in the developed world-Hastur! (talk) 23:23, 2 August 2020 (UTC) - Another one asks for respect of private property rights. Are we distinguishing here between capital and private property?-Hastur! (talk) 23:26, 2 August 2020 (UTC) - Aannd another question conflated civil forfeiture and eminent domain. Final thought: this website design is kind of a pain. Maybe this was meant for phones/tablets?-Hastur! (talk) 23:29, 2 August 2020 (UTC) - "Libertarian socialist" oh dear. Chef Moosolini’s Ristorante ItalianoMake a Reservation 23:37, 2 August 2020 (UTC) - Had trouble using the website on my laptop due to its design though. Chef Moosolini’s Ristorante ItalianoMake a Reservation 23:38, 2 August 2020 (UTC) - Apparently I'm a social democrat, which will make Godless Raven happy. However social democrats apparently oppose "most private property rights and most uses of money." Anybody want to take bets on the chances that this quiz was designed by a libertarian? -Hastur! (talk) 23:42, 2 August 2020 (UTC) - Yeah, not a big fan of that political test. Chef Moosolini’s Ristorante ItalianoMake a Reservation 23:44, 2 August 2020 (UTC) - Poe's law? Because that was the most amusingly bad and biased political compass test I've ever seen. And the worst implementation of responsive design I've ever seen, too. At least half the questions were impossible to answer as an anarchist. Libertarians really don't understand Anarchism... Dendlai (talk) 00:27, 3 August 2020 (UTC) - Has Oxyaena secretly been a libertarian this whole time?-Hastur! (talk) 00:31, 3 August 2020 (UTC) - I also agree that a few of the questions were ambiguous, vague or confusing. I ended up much less to the left and to the libertarian side on this compass than with other compasses (-62, -49). I also really wish that these compasses would stop using the term libertarian per the "freedom" slide of the scale. Libertarianism as a term is so heavily loaded with people whose ideology tends towards a conservative side of the spectrum and radical free-market principles that using libertarianism, even in the 2D scale, is very very confusing. ShabiDOO 00:35, 3 August 2020 (UTC) - Oxy is an anarchist that really likes to defend Cuba, China, USSR, etc. Make of that what you will. (If you don't believe me: go to pages we have on these dictatorships and see who editwarred there.) — Godless Raven talkstalkwalkbalk 🌹 00:37, 3 August 2020 (UTC) - Also, I did that test some time ago but I got "libertarian socialist" (-65 economically, -31 culturally). I guess I have to defend Cambodia now. — Godless Raven talkstalkwalkbalk 🌹 00:40, 3 August 2020 (UTC) - According to that test, I'm a centrist. Honestly, I preferred the other one with all the questions about sex and religion. At least those are things I;ve got opinions about. I found all those questions about property and trade boring. Spud (talk) 11:49, 3 August 2020 (UTC) - You're an idiot, Raven. — Oxyaena Harass 14:06, 3 August 2020 (UTC) Template:Verygood When are you going to debate Jar, an actual socialist? @Oxyaena — Godless Raven talkstalkwalkbalk 🌹 14:19, 3 August 2020 (UTC) - why is the saloon filled with "you're an idiot, raven"?Fowler (talk) 14:22, 3 August 2020 (UTC) - Because it's oxy, she is upset because I challenged her to debate an actual socialist (who is strongly critical of Cuba and other Communist regimes); she backed out. — Godless Raven talkstalkwalkbalk 🌹 14:27, 3 August 2020 (UTC) - @Oxyaena Do you still think that this is the best political compass test by far?-Hastur! (talk) 14:33, 3 August 2020 (UTC) - @GR} You didn't challenge me to do shit, you had Em pull me into a discussion I did not want to be in *multiple times*, to "debate" someone I didn't even know, and wouldn't leave me the hell alone. — Oxyaena Harass 17:02, 3 August 2020 (UTC) @Ze You were there. Oxy backed out from debating an actual socialist (Jar), right? — Godless Raven talkstalkwalkbalk 🌹 17:13, 3 August 2020 (UTC) - Let's assume, for the sake of argument, that what you are saying is 100% true, GR. What does it matter? What is your goal in fighting with Oxy? I really can't see what either of you have gained out of this little feud, it looks lose-lose from where I'm sitting. Glitch (talk) 17:28, 3 August 2020 (UTC) - I know you are new here glitch, but if you knew GR and his pattern of talkpage/saloon bar edits better you would realize starting pointless drama with users he perceives as being to the political left of him is at absolute least 50% of what he does.-Flandres (talk) 17:41, 3 August 2020 (UTC) - That's hardly the case. He has a bit of a grudge against some users who dogpiled him when he first joined the site, that's all-Hastur! (talk) 17:55, 3 August 2020 (UTC) - You're insufferable, Raven. And, Hastur, that's far from the truth as to what originally happened. I don't even know the guy, I was pinged out of nowhere, I left because I was, again, in no mood to "debate" someone I didn't even know, and was also mourning, you dumb prick, and you wouldn't leave me alone afterwards. You had Em invite me twice to something I wanted no part in in the first place. — Oxyaena Harass 18:16, 3 August 2020 (UTC) - Okay, so there may or may not be bad blood, maybe it's one sided or may be not, but what I'm asking is... What is the POINT? What goal is being worked towards? Isn't pointless bickering in many ways the very opposite of the mission here? Can we not try to move past it? Yes we're all humans and when we're attacked we want to strike back in revenge, but it's not like we can do enough damage here to actually dissuade each other from attacking again in the future so that revenge would have some kind of purpose... It just makes things worse for everyone, and I can't stress this enough, it's detrimental to our mission. Glitch (talk) 18:17, 3 August 2020 (UTC) - There really isn't a valid "point." The "goal" is more or less some childish sense of fulfillment derived by "pwning" a user you happen not to like. That is...pretty much how this site de facto works, or at least the parts of it where users can talk to each other.-Flandres (talk) 18:30, 3 August 2020 (UTC) - Well, maybe. Certainly I considered that scenario. But I would like to hear those involved explain what they're trying to accomplish, in their own words, rather than assuming or ascribing motivations to them. No one likes to have others put words in their mouth, and it's really bad for trying to get to the actual truth of the matter. To clarify, all of this is value-free. I'm not saying it's morally wrong to bicker. I'm saying it's wasteful and inefficient and that alone is sufficient reason to try and put a stop to it, unless it's fulfilling some critical need that I'm not seeing. Glitch (talk) 18:44, 3 August 2020 (UTC) - If you still want an answer to your question, @Glitch, let me know on my talk page. I will happily explain the context to you. — Godless Raven talkstalkwalkbalk 🌹 15:37, 7 August 2020 (UTC) Something I didn't know about Marx[edit] In other words, Marxists & ML's worship an anti-semite who came up with this shit? And I thought communists were terrible... Gunther1987 (talk) 18:02, 3 August 2020 (UTC) - @Gunther1987 You might want to read the discussion on the talkpage. ☭Comrade GC☭Ministry of Praise 18:06, 3 August 2020 (UTC) - What a jerk that Marx was! I've always had mixed feelings about the guy. He authored an enormous body of work and had clear intellectual pursuits that rival any of the great thinkers in history. At least some of his ideas were motivated by genuine concern for working people and forwarding human progress. But, upon the discovery of an admittedly hostile biography, "The Red Prussian" I had to concede that Marx, the man, was a pretty odious lout in his personal life and held some fairly bad political views. He alienated almost everyone around him, was unhygienic, egotistical, moody, often crass, bad with money, and endlessly mooching. None of this disproves his ideas, they stand or fall on their own merits. Likely his worst sin, although historically controversial, is that he probably impregnated his own maid(who he very ironically may have never paid) and then denied paternity to the child by blaming the whole thing on Engles. Neo Stalinist (talk) 03:39, 7 August 2020 (UTC) - The racism bit could definitely use more nuance and information. And yeah, he was definitely an anti-semite. Hardly the most rabid one, but that doesn't excuse him-Hastur! (talk) 18:14, 3 August 2020 (UTC) - Speaking only for myself, as a socialist, I take everything he wrote with a grain of salt. He didn't invent socialism and he certainly isn't the sum total of thought on the subject. And Lenin and later Stalin's interpretations of his theories are progressively more and more dubious. Taking anyone's word as gospel truth is foolish, all the moreso if they lived in the 1800s with all the cultural baggage that entails. That said, he was undeniably brilliant, and a good deal of what he said holds up today as a wonderful diagnosis of the ills of capitalism. His prescription of communism is a lot less solid, even though I think socialism in general is a good treatment plan for now. Yes, you're right, a European man from the 1800s was racist. That's hardly surprising, and not directly relevant to the bulk of his work. Glitch (talk) 18:26, 3 August 2020 (UTC) - @Hastur Personally, I'm not surprised that a European man from the 1800s was anti-Semitic, given that Europe only began to address its deeply entrenched anti-antisemitism after the 1930s, and continues to struggle with it today in some areas. ☭Comrade GC☭Ministry of Praise 18:34, 3 August 2020 (UTC) - @Gunther1987 There is worse, and only because @Oxyaena is editwarring AGAIN it isn't shown, but check out: (it is sourced and all) [10][10].! — Godless Raven talkstalkwalkbalk 🌹 00:13, 4 August 2020 (UTC) - That quote alone isn't good enough. You referenced a paper with a far more detailed breakdown of Marx and Engels' racism on Talk:Karl Marx and that would make a far better basis for calling him a racist-Hastur! (talk) 00:15, 4 August 2020 (UTC) - By all means document his racism, and the fact he was probably an asshole too. People who find that relevant ought to know about it. Personally, I always ASSUMED he was both a racist and an asshole, so when you claimed such, I really didn't doubt it. I just don't find it relevant to the bulk of his writings. Proving someone is a racist asshole is a completely different thing than proving their economic and political theories wrong. I mean the vast majority of people, even important thinkers, that lived before say 1900 were morally radioactive by today's standards. That doesn't make them WRONG. Sure, acknowledge their awfulness. Even Lincoln was hella racist. But isn't saying "Marx was a racist asshole, therefore Marxism/ML is incorrect" a textbook ad hominem? Again... I am not a Marxist and for damn sure not a ML. Glitch (talk) 00:27, 4 August 2020 (UTC) - It doesn't matter how hawkish Hillary Clinton's foreign policy is, nor how corrupt her campaigns are, only that we remember to yell "Benghazi" and "Emails" on cue. ☭Comrade GC☭Ministry of Praise 00:57, 4 August 2020 (UTC) — Godless Raven talkstalkwalkbalk 🌹 01:54, 4 August 2020 (UTC) - Okay? I'm not sure why you're trying to convince me of something I already told you I believed before you even asserted it. I really don't care if you add all of that to his article, as long as it's properly siloed away from the things he said that actually mattered. He wasn't influential because of his views on race. An ad hominem fallacy is not making INACCURATE statements about someone's character. It's making IRRELEVANT statements about their character to refute their arguments. Sure, maybe you could make a case that his racism in some way makes his writings on economics and politics incorrect--I don't see how, but in principle maybe you could. Do you intend to? Otherwise it's a cut and dried ad hominem... Surely you see that? Glitch (talk) 02:25, 4 August 2020 (UTC) - Now, Marx's support of the British effort in the Crimean War(1853-1856) is starting to make sense. Neo Stalinist (talk) 03:58, 7 August 2020 (UTC) So you agree that Marx was a virulent racist? — Godless Raven talkstalkwalkbalk 🌹 02:29, 4 August 2020 (UTC) - Sure, I don't know why I wouldn't. Glitch (talk) 02:31, 4 August 2020 (UTC) - Literally none of this surprises me. I just think it's largely irrelevant beyond "A guy from a time period where racism was widespread was was racist." In other news, water is wet, but that doesn't tell me whether this particular body of water is safe to drink. ☭Comrade GC☭Ministry of Praise 02:43, 4 August 2020 (UTC) - Also Raven, please respond on the Communist Manifesto talkpage. I'm not going to ping you every time I respond, as I don't think that would be polite. ☭Comrade GC☭Ministry of Praise 02:45, 4 August 2020 (UTC) - Holy shit. - Also, I thought Oxy was going to stop editwarring after she got desysoped (I probably misspelled that), so she could get her tools back in a few months? Gunther1987 (talk) 15:37, 5 August 2020 (UTC) Cuomo Begs Fleeing New Yorkers To Return From Connecticut, Hamptons After Revealing Top 1% Pay 50% Of State Taxes[edit] Andrew Cuomo begs fleeing New Yorkers to return Ffom Connecticut, Hamptons after revealing Top 1% pay 50% of State Taxes. Pathetic. — Unsigned, by: 2001:8003:59db:4100:d017:4320:36a2:ac90 / talk - LOL Daily Wire. Here is a CNBC link for those who actually know what capital gains are, which apparently Ben Shapiro does not. - (Incidentally, my initial thought on the New York proposal, which based on the CNBC article is a "mark-to-market" yearly unrealized capital gains tax above a certain level, is a terrible idea. I do personally believe realized capital gains should be taxed at ordinary income rates, and do think that in general all the bullshit shuffling around corporations and rich individuals do to avoid taxation needs to be clamped down on. But this IMHO seems way more discouraging of investments in productive assets at first glance, it's not the right focus.) Soundwave106 (talk) 22:02, 5 August 2020 (UTC) - Well, people are already leaving the large cities and are buying properties in the suburbs and exurbs. After a brief pause due to the Great Recession of 2007-8, the suburbanization of America continues. The Wuhan flu merely speeds things up. I personally do not think people mind paying high taxes. After all, the New York City metropolitan area is home to about 20 million people, making it one of the largest in the world. However, people, quite reasonably, I might add, expect good public goods and services in return. That means effective law enforcement (read safe neighborhoods), reliable firefighting, quality public schools, dependable public transportation, among other things. Capital flight is a real phenomenon. If you make your place disagreeable, people will leave, starting with the rich, who can do so the easiest. Nerd (talk) 22:12, 5 August 2020 (UTC) - Daily Wire is unfettered shit.RipCityLiberal (talk) 22:20, 5 August 2020 (UTC) - Umm, last I checked, people were moving back into the cities. That's what Gentrification is; rich people moving out of the 'burbs and back into the cities. Funny how people complained about white flight when the rich people left, and now complain about rich people moving back in, really, rich people should just stop moving anywhere, apparently. CoryUsar (talk) 01:56, 6 August 2020 (UTC) - Yeah, I was never really clear on how both could be horrible expressions of racism (white flight I could see, given the redlining, but there's no income ceiling on moving anywhere). Reminds me of the joke headline, "World to End Tomorrow: Women, Minorities Hit Hardest". The Blade of the Northern Lights (話して下さい) 02:10, 6 August 2020 (UTC) - I guess the concern of this is that housing becomes too unaffordable for those of lower income. This happens to often be minorities in urban areas, but I'm not sure that this alone is important enough to be a "racist" thing -- I would say, for instance, the same income issues also applies to artists, who also often are attracted to lower rent areas, know no race or gender boundaries, and sometimes form part of the reason people are attracted to "gentrify" an urban area in the first place. It is probably possible on a community level to craft policies to help longtime residents stick around and thus benefit economically from gentrification (someone determined that whether people mostly rent or own property matters a lot here, so that could be a focus). Keeping older residents around probably would also help maintain the "soul" of a community; actually, the main complaint I've heard about gentrification is that the soul of the community is lost. Soundwave106 (talk) 02:44, 6 August 2020 (UTC) If anyone who doubts people are leaving the cities in large numbers, please read this whole section from Wikipedia. Check the sources if you are skeptical or want to learn more. Again, please read the whole thing. In my opinion, the only problem with 'gentrification' is when buyers, especially those from overseas looking for a safe destination for their money, are not really looking for a place to live for any significant part of the year but only as an investment which they later sell to somebody else. Land is a special commodity in the sense that its total amount is generally fixed. Such phenomenal demands, as can be seen, for instance, in Vancouver, distort the market at the expense of the locals. Other than that, gentrification is actually beneficial because financially successful people are moving in and settling down with their families, providing the local authorities with more taxes to fund their services. People tend to like living in nice neighborhoods, so more will move in. That could help the city revitalize itself. As for the so-called 'white flight' phenomenon, it is commonly observed. Demographer Eric Kaufmann noted, "Minorities will move into relatively white areas, but whites generally do not move into strongly minority areas. Whites have, and will, tend to move toward relatively white areas." More here. Many non-whites prefer white-majority neighborhoods, too. Makes sense if you think about it. Immigrants would not have come to white-majority countries had they hated being near white people. What I also find interesting is that even those who tout the virtues of multiculturalism and ethnocultural diversity reportedly do not really believe in what they say when it comes to buying a house in a neighborhood with quality public schools. People generally being among their own kind. Here, I am using the word 'kind' in a rather broad sense. Race may or may not be relevant. Look at your own social circles, for example. In this case, people like living among themselves and among well-off white people. Nerd (talk) 05:28, 6 August 2020 (UTC) - And then that's where the problem of gentrification making areas unaffordable for anyone but the wealthy and privileged. This shit reads like an apologia of gentrification, which has many genuine problems. — Oxyaena Harass 17:11, 6 August 2020 (UTC) - No one is entitled to somebody else's property or fruits of labor. You get what you pay for. If you dislike the deal, walk away. I don't have a problem of relatively wealthy people move into my neighborhood. It shows me that where I live is desirable. If I were living in a proverbial crime-infested Third World slum, they would not be interested. Having people like those moving in benefits the entire neighborhood, as I explained above. More funding for public schools, firefighting and police departments, better public infrastructure, safer streets, more well-off people moving in. The place as a whole becomes a better place to be. Nerd (talk) 19:09, 6 August 2020 (UTC) - What a horribly spooked point of view, I highly recommend reading Proudhon. First off, all property was stolen from someone else, either by being parceled out of the commons via fiat or seizure from the indigenous. Second off, where would they go? Throw them out onto the streets? That seems to be what you're suggesting, all of what you say is good and all, but it's exclusionary to the privileged class. Where will the less well-off go? — Oxyaena Harass 19:44, 6 August 2020 (UTC) - Everybody lives on land their predecessors fought over. This does not mean the people living today have no right to ownership. The moment you deny the right to property that moment you sow the seed for social chaos. The concept of historical claims is as ludicrous as the attempts by the Chinese Communist Party to seize more land and maritime territories from their neighbors. It requires you to give special importance to a certain time in history. I cannot just go to your place and demand you let me stay because somebody fought over the piece of land you now live in on the past. That's nonsense! In case you did not know this, people have been leaving the cities for some time now. (Please see the Wikipedia section I linked above). Why have they been moving? Among other things, high costs of living and high taxes. If you cannot afford to live in a place, go elsewhere. Find a cheaper place. You are entitled to your own fruits of labor and property, not someone else's. Nerd (talk) 19:51, 6 August 2020 (UTC) - I did, actually. Out of the places that have become too expensive for them. The final location is for them to decide. It is after all their lives, so they have to take responsibility for them. You can't just sit there and demand a house or an apartment. People should seize control of their own lives. Nerd (talk) 20:04, 6 August 2020 (UTC) Some of us have had to move because we do not like the current place. It seems to me a fact of life. Don't like it here? Go somewhere else. Nerd (talk) 20:33, 6 August 2020 (UTC) - @GrammarCommie You deal with this liberal. — Oxyaena Harass 20:49, 6 August 2020 (UTC) - You don't have an inherent right to live in any specific place. CoryUsar (talk) 22:59, 6 August 2020 (UTC) - @Nerd What if I can't because I'm too poor? What if I like where I live, and I just think those with more should contribute more? @CorruptUser And you don't have an inherent right to money, or to force someone to live somewhere else. ☭Comrade GC☭Ministry of Praise 00:55, 7 August 2020 (UTC) - So, we agree? CoryUsar (talk) 02:38, 7 August 2020 (UTC) - Probably not, given the content of your earlier posts. ☭Comrade GC☭Ministry of Praise 12:04, 7 August 2020 (UTC) - I think it depends on what you mean by an inherent right to money. If you have money, or property, you have a right to it. The government can't simply take it away from you without fair compensation, that's literally in the constitution. We needed an amendment before income could be taxed. Property is a bit different in terms of tax, it's yours, but you are using services so it's only fair that you pay tax to pay for those services. In terms of inherent right to it, if you don't have money or property, the government isn't under any obligation to simply give it to you. We give people some bare necessities for numerous reasons, but we aren't required to. In terms of where you live, you don't have a right to live in, say, The Hamptons. If you can't afford to live there, you don't get a house there. Government can't force someone out to let you in, at least not without fairly compensating the prior homeowner. You can't be forced by law to live in a specific part of town, but if that's all you can afford, no one is violating your rights if you live there. - Gentrification is a bit weird, as it creates some perverse incentives. Let's say some poor people actually band together and decide to make their community a mini paradise. They do the dirty work, kick out the gangs and drug dealers, get rid of the homeless, clean the place up. Then the rents rise. So they kind of have to avoid making the place better than they can afford, unless EVERY neighborhood decides to do this and there aren't enough rich people to move in. You end up with issues if a rich person can own many, many homes instead of just one, but the smart thing to do would be to simply charge exorbitant taxes on non-primary residences so that everyone else gets lower taxes or it makes first-home ownership that much cheaper. - However, that doesn't mean gentrification should be illegal. - Do we disagree on anything? CoryUsar (talk) 12:38, 7 August 2020 (UTC) - "If you have money, or property, you have a right to it." No you don't. Both of these things are granted to you at the whims of the state, and these can be revoked at any time. Money especially is not yours, it belongs to the national government under which you live, and is lent to you for use. It's the same with private property, ultimately. These are things that the state apparatus lends to you, not things you have any inherent right to. As to gentrification, this concept is very much tied to systemic racism and the ongoing disenfranchisement of black people in this country. You said " Let's say some poor people actually band together and decide to make their community a mini paradise. They do the dirty work, kick out the gangs and drug dealers, get rid of the homeless, clean the place up. Then the rents rise.", yet you failed to see the whole picture. The black people existing in large numbers in that neighborhood is part of why it's so poor. Further, crime is downstream of poverty in almost all of these neighborhoods. In essence, black people are disenfranchised, thus leading to poverty, thus leading to an uptick in crime to augment their income so they don't lose their homes and/or to escape the slums, which is then used to argue for disenfranchising them further. Gentrification is not merely urban development, but borderline ethnic cleansing (note I said borderline), in that it seeks to remove a specific ethnic group, for sole purpose of replacing them with another. Finally, to address the original topic, a 50% tax on the wealthy is adorable. FDR set it at over 90%. ☭Comrade GC☭Ministry of Praise 13:09, 7 August 2020 (UTC) - 1) Uh, no, property rights (and thus, money as well) are in the constitution. If a right guaranteed by the constitution is subject to the whims of government, then rights as a concept are utterly meaningless. - 2) Neighborhoods aren't poor simply because they have black people. There have been numerous communities of minorities that achieved wealth without the help of Mighty Whitey, heck, that was what the Tulsa massacre was about. - 3) Poverty being the main source of crime does not explain why rich kids commit crime as well, often at similar rates. Not always the same types of crime, but surprisingly, most drug dealers aren't actually from the lowest echelons of society. Really, the biggest difference between poor and rich kids is money, it's middle class kids who are obsessed with obeying the law because unlike poor and rich, middle has something to lose and will lose something. - 4) Gentrification is "borderline ethnic cleansing"? Really? That's about as asinine as insisting that white people were the victim of ethnic cleansing when they were forced out of the cities in the 60's. Heck, you'd have a stronger case there, as the increasing crime really was violence forcing people out. - 5) Gentrification does not remove an ethnic group, but a socioeconomic group. Rich black people move in too, even if they are fewer than rich white people. Unless you can show me where rich black people have been forced to leave by equally or less rich white people, you are high on your own supply. What I can show you, however, is an actual case of ethnic cleansing of Afromericans by illegal immigrant gangs. Long story short, drug cartels want that sweet sweet drug money and don't give two shits about whether or not a black person is actually competition, it's easier just to chase absolutely everyone out and not take any chances. - 6) The 91% tax bracket was basically a joke. Barely anyone was actually in that bracket, and there were so many ways around it (e.g., my Jaguar and Gulf Stream are actually owned by my company, etc) that few actually paid it, it was mostly for show. Imagine if tomorrow we enacted a 99% tax bracket on incomes of a trillion dollars or more, that wouldn't do jack. CoryUsar (talk) 16:00, 7 August 2020 (UTC) About a person who is a thorough anti-communist but is classified as "Libertys" and "Left of Reason"[edit] I'm not sure how to use it, but I'll post it on this page. Some people, like Harry Truman and John F. Kennedy, are anti-communist but classified as "left-wing." I don't think all anti-communists are right-wing and don't hit the left. Harry S. Truman is the president of the atomic bombing Mainland of Japan (Hiroshima and Nagasaki, Atomic bombings of Hiroshima and Nagasaki) and should be classified as Crimes against humanity. Jimmy Carter is also an anti-communist, though he has a bad reputation from conservatives such as Ann coulter. In the first place, during the Cold War, both Republicans and Democrats were conservative parties. Nelson Rockefeller became synonymous with Republican moderates as "Rockefeller Repabublican", but he is an anti-communist. he is not left-wing Michael Bloomberg, who was classified as Rockefeller Repablican, later tilted to the right. Classifying them as "left" or "liberal" is like classifying the anti-communist Democratic Social Party, which was originally separated from the Japan Socialist Party, as left-wing.— Unsigned, by: Karasawa Takahiro / talk / contribs - You can be left wing and anti-communist even anti-socialist. I don't see a problem here or why it's a mod issue tbh. — Z 15:51, 6 August 2020 (UTC) - ^ she is right. I consider myself to be left-wing and also anti-Communist. — Godless Raven talkstalkwalkbalk 🌹 16:41, 6 August 2020 (UTC) - Pretty sure being left wing means being "anti-authoritarian" which would make you anti-communist.RipCityLiberal (talk) 17:09, 6 August 2020 (UTC) - @RipCityLiberal You're conflating Marxism-Leninism with communism, as an anarcho-communist I beseech you to correct that error. — Oxyaena Harass 17:15, 6 August 2020 (UTC) - @Oxyaena Even as I typed this I realized an error, it should be instead directed towards Stalinism, Maoism, Putinism and the CCP.RipCityLiberal (talk) 17:24, 6 August 2020 (UTC) - I suppose this whole thing would depend on how you define left wing. Personally, saying you are "left wing" only really says you (nominally) favor labor over capital, rather than vice versa. The intricacies of this quickly explode into a kaleidoscope of opinions, some bad, some good. As an anti-capitalist, and anti-Marxist (I'm critical of Marxism as a collected work, though I think he had some good ideas here and there), and anti-authoritarian, I am (obviously) aware of these intricacies. ☭Comrade GC☭Ministry of Praise 18:06, 6 August 2020 (UTC) — Godless Raven talkstalkwalkbalk 🌹 19:15, 6 August 2020 (UTC)— Godless Raven talkstalkwalkbalk 🌹 19:15, 6 August 2020 (UTC) - @GR You ignore the fact that there has been an active anti-Bolshevik tendency among the left, specifically among communists, since before 1917. Great quotes you got there from a guy who has barely any knowledge of communist theory. — Oxyaena Harass 22:56, 6 August 2020 (UTC) One of the problems with defining both "left" and "right" is that you first need to define a "centre" to which you can be left and right of. Unfortunately the centre moves depending on which area of the world you consider along which period of history. Obviously there are some things which will almost always define left and right such as labour and capital but much of the debate about left/right is pretty subjective for the reasons I've mentioned.Bob"Life is short and (insert adjective)" 09:25, 7 August 2020 (UTC) - On any particular issue there isn't a true straight line, e.g., you could want to legalize abortion but only to reduce the amount of interracial babies (not a farcical example, it's Nixon's view and thus indirectly the reason for Roe v Wade), you could want mandatory abortions of the mentally disabled, you could want fully legal and accessible abortions prior to the third trimester, you could want it only up to 11 weeks (Germany), you could want it heavily restricted and onerous to get one but occur at any stage, etc. "Left" and "Right" only exist because in general, you need to get as many allies as possible in order to get something relatively close to you want, and the only way to do so is by getting the biggest faction possible, meaning there's only room for 2 sides. CoryUsar (talk) 13:24, 7 August 2020 (UTC) - One of the problems of defining a "centre" is generally it can be occupied by people who are apolitical, without any defining political characteristics who are easily persuadable by family friends, media, and entertainment. These "Centrists" generally go unrepresented. nobsTo Bob Mueller:Every dog has his day. 17:55, 7 August 2020 (UTC) - I don't think the plasticity (i.e. the agreeableness) of people is an issue with the political axis classification; normally, there are two kinds of people who have an issue with the axis: - Extremists who want to over-represent themselves onto others (e.g. fascists, communists, socialists, anarchists, Nazis, etc.) - People who have legitimate issues with reductionism in politics and the arbitrary nature of classifications. — Godless Raven talkstalkwalkbalk 🌹 18:44, 7 August 2020 (UTC) - "Extremist" is a loaded term, and you're still lumping in anarchists with Nazis. Jesus Christ. You do realize that these two "groups" you've created are not mutually exclusive, right? Also I see you're still incapable of admitting you're wrong regarding the existence of the anti-Bolsheviks amongst the left, since before 1917. — Oxyaena Harass 20:32, 7 August 2020 (UTC) - I'm not talking to you anymore, @Oxyaena. You declined to debate a real socialist when I offered you one and people like @Shabidoo will complain about me if I even address you. So I ask Shabidoo to contain Oxy or something, I don't wanna interact with Oxy (because I will inevitably be blamed if she has a meltdown) and will try my best to not interact with Oxy. Good night. — Godless Raven talkstalkwalkbalk 🌹 20:40, 7 August 2020 (UTC) GR, I wouldn't start bitching about other people acting out or asking others to contain them until you show that you are able to do it yourself, which you haven't shown much in the last few days. The only thing that has changed is your frequency of being insufferable, not the intensity of it when you do. You've actively provoked Oxyana on several occasions this week and now you're playing the little persecuted victim who needs to be protected from her. As you may have noticed I don't defend most of what Oxy says or does, I have only called you out when you've been a dick to her. As is no surprise to anyone, some people harass the shit out of her, something that can go well beyond the colorful or surprising things she does and says. I would agree if you are incapable of interacting with a user without being a dick, then by all means do it...disengage. Just don't, while you are at it, ping the user, challenge the user, goad the user or initiate or participate in any drama whatsoever with the user. ShabiDOO 21:14, 7 August 2020 (UTC) - Cool, will remember. Let's see what happens if I ignore Oxy. (Spoiler: She will still accost me everytime and everytime someone will accuse me of being 'provocative'). — Godless Raven talkstalkwalkbalk 🌹 21:29, 7 August 2020 (UTC) How many active users are on the site?[edit] Just new and wondering really. — Unsigned, by: Junfa / talk / contribs - Signature please. As for the number of users, I have no idea. --George Soros Puppet (talk) 01:10, 3 August 2020 (UTC) - There's a tool for it but it appears to be broken-Hastur! (talk) 01:13, 3 August 2020 (UTC) Just wondering because I don't want to get into flame wars on public record! I guess I should just be careful typing or go back to lurking, anyway. Wonderful site even if I didn't get off to the best of starts! Junfa (talk) 01:19, 3 August 2020 (UTC) - Been a user for a while and I got off on a pretty bad start myself. Just be civil and avoid senseless arguments. I have been in your shoes. --George Soros Puppet (talk) 01:47, 3 August 2020 (UTC) - Go to Special:Editcount, leave the username blank, select "All" for the month, "2020" for the year, and 200 or so for "return users in top." That will give you an idea of the number of active users this year so far. —cosmikdebris talk stalk 01:50, 3 August 2020 (UTC) - If I read it correctly the 500th most active user in 2020 has 7 edits Aloysius the Gaul 03:12, 3 August 2020 (UTC) - (Checks own stats) Huh, I have 428 edits. 214 of them in 2020 and a 183 of them last year... (Side note, what's the difference between "Main" and "Project" pages?)--NavigatorBR (Talk) - 05:36, 3 August 2020 (UTC) - Just different namespaces. — Godless Raven talkstalkwalkbalk 🌹 08:35, 3 August 2020 (UTC) {{ns:0}}:, {{ns:1}}:Talk, {{ns:2}}:User, {{ns:3}}:User talk, {{ns:4}}:RationalWiki, {{ns:5}}:RationalWiki talk, {{ns:6}}:File, {{ns:7}}:File talk, {{ns:8}}:MediaWiki, {{ns:9}}:MediaWiki talk, {{ns:10}}:Template, {{ns:11}}:Template talk, {{ns:12}}:Help, {{ns:13}}:Help talk, {{ns:14}}:Category, {{ns:15}}:Category talk, {{ns:16}}:, {{ns:17}}:, {{ns:18}}:, {{ns:19}}:, {{ns:20}}:. Seems like it stops after 16. — Godless Raven talkstalkwalkbalk 🌹 08:53, 3 August 2020 (UTC) - how do we define active users anyway? Vorarchivist (talk) 17:59, 8 August 2020 (UTC) Help with Coast to Coast AM “Area 51 caller”[edit] Long story short, my anxiety has been spiking like hell (probably due to the lockdown and having more free time) and caused relapse into old fears. In essence, I’m asking for any help kind of explaining to me why the coast to coast AM radio broadcast is bullshit. I know it’s bullshit, I have all the evidence it’s bullshit, but my dumb monkey brain needs confirmation from people I hold in a high esteem (i.e. RW). The basic rundown is that in 1997, some guy called in to allege he was an ex-area 51 employee, said that aliens are extra dimensional beings, and that they’re working with the government to control the population or something, then the broadcast cut off (video in question) Later, I’m 1998 a guy called in saying that it was him and it was a hoax. He even does an impression of the frantic call which is spot on. The video of the second broadcast starts at 5:30 of the video. One would think that that was enough but the true believers weren’t happy with that and came up with a bunch of wild theories about how it’s a cover up, it’s not the same guy, it’s aliens that imitated his voice etc. Etc. Their evidence is that 1) the voices don’t sound alike or 2) that the voices sound too much a like (something that I can’t wrap my head around) and 3) that the voice analysis proves that those two are different people. I’ve searched long and far and couldn’t find any proof of that alleged voice analysis. Scare theatre did a good job of analysing the video and provides a sceptical outlook on things, also found this reddit post with many people saying that essentially it’s a hoax. In my opinion, the voices sound identical, I spent hours continually playing the clips side by side and the voices sound a like. It feels like people saying that they don’t sound alike is just wishful thinking and cognitive biases. But yeah they sound very alike to me. So all the pieces are there, but somehow I cannot shake off the anxiety of the alleged aliens wanting to control the world, so I asking is someone would be able to help with just doing a quick logical and coherent debunk of this? I guess I’m afraid of the idea of extra dimensional beings wanting to take control, which sounds very stupid when I write it out (because it is) but we already have established that my brain is stupid. Also I’d like to know why people say a voice analysis proved this if there isn’t even one? I’m really sorry about this honestly, I feel like a fucking broken record at this point, but as a way of saying thank you, I could make the page both for this and that other piece of shit anxiety fit I had the other month? Let me know if that’d be valid. But yeah, I’m sorry about being a pain and any help is greatly appreciated, if there’s anything I can do in return to show my appreciation please let me know.—WMS (talk) 17:01, 4 August 2020 (UTC) - Elaborate coverups tend to not be falsifiable in the end. Every point of evidence raised against a coverup just indicates that the coverup was on a greater scale than previously assumed-Hastur! (talk) 17:05, 4 August 2020 (UTC) - A Google of the current psychological thinking on alien experiences suggests that the people most susceptible to alien belief score highly in schizotypy personality and also are open to new experiences. I wouldn't call it a "stupid" brain. The schizotypy type proposal is like the autism spectrum, in that its bad in its worst cases (schizophrenia), but it is also linked to positive characteristics such as high creativity in smaller doses. And being open to new experiences is *not* a bad thing. Unfortunately it is a personality type linked to paranoia and anxiety issues as well, that's the negatives of this particular spectrum. Something to be aware of. - The logical debunking of this is more just to say what Area 51 is. Area 51 is well known to be where the military designs top secret experimental aircraft. Due to the number of engineers and scientists involved over many decades, in my opinion, if something was actually "extra-terrestrial", we'd know about it. Conspiracy theory types generally take dystopian views of aliens, but science and engineering types often have a more positive view of extra-terrestrial life (think the Star Trek crowd). Frankly I find it inconceivable that there is any we would *not* hear of signs of extra-terrestrial existence at first from them, even if the net was negative in the end. - The real conspiracy is to some degree, working conditions might have been shitty and the government may have fucked up the environment. The general story I've heard is that the UFO rumors got started when they were testing some of these planes, some of them (like the Lockheed U-2 and the Lockheed F-117 Nighthawk) looking relatively unusual. The military didn't mind because the alien UFO thing was a "useful distraction" from the real work going on there. So, if you want to entertain a notion, fancy a Area 51 engineer, bored of working on Boeing YF-118Gs all day, maybe drunk, calling up poor old Art Bell and pulling a little prank on his listeners. Sounds more plausible than the caller's tale, at least. Soundwave106 (talk) 17:51, 4 August 2020 (UTC) - There are many, many reasons why the general claim the US government has proof of the existence of aliens is super dubious, all of which makes this particular more specific claim even more dubious than that. However, let me walk you through a very simple argument to put your mind at ease. - If a whole major military base like Area 51 was dedicated specifically to working with aliens, the US President would almost certainly know about it even if it was Need To Know since it would be relevant to many things the president does. If a US President revealed to the people of the world the existence of aliens, that president would go down in history as one of the most significant people to have ever lived. Donald Trump could not possibly resist such a temptation, no matter how dire any possible consequences of the revelation might be. Therefore if there is such proof, the US President is not informed of it, which is extremely unlikely, therefore the claim as a whole is extremely unlikely. Glitch (talk) 21:52, 4 August 2020 (UTC) - Edward Snowden said he couldn't find anything about aliens. HairlessCat (talk) 12:46, 5 August 2020 (UTC) - That's an interesting piece of information to chew on Soundwave, I've been quite susceptible to anxiety and paranoia from a young age and my family had have had similar experiences with anxiety so I'll definitely have a look into the schizotpy personality as it may be of important help to understand my brain. But honestly, thank you all for these logical arguments, they're very helpful and have managed to calm me down. Thank you very much, I'm hoping to use all the knowledge, energy, logic and paranoia to help RW. Thank you.--WMS (talk) 14:03, 8 August 2020 (UTC) Maybe I can get a job digging plague pits[edit] The poor planning at reopening schools is already leading to mass COVID-19 infections. Give it time and a new viral strain will possibly show up. The more infections there are means the increasing chance of mutation. --George Soros Puppet (talk) 14:57, 6 August 2020 (UTC) - Infections are one thing but what we really should be concerned about is the fatalities. Only those who are the most vulnerable -- the elderly and those with pre-existing conditions -- should be quarantined. Healthy adults and children should be allowed to roam freely as they choose, with social distancing and masks in crowded and confined spaces, of course. It seems that people overemphasize infections and neglect the possibility of herd immunity. How on Earth would you build up herd immunity if you do not allow healthy people to get infected? People will eventually need to return to work and to school. Nerd (talk) 15:50, 6 August 2020 (UTC) - Pre-existing conditions? Like being diabetic and/or overweight? There's the majority of the anti-mask protestors in the US fucked then.Cardinal Chang (talk) 16:27, 6 August 2020 (UTC) - {Edit Conflict} You continue to make this argument and it is just fundamentally false. The argument is not that we don't want people to work or school, the point is to limit infections of people to: 1)Try not to overburden the health system and 2) Stop the spread from children to adults. Without the ability to get test results in a reasonable time (48 hours max), trace infected people's recent contacts, and quarantine infected people, America will not get control of the virus. One of these school situations, the parents sent the child to school while waiting for test results. In another 116 people were exposed to an infected person, assuming each person was in close contact with 10 people, trying to trace and contact over 1000 people is a herculean task where there are likely only a few dedicated contract tracers. And if children get infected, they have to quarantine at home, with their parents who also need to quarantine. What is the difference between that situation and where we were before? Besides now possibly a family unit is exposed to a dangerous virus. This idea of herd immunity is also so outlandish, primarily because it would likely condemn 2-5% of the population to death, and it would require at least 60% of the population to get infected and recover. How exactly are hospitals supposed to support tens of millions of people sick at the same time, not to mention what is that going to do to the economy when tens of millions more people aren't working because they're sick. Everyone who believes this pipe dream should just admit; they are OK with millions of preventable deaths, just to not wear a mask.-RipCityLiberal (talk) 16:30, 6 August 2020 (UTC) - If you read what I wrote, I support wearing masks in crowded public places. Unless somebody manages to produce a commercial vaccine soon, our best chance of getting out of this mess is herd immunity without it. Staying indoors for long will only wreck out mental health and our economy. According to this tracking board from John Hopkins University, out of 4,852,749 people infected, 159,407 were killed, or 3.3%, compared to 3.8% for the whole world. Places like Canada, Mexico, Spain, Italy, France, Belgium, and the United Kingdom are doing worse than the U.S. And don't forget the people who got infected but show no symptoms and have never fallen sick. Even in countries that aggressively test people, the number of individuals infected is probably higher than the number of confirmed cases. Overall, infections and fatalities were on their way down, but then came the protests and riots. If people could manage to stay calm and practice social distancing and where masks in crowded places, things could have gotten better. But somebody had to throw temper tantrums so here we are. - Deaths from the Chinese novel pneumonia are preventable if we practice social distancing, wear mask in crowded places, and carry on as calmly as possible. It will not go away any time soon. For that to happen, either somebody produces a commercial vaccine, herd immunity is achieved, or the virus expires. The first and third possibility seem beyond our reach, but the second is achievable if we are careful. Living in fear is not the way forward. Nerd (talk) 19:03, 6 August 2020 (UTC) - First, it's Covid-19, not whatever racist nickname you garbled there. Second, to achieve herd immunity you would needs 70% of the population to be infected and recover from the virus.[18] That is upwards of 260 million Americans that would need to be infected. Even if we assumed the most charitable fatality rate, .01%, that's over 3 million deaths. Is that really a stance you want to take, kill 3 million people for the rest of us to live without "fear"?RipCityLiberal (talk) 20:03, 6 August 2020 (UTC) - Have you heard of the Spanish flu, Lyme disease, German measles, Japanese encephalitis, the Stockholm syndrome, the Ebola virus, the West Nile virus, the Middle Eastern respiratory syndrome (MERS), the African swine flu, among other names? Nothing 'racist' there. You use that word but you don't know what it means. Like I said, actual infection numbers will always be higher than reported or confirmed cases. Are we sure a large chunk of the human population has not already been infected? The way forward is not fear and paranoia but rather caution. There is a difference. We should gradually and carefully re-open things while quarantining the most vulnerable, who are generally not young children and young adults but rather the elderly and those with pre-existing conditions. You are talking about percentages yet you seem obsessed with raw numbers. Percentages tell a more nuanced story. Yes, hundreds of thousands of people have been killed around the world and well over ten million got infected. But there are more than seven billion people. The human population won't crash. Most people will survive. As I stated above, the U.S. is doing better than average, nothing to be ashamed about. America's neighbors and some other major economies are doing much worse. A better future will only come if we walk towards it. Nerd (talk) 20:13, 6 August 2020 (UTC) - I am astonished no one has shit on you in the six months this pandemic has dragged on, because everything you just said is wrong and requires only a cursory web search to destroy everything you wrote. Yes, your stupid pun is racist. Spanish Flu was first detected in the United States, not Spain. But in 1918, the American news media failed to adequately inform the public, instead taking their talking points from politicians. The Spanish media was the only group reporting the truth.[19] Ebola gets it's name from a river near where the first cases were discovered in 1976. Pretty sure everyone just says measles, encephalitis and swine flu. The others probably should have a name change, but that is neither here nor there. Only racists specifically say "China Flu", the point being to blame Asian people for the disease, that has resulted in several racist attacks.[20][21][22] - Yes I am quite concerned with numbers, because numbers inform decisions, pretty sure percentages are also still numbers. If I am understanding your argument correctly, you don't just want herd immunity for America, but the planet, which is just so insane it's bordering on genocidal. If the fatality rate was at .01%, which again is extremely generous, you are condemning 70 million people to death. That would be catastrophic.That is the entire population of Thailand, the UK France and Italy. And that's just deaths from Covid-19, assuming everyone was infected around a similar time frame (say 3 months), worldwide ICU capacity would be completely maxed out. 96 countries have less than 5 ICU beds per 100,000 population.[23] What about all the other things that kill people, they haven't just disappeared. Cancer, stroke, heart disease would still be killing people on the regular. - There is virtually no metrics that indicate the US is handling this pandemic well. The US accounts for roughly 4 percent of the world population, but accounts for nearly a quarter of all cases. The US accounts for a fifth of all fatalities. Florida, a state with 21 million people, had more cases than the entire EU combined,[24] and twelve times the number of Australia (25 million) and South Korea (51 million) combined.[25] - Maybe we do need a new name for this disease, Trump Flu. He seems to be the one fucking all of this up for everyone.-RipCityLiberal (talk) 21:45, 6 August 2020 (UTC) - More specifically concerning the 1918 flu pandemic, the reason it was first reported in Spain and received the wholly unfair misnomer "Spanish Flu" is that most of the western world was involved in WW1 and information about an epidemic that might be harmful to the morale was hushed up. Essentially there was no free press back then. The flu started almost certainly in Kansas (in one of two possible military bases) and moved on troop ships to France and Belgium, both of which were also very much involved in the war and hushed it up. Spain was the first neutral country it got to, and the press there was free to report it. - So Nerd, either start calling it a "Kansas Flu" and admit that the most deadly pandemic in modern history started with Americans not washing their hands after shoveling chicken shit[citation NOT needed] (PIDOOMA based on the actual fact that it was an avian flu [26], or better yet stop applying national signifiers to pandemics. You racist wanker.Coigreach (talk) 23:21, 6 August 2020 (UTC) - First off, for fuck's sake, the Kansas story is mostly bullshit, we aren't sure where it originated but it had already begun in Europe in March 1917, 10 months before the outbreak in Kansas. No one knows for certain exactly where it started, but it wasn't 1918 Kansas. - Second, also FFS, I don't know how often I have to reiterate this but the actual mortality rate from COVID is .6%. Not 3%. Not 5%. 6/1000. It's dangerous because it spreads so quickly and severe cases can cause permanent damage, not because it's particularly deadly. More importantly, we don't have enough space in our hospitals for everyone at once, so if too many get sick, people that would've otherwise survived are simply left to die. - Third, number of cases is absolute bullshit. Not all countries are doing adequate testing (including the US), but if you look at deaths per capita, the US comes in 8th. Not exactly good, pretty awful in fact, but behind a lot of other countries which supposedly are better. However, again, the deaths are somewhat bloated, as someone that has both terminal cancer and COVID will count as a COVID death. (EDIT, can't confirm hospitals outright lying about COVID). Elsewhere, Iran, Russia and China are lying through their teeth about how many have died. - This disease is far from over, but whatever it is we do, everyone will after the fact insist they knew what we should have done.CoryUsar (talk) 03:04, 7 August 2020 (UTC) - @CorruptUser You can't have this argument both ways. Mortality is likely way lower than .6%, I used .01% to put it in line with the Flu. Percentages though allow people to hide behind the actually human cost. If .6% of the American population died over night it would be catastrophic. If .6% of the world population died over night, you're talking about entire countries becoming mass graves. Herd immunity is more than just a pipe dream, it is death sentence.RipCityLiberal (talk) 15:28, 7 August 2020 (UTC) - First off, Flu has a mortality of .1%, not .01%. Second, most of the people dying are already sick. Some may have lived a few years more, a few maybe a decade or so, but it's rare for someone both young and healthy to simply die. It's a terrible disease, but keep in mind that this disease is actually less deadly than most of the diseases that we simply just put up with back in the day. Whooping cough kills 1 in 200 children and thus is dozens of times as deadly as COVID. Measles is twice as deadly; the lower reported mortality rate is only because as the absolute fastest spreading disease, just about everyone had it as kids. Diptheria is absolutely awful, killing around 8% of those who catch it. Mumps only rarely killed people, but it often caused complications. - This is absolutely not an endorsement of COVID. The point is that COVID is not "new" in terms of the type of threat that we have faced before, it's actually much milder than most of those types of threats. The world that we left behind thanks to the efforts of Jonas Salk, Robert Hilleman, and all the other vaccinologists? COVID is merely a shadow of that world. COVID is tragic, but if it's as you say "catastrophic", then we as a society has grown too complacent. If anything, this is a horrible reminder of the world the Anti-Vaxxer crowd wants to bring back, we have been in a war with diseases for millenia and we need to call out those Quislings for who they are. However, we have faced these sort of threats before, much worse threats, and often several at once and survived. And we will survive again. CoryUsar (talk) 17:05, 7 August 2020 (UTC) - All of those diseases you mention are preventable. And it is awful that we have just accepted that people die in large numbers. Again, you cannot keep hiding behind percentages, what is the number, how many people will die from something we can prevent? In the US, between 24,000 and 62,000 people die from the flu. Worldwide 160,700 children die from whooping cough.[27] All of these deaths are preventable, but because they generally only accept poor countries no one cares. In the eight months Covid-19 has spread across the globe, it has killed at least 711,000 people. In the US, Covid will likely be the third most common cause of death this year.[28] Stop trying to normalize your genocidal predisposition.RipCityLiberal (talk) 17:23, 7 August 2020 (UTC) - WaPo put together a good tool for you to try your her immunity idea. .6% fatality rate = 1.2 million deaths to achieve 60% immunity [29] - on deaths per capita - the us is vast and full of wide open spaces. taken as a whole, its population density is relatively low. if per capita deaths arnt too bad its because of more sparsely populated areas lowering the number. looking at state by state, per capita deaths are through the roof in some places, corresponding with the more densely populated states. seeing as many states are larger than most european countries, its probably a better comparison, especially as there has been so much divergance in response state by state. all these stats though arent always really directly comparable for alot of factors. that said, excess mortality rates can give a clearer picture thre impact as it will include deaths not just directly attributed to covid itself, but everything surrounding it. russia's excess mortality rate is significantly higher than deaths attributed to covid alone. i am reluctant to draw any firm conclusions on any of this even now until the dust has finally settled, especially on doing worse and for what reasons. except maybe for the most blatant fuckheadedness. there is alot of that going around though AMassiveGay (talk) 17:45, 7 August 2020 (UTC) - Digging plague pits is for somebody with just a GED or less. If you have reasonable computer skills, you can get hired as a contact tracer with access to the NSA's FISA database. nobsTo Bob Mueller:Every dog has his day. 17:46, 7 August 2020 (UTC) - @Rip Those diseases are preventable today, they were not preventable a century ago. Again, I'm not endorsing COVID. As for "normalizing" it, everyone you know and love will die. Every last one. Life is a terminal condition. We can't simply stop living because we might die. If the country and economy collapses, guess what? A fuckton more people will die than from COVID. We invaded Iraq, and by June 2006 the Lancet estimated we had killed 500,000, not from bullets or bombs or even violence, but because the entire country went to hell and people couldn't see their doctor, the electricity was out for weeks at a time, plumbing was a pipe dream, food was a memory, etc. If the country collapses, and it very well could, well, you get the idea. - That "60% needed for herd immunity" is misleading. You don't actually need a random 60% of people to get COVID, you just need the most connected people to get it. The reproductive rate is an average, with a few people both spreading the disease most rapidly and being the most likely to catch it. NYC achieved herd immunity months ago with something like only 30% of people having gotten it. That's still more than half a million deaths, which admittedly, is scary. Even adjusting for age and health, that's still going to be the equivalent of 100-150,000 average people. - Once again, my recommendation is "make masks mandatory, limited opening of economy". Something that can be done indefinitely. Now, if we know for a fact that a vaccine/cure is a month away, of course we shut down hard and wait it out. But we can't shut down hard and wait another month, and another, and another, for years at a time. We can however wear face masks forever, just like we now bury the dead instead of leaving them for the scavengers, or flush our poop instead of leaving it in the field. It may be an issue regarding masks in a public park or sidewalk, but there's nothing illegal about being thrown off a bus for refusing to wear your face mask properly. We just have to be willing to be confrontational enough to do so, like the good ol' days when kids used to beat the shit out of you for fashion faux pas (yes that actually happened). CoryUsar (talk) 19:17, 7 August 2020 (UTC) Regarding herd immunity, coronaviruses in general don't produce particularly robust long-term immune responses. It's looking like SARS-CoV-2 antibodies fade on the scale of a few months, so herd immunity is not a particularly viable option, even via a vaccine. Especially since there has never been a successful human coronavirus vaccine for various reasons. Prevention via exposure management is probably going to be the main thing going forward, at least if DRACO doesn't get funding. 192․168․1․42 (talk) 19:28, 7 August 2020 (UTC) - It's very unlikely that reinfection will occur, mostly limited to anecdotes. CoryUsar (talk) 19:53, 7 August 2020 (UTC) - Tested, documented cases of reinfection have been known for months, and have happened around the world. Coronaviruses in general can be caught multiple times. And COVID-19 is still a new, relatively rare disease. If one in a thousand catch it, only one in a million would be likely to catch it twice if there were no immunity at all. Less since there hasn't been much time for immunity to fade yet. This hasn't become significant for the population dynamics of the disease yet, but it will probably be a major part of how things play out long-term, especially if it becomes endemic. 192․168․1․42 (talk) 20:10, 7 August 2020 (UTC) - @CorruptUser Not even gonna bother looking at the tool WaPo created about this exact thing and continue with random bullshit. OK. Also the argument isn't "No one should die", it's "We should do everything to stop preventable death from an infectious disease we know little about". Also I thought conservatives were prolife? -RipCityLiberal (talk) 21:12, 7 August 2020 (UTC) - 1) I'm not conservative - 2) Your lockdown is going to kill people. I thought "you liberals" were always harping on about how poverty is deadly? CoryUsar (talk) 22:16, 7 August 2020 (UTC) - Pretty sure poverty is deadly (not quite as deadly as an infectious disease), and the government should be providing financial support to people while businesses are shut. Because if people are forced to return to jobs and then get infected, it's not exactly going to help the economy. Pretty sure you've been using every single right wing talking point to try and justify killing millions to protect the markets. But that is what you are trying to justify aren't you?RipCityLiberal (talk) 23:33, 7 August 2020 (UTC) - A comment of mine, which you have ignored twice now by the way, needs to be repeated again it seems. The fall out from poverty can partly be alleviated by government spending and wisely planned and implemented social programs as is done in most of Northern Europe, along with free medicare and subsidies for housing, generous unemployment benefits, food subsidies, cheap post-secondary education etc. Government planning and spending can help with this and can definitely help cut down on the number of deaths...so people don't need to rot away in exteme squalor or be homeless rotting in the gutter. At the same time the government can also implement wise programs in which sensible reasonable human beings wear their fucking masks, don't have parties and maintain social distancing and utterly minimize their socializing and shopping and non-essential work places shut down for a reasonable period of time.. That along with government programs to subsidize wage losses and failing businesses (as done in some EU countries) will very much help minimize deaths. So it isn't a zero sum game Cory. You can both help people not pointlessly die of COVID and help minimize people pointlessly dying of poverty. Try to get that into your head. It is NOT either/or. Both can be avoided. ShabiDOO 00:30, 8 August 2020 (UTC) - You can have the generous social services as long as you have a tax base to support them. The US? Even without the pandemic we'd be lucky if we could raise enough taxes to cover the current debt, let alone the added social services. We simply aren't going to raise an extra trillion in tax revenue, not even if the Dems win the entire House and every Senate seat up for grabs. The lockdown is only going to make things worse financially, as the tax base is being obliterated. There's only two longterm solutions if this lockdown isn't eased, and both are basically the same result. The first is the US renegs on its debt; who knows, maybe Trump will get pissy and cancel only the debt China owns, but what this will do is cause the entire financial system to collapse in a manner just as bad as The Great Depression. And all the Northern European social democracies? Remember that in spite of the 2008 crisis being about the US, Europe was hit harder. The US slips and falls, the EU gets a broken neck. Your rightfully-lauded Scandinavian model countries will collapse as well. The second option, well, it's basically the same thing but lying that it totes isn't, bro. The US prints more money. Basically, everything the US owes is in dollars, and the US can simply print 25 Trillion dollars and claim all the debts are paid off. Doesn't matter if the dollars are only good for wiping your ass, the debt is gone, and the rest of the world economy collapses entirely, which drags the US along with everyone else. The US is unable to import anything, dollar being worthless, and also can't take out any more debt. CoryUsar (talk) 00:59, 8 August 2020 (UTC)n - Countries are not static entities, with enough motivation they can quickly transform. There is no reason why the US cannot become a more compassionate reasonable society. In the mean time...what are you doing about it? By the way, Northern Europe is not limited to Scandanavia. Even moderately generous countries like Belgium or Ireland utterly surpass the US in relative social spending (and effectively cutting down on some of the misery of poverty). Even Spain is doing better than some republican states. So no...you don't have to look to "model" Scandanavian system to find caring countries that seriously try to tackle social problems (and limit the fall out and deaths from poverty). Canada shows that a North American country can pull it off with a lot fewer resources, economy and people. ShabiDOO 01:22, 8 August 2020 (UTC) I wonder if Mike Pence will run for President in 2024[edit] George Bush Senior followed after Ronald Reagan, what will Mike Pence do?— Unsigned, by: 2001:8003:59db:4100:47e:6313:fa23:156a / talk 12:16, 8 August 2020 (UTC) - It is possible that he might make a run in 2024. --Possible Goat (talk) 15:16, 8 August 2020 (UTC) - Why is this trollish? Seems like a reasonable query to me. Scream!! (talk) 17:13, 8 August 2020 (UTC) - GC making an ass of himself and thinking that every BoN is a troll again. I’m hitting the end of my patience. Chef Moosolini’s Ristorante ItalianoMake a Reservation 17:19, 8 August 2020 (UTC) - Has he ever tried running for a Presidential election before? Gunther1987 (talk) 17:37, 8 August 2020 (UTC) - See, this is why I fucking removed this topic, because none of you fucking think. Wow, some guy keeps posting shit in the saloon on a daily basis, and engages in trolling in articles. Hmm... Maybe the saloon posts are trolling too... Maybe not feed them... ☭Comrade GC☭Ministry of Praise 18:12, 8 August 2020 (UTC) - A penny for people's thoughts? Anna Livia (talk) 18:45, 8 August 2020 (UTC) - Here's a link to where I list off the IP range's behavior, both in the saloon and in other parts of the site. ☭Comrade GC☭Ministry of Praise 18:46, 8 August 2020 (UTC) - @GrammarCommie for God sake, most of these discussions are fine. You are the one throwing a fit. If you don't like the discussions then don't participate. Simple enough. Get your undies out of a knot. --Possible Goat (talk) 21:38, 8 August 2020 (UTC) - I'm sorry if I'm (apparently) the only person that studied up on how to deal with trolls. ☭Comrade GC☭Ministry of Praise 21:41, 8 August 2020 (UTC) - Here is the thing- the OP asked a legit question, you threw a fit (for some reason). How is asking if a person will run for election somehow trolling? --Possible Goat (talk) 21:57, 8 August 2020 (UTC) On topic: If Trump wins in 2020 (I hope not, but Amerikkka is Amerikkka), he could technically have Pence run as the front candidate and Trump as VP. Yes, this is legally allowed afaik. — Godless Raven talkstalkwalkbalk 🌹 21:59, 8 August 2020 (UTC) - Well, Putin pulled of this stunt back in 2008 when Medvedev became President and made Putin Prime Minister of Russia, before retaking his throne in 2012. So if the russians can pull such a stunt, I wouldn't be surprised if America copied this over. Gunther1987 (talk) 22:13, 8 August 2020 (UTC) - @Gunther1987 I'm betting if they try that stunt they'll be blatantly cribbing Putin's playbook. ☭Comrade GC☭Ministry of Praise 22:23, 8 August 2020 (UTC) Help[edit] I just made an account on Conservapedia, what should I do with it? Fowler (talk) 13:28, 4 August 2020 (UTC) - Conservapedia isn't as fun as it used to be-Hastur! (talk) 13:46, 4 August 2020 (UTC) - Watch as it gets banned. ☭Comrade GC☭Ministry of Praise 13:47, 4 August 2020 (UTC) - And people say that I lack subtlety-Hastur! (talk) 14:05, 4 August 2020 (UTC) - well shit... Fowler (talk) 14:07, 4 August 2020 (UTC) - Well that block escalated quickly.Coigreach (talk) 14:41, 4 August 2020 (UTC) Figuring out the number of digits in extremely large numbers[edit] I speak of numbers such as Graham's Number and TREE(3) in terms of digits. Now I am no mathematics expert (I barely passed Algebra 1 in high school) but wouldn't using the number of universes it would take to fit the digits be a good method i.e the number of universes to put all the zeros? I probably sound stupid but I am just curious, I sorta developed an interest in very large numbers recently. --Possible Goat (talk) 01:24, 9 August 2020 (UTC) - Large numbers eh? I recommend watching Numberphile, they have videos on even larger numbers, discussing about Grahams number with Graham himself etc. The Sqrt-1 talk stalk 01:53, 9 August 2020 (UTC) - Here is the playlist of big numbers. You are looking for “What is Grahams number? (feat Ron Graham)” and “The Enormous TREE(3)”. I also recommend checking out other big numbers. He is the link Hopefully this will explain why Grahams number is G64 etc. The Sqrt-1 talk stalk 04:06, 9 August 2020 (UTC) Friendly reminder to US citizens on the wiki who are 18 or older[edit] Remember to vote the Mango Messiah out of office and straight into the dumpster this November. Ideally a dumpster behind a Mexican restaurant for Irony. --George Soros Puppet (talk) 16:28, 30 July 2020 (UTC) - The primary trouble with this idea is that for the vast majority of possible voters, their vote is only symbolic because their state is locked for red or blue no matter what they do. It really only matters if you're in one of the swing states. The rest of us are essentially spectators. Glitch (talk) 17:05, 30 July 2020 (UTC) - Vote anyways. Make a show of support. Also some formerly red states are looking mighty purple right now-Hastur! (talk) 17:15, 30 July 2020 (UTC) - I hereby commend you. Also, my state is not one of the purple ones--at all. Deep, deep red. Further, since it's entirely symbolic, I don't want to symbolically participate in my own oppression by voting for Biden, who is only better than Trump in the sense that a gutshot is better than a headshot. My ideal scenario is that Biden wins, but in a close race with the lowest turn out in history, to terrify the Dems into actually transforming into a left wing party instead of a center-right one. Right now anyone on the actual left has no representation in government at ALL. Things are only going to get worse overall as the government gets further and further from being representative of the people. The "Harm Reduction" strategy of the Dems has been a monumental failure going back for several decades now and this is its last gasp. Or so I see it, anyway. Glitch (talk) 17:25, 30 July 2020 (UTC) - I will say, establishment democrats are facing a lot of pressure to be more on the left. Encouraging. Fingers crossed, we won't see a repeat of the Obama era where democrats lived in fear of Republican filibuster and we'll see some meaningful legislation-Hastur! (talk) 17:32, 30 July 2020 (UTC) - Would it help if I told you that by not voting you were participating in your own oppression to an even greater degree by doing exactly what Donald Trump wanted you to do? Semipenultimate (talk) 17:36, 30 July 2020 (UTC) - Not unless you have a much more persuasive form of that argument than the ones I've already seen before many times, which I find to be mostly nonsense, no. Glitch (talk) 17:45, 30 July 2020 (UTC) - Well it's difficult since I can't see any valid reason to sink into complete hopelessness as a response to the two-party system. If political franchise is entirely symbolic, if voting is totally pointless, then you've left yourself with no path to induce change on any level. Semipenultimate (talk) 18:09, 30 July 2020 (UTC) - (EC)I'm sick of this stupid topic ban, because failing to show support for someone getting dogpiled by these same shitty arguments feels worse than getting banned. You're not alone, and you're 100% right glitch. You're not obligated to vote for a right wing rapist, just because there's another right wing rapist who's worse on the other side. It's okay to have moral standards. ikanreed 🐐Bleat at me 18:14, 30 July 2020 (UTC) - Ikanreed, wasn't your topic ban to only last as long as the primaries? I, at least would support ending it now.-Flandres (talk) 19:16, 30 July 2020 (UTC) - You have mistaken what I've said, I'm afraid. Or I said it poorly. I'm not hopeless. And I'm quite politically engaged. But voting for Biden is counterproductive to my goals. Do you understand? I donated $200 I could ill afford to Bernie's 2016 campaign, which by my count makes me extremely invested in the political process even compared to billionaires if you consider percentage of wealth given. I thought Bernie was our last, best hope for a compromise candidate that MIGHT be able to accomplish enough to head off a very bloody revolution. We all know how that went. - I think at this point a revolution is inevitable. The questions that remain are, how bloody can we stop it from becoming, how fast is it going to happen, will it succeed or be crushed, and if it succeeds can we keep the result of the revolution from just switching who sits in the authoritarian seat of power but actually devolve real power to the people. I very much hope that I'm wrong and we can achieve the radical change needed without a single drop of blood. But the odds of that coming from the existing legal structure in the US are practically nonexistent. - Familiarize yourself with the way the Constitution actually works. The details. I'm not really interested in debating the intent of the Founders and if they intentionally set us up for this result or just didn't know what they were doing, but this conflict is systemic destiny. Given the Constitution, and the mechanisms in place to alter it, this was practically inevitable. The rules of the game demand it. It's like arguing that the game of Monopoly doesn't inevitably end up with one person the winner. The only way to avoid that outcome is to flip the board and reject the rules themselves. How peacefully we can manage to do that, that's the real question. But unless we have a new Constitutional Convention, this is going to happen again and again until the game ends. - Well, that's how I see it, anyway. I'm open to being convinced otherwise. Glitch (talk) 18:40, 30 July 2020 (UTC) - @Glitch now if a revolution happens (entirely possible), it would certainly be a bloodbath. There is no tip-toeing around that fact. This is the United States, it has mountains of gun owners. Right now voting is the only option to stay peaceful. Plain and simple, hate to break it to you. --George Soros Puppet (talk) 18:56, 30 July 2020 (UTC) - Do you understand how the Electoral College works? And the Senate, for that matter? Please help me understand how my vote, in a state so deep red that it will not only go to Trump with a HIGH degree of certainty, but both Senators will be red as well, has a more than almost indistinguishable from zero chance of affecting anything at all. If you can't, and you believe what you say, you will accomplish your goals much more effectively by bothering those whose votes might actually count for anything at all, I think. Glitch (talk) 19:34, 30 July 2020 (UTC) - I want to sum up, if I can. Correct me if I'm putting words in your mouth. You don't want to vote for Trump, or Biden, or put in a protest vote for your chosen candidate, Bernie. You advise others to bother those whose votes might actually count; by this I presume you mean their senator or congressional rep and it's good advice - call your reps! But for you these are all Republicans anyways since you live in a deep red state, so those whose votes might actually count will not listen to you. The only solution you see is some form of revolution which you hope will be as bloodless as possible, which for your sake I hope would be true, as you are a nonbinary person living in a deeply red state. Do I have the facts on the ground correctly arrayed? Semipenultimate (talk) 21:38, 30 July 2020 (UTC) - Thank you for respectfully trying to understand what I'm saying. That's so fundamental to productive discussion, and so rare. I wanted to say that first, lest I forget to. - Some slight clarifications. I think that the election process, from top to bottom, in the US is systematically illegitimate and does not represent the actual will of the people. I'm not sure how anyone who understands the way the government works in a systematic way, totally aside from the motivations of those elected, can come to a different conclusion. But nonetheless, based on that premise, I further think that any participation in this illegitimate system only serves to give it a false veneer of legitimacy, which should be avoided except in direst need. I think that if enough people reject the system entirely, it can no longer pretend to be legitimate and will have to be replaced wholesale. In theory there are ways to reform the system within the system--but in practice they are virtually impossible to use in any meaningful way. - Therefore, I will not vote unless there is an incredibly dire emergency AND I have reason to believe my vote will have some sort of effect on the outcome. The Trump situation is very nearly a dire enough emergency to count--but since my vote is entirely symbolic, that's irrelevant. If I personally got to choose between Biden or Trump and my vote was the only one that mattered, I would swallow my ideals and crown Biden, rather than abstain such a responsibility. But essentially the opposite situation is true, so I get to keep my ideals intact. Most citizens of the US are in a similar situation. Any "Get Out The Vote" efforts should be laser focused on the swing states, where votes actually matter. It's still the choice between a gutshot or a headshot, in my opinion, so I don't blame those who refuse to pick how their captor will execute them, but at least those people have the actual option to choose to choose, as it were. And I don't blame them for picking the gutshot, which has more chance of being saved before it's too late. - Perhaps at this point the best outcome I can see is that the threat of revolution will swell until a new Constitutional Convention is called in a desperate attempt to avoid it, and we can then create rules amenable to actual representative rule instead of innately hostile to it. That's probably a pipe dream, though. So taking revolution as extremely likely, I'm focused on the principle of least harm. Given, that the US government is systematically ill, broken on the inside and not going to get better on its own, it remains to us to determine how to proceed. Most care only that the tumor is removed, and I agree that is the most essential thing. However, I much prefer that we wield the blade with the precision and care of a proper surgeon, rather than get carried away with a Jack the Ripper impression. I wish no harm to anyone. But, as inaction is causing great harm and has for centuries, and we very likely cannot correct it without doing SOME harm, I'm very concerned with how we can correct it with as little unnecessary blood spilled as possible. - I appreciate the personal concern and I'm aware that I'm quite vulnerable myself. But, and you may take this as unlikely, I'm not terribly concerned with what happens to me personally given the stakes. If I could trade my life to fix it all with no one else getting hurt, I would do it in a heartbeat. If I could trade not just my life, but the lives of everyone I love so dearly too, to limit the damages to only that, I would hesitate for only a fraction of a second longer. And consider it a very, very good bargain indeed. The stakes are far too high for such a scope to hold any weight at all, in the balance. And I would happily let my legacy be that of the villain for thinking and saying so. Glitch (talk) 22:47, 30 July 2020 (UTC) - Trump going all in on encouraging anti-Chinese racism has made me pretty committed to voting against him for my own self-preservation. Chef Moosolini’s Ristorante ItalianoMake a Reservation 22:28, 30 July 2020 (UTC) - Well there's no doubts how I'll vote since, if I had to pick the most important issue that Republicans are mucking up, they are the party of climate change denial but it's like they want to make it personal with me with the anti-Chinese bigotry and willingness to kill birds for their stupid black sludge and mold paper with dead, sad white men on them that smells like greasy palm. --It's-a me, LeftyGreenMario!(Mod) 23:12, 30 July 2020 (UTC) - You're supposed to vote your conscience, I wouldn't shame anyone for voting their conscience. — Oxyaena Harass 01:34, 1 August 2020 (UTC) - No, that's not what democracy is about. Voting is a highly utilitarian practice. This isn't your soccer league where you can pick and choose as you want. Politics is done by mass movement and compromises. In the US, there are two alternatives: a conservative democrat (Biden) and a fascist (Trump). If you don't vote for Biden, you are enabling fascism in the US. That's where your conscience should be, not this idealistic fantasy that people project on the world of realpolitik. — Godless Raven talkstalkwalkbalk 🌹 02:59, 1 August 2020 (UTC) - I'd be pretty pissed off if people "vote their conscience" and Trump's war on immigrants, trans people, and other minorities goes on unchecked. People who don't vote for Biden have blood on their hands. Get out of your ivory tower and realize that there are real world consequences to your actions-Hastur! (talk) 03:04, 1 August 2020 (UTC) - The Dems have been campaigning solely on not being as bad as the Republicans for many decades now, and shaming anyone who demands they do better. Do you find that's working well? Does it seem to be a winning strategy? Because all I see is the Dems going further and further to the right as fast as they can, while the USA burns. But I'm sure a few more doses of shame to throw around will turn it all around. Glitch (talk) 03:57, 1 August 2020 (UTC) - Sorry... That was more confrontational than I like to get. But you're not going to change any Never Biden minds by shaming them. They've heard it all before. You're just going to piss them off to no purpose. If that tactic was going to work, it would have already worked by now. Glitch (talk) 04:10, 1 August 2020 (UTC) - None of those promises by Biden are worth anything at all. The only reason they're even being made is because they know they can't keep them. There's basically zero chance of the Dems getting the 61 Senators needed to break the filibuster (and they don't have the guts to remove it), so none of that legislation has a chance in hell of passing. It's just hype. The Dems OFTEN talk a good game. But they have done NOTHING substantive since Johnson. Nothing at all. It's Lucy with the football, Charlie. I feel like a great deal of the problem is that people don't understand just how stacked the deck is. Hell, REDMAP really should've clued people in, the people who pulled it off admitted it and said how and why they did what they did, and people still don't get it. People don't even know what REDMAP was or why it matters. The system is broken from top to bottom. We don't HAVE a democracy. The sooner people realize that, the sooner we might actually get one. Glitch (talk) 05:13, 1 August 2020 (UTC) - Like I said above, there is real policy at stake here.[32][33] Biden and Trump are not the same and nor will they do the same things-Hastur! (talk) 05:15, 1 August 2020 (UTC) - I never said they were. Biden will be a relief after Trump. Trump and the Republicans have been trying to kill the golden goose (us) to get what's inside, Biden and the Dems will just keep taking the daily eggs while slowly starving us to death because feed is so expensive. Forgive me if I don't throw a party at the thought. Glitch (talk) 05:31, 1 August 2020 (UTC) - The Dems are exactly the same as the GOP, America is not a democracy, it's an oligarchy, the only way to enact change is to replace the system entirely. Biden's a rapist and is responsible for a lot of the mess we're currently in, being "better than Trump" shouldn't be the bar we judge politicians by. — Oxyaena Harass 06:01, 1 August 2020 (UTC) - Now, that's slightly unfair. Biden MIGHT not be a rapist. Glitch (talk) 06:05, 1 August 2020 (UTC) - Okay, Oxy. If Trump wins and you didn't vote against him, whatever happens to undocumented immigrants and trans people as a result is on your hands.-Hastur! (talk) 06:07, 1 August 2020 (UTC) - Same if he escalates foreign conflicts. Same if he cuts important federal benefits. Same for refugees seeking asylum here. Same for people being attacked by federal agents. Those are largely Trump things. See, I actually know a lot of undocumented immigrants. Some DACA, some not. I know a lot of people who would be hurt if Trump were allowed to continue his rampage. But I guess you don't care about those people. You care more about standing on principle, in your ivory tower. Watching people get hurt and doing nothing.-Hastur! (talk) 06:10, 1 August 2020 (UTC) The Dems are exactly the same as the GOP Yep, that's exactly what Oxy said. Let's see how the GOP differs from the democratic party. - Trans rights? Equal. [34] = [35] - Immigration? Identical. [36] = [37] - Climate change? Can't see the difference. [38] = [39] - Abortion? Hard to tell. [40] = [41] - Foreign policy? Who cares. [42] = [43] - Taxation? No difference. [44] = [45] - Police brutality? Same same same. [46] = [47] I could go on and on, but I now recognize anarchism is a very serious ideology and Biden = Trump. — Godless Raven talkstalkwalkbalk 🌹 06:25, 1 August 2020 (UTC) - -Hastur! (talk) 06:28, 1 August 2020 (UTC) - You liberals sure are self-righteous, notice how all of these are merely half-measures at best. And to say I don't care about marginalized people is rich, even though I myself am marginalized. Remember that Biden instituted the ICE concentration camps in the first place. Again, Biden is in large part responsible for the current mess, you can go on and ignore my points, but at least don't pretend to be actually responding to what I said. Being better than Trump is not a bar which we should judge politicians by, not that you people care, since that seemed to go right over your heads. — Oxyaena Harass 06:34, 1 August 2020 (UTC) - Like I said, the very real consequences of a Trump reelection are on your hands.-Hastur! (talk) 06:36, 1 August 2020 (UTC) - Half-measures? Far better than Trump's active stance against these groups. You lack empathy. Go preen in your ivory tower and tell yourself how virtuous you are. I live in the real world-Hastur! (talk) 06:39, 1 August 2020 (UTC) - You know what? Thanks for voting for Biden. No, honestly. I'm sincere. I think many of your conclusions are dead wrong and I think that you don't understand the political system well at all, but if it wasn't for the huge amount of liberals willing to vote for Biden, we might actually have another 4 years of Trump and that would indeed, as I've said all along, be worse. I will be (pleasantly) shocked as hell if Biden does anything of any substance whatsoever besides not being Trump, but that alone is worth thanking you libs for. And because there are so many of you, those of us who have given up on electoralism in favor of direct action don't have to wrestle with our conscience about voting for Biden, because you guys have got it covered. So go fire up your fellow libs and kick the Cheeto out of office. Really. Maybe we can just leave it at that? Even if we're not voting, we're pushing others to vote him out with lots of anti-Trump social media content. We're on the same side. Glitch (talk) 06:40, 1 August 2020 (UTC) Reflect about it: In Weimar Germany, who would you be before Hitler took over? The people opposing them (the SPD) or the people who just stood by and watched fascists take over (the KPD)? I know which side I am part of. I care about trans people. Biden will help trans people. Trump fucks them over. This isn't hard. You either care about trans people or you don't. — Godless Raven talkstalkwalkbalk 🌹 06:47, 1 August 2020 (UTC) - You accidentally exposed your file structure there, Hastur, I edited it out for you. And I don't think you read what I said. I'll be glad to engage you on that topic, and any other, in a respectful manner, but please put a pause on it for tonight. I'm very tired. - GR, as a trans person myself who has not one but two other trans people as my romantic partners, I'm trying really hard to not be snarky on the topic of whether I care about trans people. But honestly it would be nice if you stopped using "Think of the trans people!" as a variant of "Think of the children!". We're quite capable of making up our own minds. Some of us hold our nose and support Biden. Others don't. Yes we all hate Trump. That doesn't mean we all automatically think Biden and the Dems are our best pals. Also, just because we're trans doesn't mean that's the only issue we care about. Again, yes, Trump is the devil. Everyone is agreed there. Glitch (talk) 07:05, 1 August 2020 (UTC) - — Godless Raven talkstalkwalkbalk 🌹 07:24, 1 August 2020 (UTC) - Biden = Trump is such a ridiculous exaggeration. Even if it were the case that Trump was 90% bad and Biden was 80% bad (which is not the case and would be extreme hyperbole) 80% bad is an entirely more attractive option than 90% bad. And even if that were true per policies (which it isn't), the leadership style of a politician has a HUGE effect on the social climate of a nation. Having a president openly spout racist homophobic nastiness all the time emboldens the considerable number of racist/homophobic people to do crazy shit all the time. It means more open racism, more swastikas spray painted on peoples houses, more acts of racists violence and harassment and abuse. Just for this horrid grief that marginalized people have to deal with is an extremely important reason alone to remove someone like that from office. And that's just one example of the small effects that an even slightly better leader could have (and thats not to mention the devastating world trade disaster policies trump has had which will take decades for not just the US but the world to recover). Literally the whole world is less stable with Trump in office. And even then, I'd go along with all of your hyperbole any of you could answer what you think you're standing to gain by effectively helping Trump get into office. Are you even remotely serious about working to get a third and fourth political party into the US political arena? Are you trying to bring about change or just saying: uff...I'm not impressed with either option so fuck them both I'll throw my vote away on a a candidate nobody cares about with a protest vote nobody even notices and poo poo the system. I'd go along with any of you if you were serious about helping build realistic alternative option in the US, which would require a whole lot more than "pff..they both suck". ShabiDOO 12:11, 1 August 2020 (UTC) - So...why are you spending so much energy to change the votes of two people who would probably not vote blue anyway? Biden has a (for our polarized time) MASSIVE lead. It's not like he is going to lose. Is Biden just such a pathetic candidate that he makes you so insecure you melt down whenever he is criticized? What is the purpose of this conversation beyond politely agreeing to disagree? Also hastur invoking a symbol of privilege to bash to trans people is hilarious,hmhmhm...-Flandres (talk) 12:45, 1 August 2020 (UTC) - A reasoned response to an irrational argument is never useless whether it changes a vote or not...nor is it a meltdown. Nice tone policing Flanders. I don't think Biden is a terrible candidate to begin with...if you actually read his policies. It's just democrats unhappy their perfect candidate didn't win and rejects the non-perfect candidate. Happened last election. No surprise. And in any case I only care because Trump's policies have made the world more unstable and have hurt the EU economy (quite pointlessly) and has inflamed radicalism in the middle East and considering Europe deals with the most random Jihhadist murdering (including in the city I live in) it is high stakes for non-US citizens like myself. Trust me...the vast majority of the rest of the world is hoping a sufficient number of Americans will be sensible this year. ShabiDOO 14:08, 1 August 2020 (UTC) - I was not responding to you personally, apparently that needs to be clarified. Again, polls all say Biden will win and you are not changing the opinions of Oxy or glitch so what *is* the use of this? Are you arguing a topic that has been debated to death in your own words just for the sake of arguing?-Flandres (talk) 14:16, 1 August 2020 (UTC) - No because to my surprise Glitch brought up some new ideas that haven't been mentioned before and as you've seen they've already converted someone to their folly. And in any case it's ridiculous to think the election is already won. Or do you have such a short term memory from the last dozen elections in the US, UK, Canada and Australia (just to cite Anglo Saxon countries alone)? ShabiDOO 15:09, 1 August 2020 (UTC) - Who has glitch converted? And um...have you seen Biden's polling lead? Like, actually looked at the data? How does he lose?-Flandres (talk) 15:32, 1 August 2020 (UTC) - Even if his lead were double it means nothing. It's a poll...not a crystal ball. They are famously unreliable. Follow a few more elections and you'll learn...you clearly didn't learn from the 2016 election. ShabiDOO 16:34, 1 August 2020 (UTC) - Yeah, complacency is nigh-intolerable. We can't take chances. The country is on fire and we need Trump out of office-Hastur! (talk) 16:52, 1 August 2020 (UTC) - You still have yet to explain why Trump could win when every other incumbent in a disaster this large has lost. Also, I would like to remind you that polls were right that Hillary would be Trump in the popular vote. They promised nothing in the EC. Also she had like half the polling lead Biden does so your observation about 2016 is nt that sound in general.-Flandres (talk) 17:08, 1 August 2020 (UTC) - I brought up some new ideas? Hey, neat. Yay me. I'm really not very familiar with what arguments "my side" has been making, because my reasons are mostly my own, not inherited from someone else. Or so I think, anyway--obviously we're all influenced by our environments. But also I have no real interest in badgering libs about Biden. Until they move further left, supporting Biden is probably the most helpful thing they could be doing. But I can't stand to see them using arguments that are 1) bad reasoning and 2) not effective anyway to harass leftists. It's a waste of time and effort if nothing else. You can't use YOUR moral intuition to shame someone else into acting against THEIR moral intuition. That should be staggeringly obvious. And yet here we are. I think it's possible to have a fruitful discussion about it, in theory, but the ad hominem and the righteous indignation and all that reason-destroying nonsense has to stop for it to even be worth trying. I believe I know the position of the libs, but maybe I've misunderstood it. I can't speak for all leftists, not remotely, but I can say that as far as my own position has been talked about here in this... thread? it's been subject to multiple major errors of assumption. In the context of a fruitful discussion, it's critical to assume good faith, so I'm not going to say I'm being intentionally strawmanned or whatever, but until we can clear up those misunderstandings (on both sides) we can't identify points of agreement and disagreement because we don't know what each other believes or is trying to accomplish. Is anyone honestly interested in approaching the discussion in a "rational" manner? I know, something something tone argument, rational doesn't mean respectful, etc, but since a fruitful discussion can't happen in the middle of a mudslinging contest, I think it would be decidedly IRrational to try to have one there. Glitch (talk) 20:22, 1 August 2020 (UTC) Imagine thinking polls are a statement of certainty rather than probability. Get better, dear, dear Flandres. — Godless Raven talkstalkwalkbalk 🌹 20:35, 1 August 2020 (UTC) - You still have yet to explain how Trump will win in these circumstances, GR.-Flandres (talk) 20:37, 1 August 2020 (UTC) - Flandres, a few months may as well be a few years in the future. A thousand things can happen between now and voting day. Clinton seemed like a sure thing leading by 15 points. Trudeau's rival seemed like he was heading for a majority. Corbyn was super high in the polls until he wasn't any more. It was considered ridiculous that the Labour party would lose in Australia last election, until they surprisingly lost. Anyone who prophesizes an election win months away has no experience following an election and shouldn't be taken seriously. ShabiDOO 20:50, 1 August 2020 (UTC) - And Trump can win re-election during the worst national crisis since the great depression? One that he made worse at every single stage, a fact that is widely known? Hillary was also not leading by 15 points for the majority of the general election, get your data right please.-Flandres (talk) 20:55, 1 August 2020 (UTC) - Yes, he absolutely could pull out a last-second turnaround. You ever heard the term October surprise? Chef Moosolini’s Ristorante ItalianoMake a Reservation 21:51, 1 August 2020 (UTC) - I never said it was, don't put words in my mouth Flandres. In any case her average lead throughout the last 6 months was higher than Biden's current lead. And none of it matter, we are months away. Too many things can happen. It's embarrassing to see someone declare any election in an open democracy a done deal months before election day. ShabiDOO 21:55, 1 August 2020 (UTC) Here is how trump can still win[edit] — Godless Raven talkstalkwalkbalk 🌹 21:00, 1 August 2020 (UTC) - btw. anyone remember Gore v Bush? And how the SCOTUS stole the election for GW Bush? — Godless Raven talkstalkwalkbalk 🌹 21:01, 1 August 2020 (UTC) - Congratulations! You have made a good point. With the make up of the court as it is, the 2000 comparison is apt and a close associate of mine works with the post office and confirms some of the details of the video and more(you are better with videos than you are with your own words-that vaush one was fairly sound as well). What now?-Flandres (talk) 21:14, 1 August 2020 (UTC) - Now, the republicans will try to cheat in every way they can, it is why I have to make people vote for Biden - who, to be very clear, I opposed and made arguments against online for 2 years - a candidate that is very weak and relies strongly on an anti-Trump sentiment rather than a pro-Biden one. He became 4th in Iowa and 5th in New Hampshire; he is not a very good vessel for campaign enthusiasm. That being said, I see Trump as an existential danger to the planet; even far-left folks like Noam Chomsky (an anarcho-syndicalist i.e. commie) agree with me. — Godless Raven talkstalkwalkbalk 🌹 21:40, 1 August 2020 (UTC) - I agree that it is important to get Trump out of the White House, but it is at best a short term reduction of harm. As for Chomsky’s emphasis on the climate crisis, I find it rather unreasonable to lay so much of the blame on Trump personally. What Trump has done is simply to be more honest about a view and a lack of preventative action, as well as a continuing detrimental actions that have been standard GOP fare for at least two decades (arguably more, if you consider that background presented in Merchants of Doubt). - While Trump has been significantly worse on other environmental issues, such as defanging the EPA etc., his climate policies don’t seem any more or less catastrophic than the GOP norm of denialism and refusal to do anything. Dubya refused to join the Kyoto Protocol, despite great efforts to water it down to appease the US. Trump’s exit from the Paris Agreement is just more of the same. Yes, it’s likely to have catastrophic consequences, but these politics are not unique to Trump and I can’t see any GOP POTUS doing anything that might be meaningfully more beneficial in halting climate change. ScepticWombat (talk) 10:13, 3 August 2020 (UTC) - Also, I have a problem with the framing because it sounds a lot like preparing the ground to blame the left for any Biden defeat, just as the Bernie bro narrative was used in the aftermath of 2016 and eerily similar to Trump’s preparation for a losing narrative blaming others (in his case voter fraud). If Biden and the “centrists” had shown just an ounce of willingness to give “the left” anything substantial (beyond meaningless task forces), there might be less of a threat of abstentions. - Once again, in a repeat of the aftermath of 2016, the “centrists” are preparing the ground for blaming the loss by a fundamentally flawed and weak candidate that they pushed through, despite these well-known flaws and without any meaningful concessions to “the left’, on feckless and faithless “lefties” who don’t do as they’re told, rather than on the lack of appeal of their own politics and candidates. To put it polemically: The “centrists” will rather lose a presidential election, than lose the control over the Democratic Party. - Again, was I a US voter, I would almost certainly end up voting for Biden, but the problem is that, while the consequences are pretty dire if Biden loses, a Biden win would once again signal that the “centrists” can and should ignore anyone on “the left” because they’ll “vote blue no matter who”. To use a medical analogy, Trump is doing nothing to stop the patient from bleeding to death and is actively making the blood loss worse. Biden promises simply to slow the blood loss, not staunch it and the patient will still bleed out; it will simply take a bit longer. My fear is that the lessons being learned among “centrists” are that is is feasible to let the patient bleed out, just as long as it doesn’t happen too quickly. ScepticWombat (talk) 10:29, 3 August 2020 (UTC) - I also consider Pakman’s defence of Biden by focusing solely on his 1990s suggestions for privatising Social Security as ancient history to be extremely selective, not to say disingenuous. As Nathan J. Robinson pointed out in his detailed layout of Biden’s political background and history, Biden has a series of incidents of favouring big business and other Republican darlings (including palling around with the likes of Strom Thurmond and Jesse Helms, when it was convenient). To quote Robinson’s summary of Biden’s character, based on his actions in a long career in politics: - .” - Thus, to boil objections to Biden down to unreasonable cherry picking of bad policies 30 years ago and then dismiss criticism out of hand is just bunk. ScepticWombat (talk) 10:56, 3 August 2020 (UTC) - You have put my concerns into eloquent words, and specific examples to my vague recollections. I would further say that the Democrats have been hammering the drum of "harm reduction", of just being not the Republicans, for at least 100 years, and what do we have to show for it? As far as I can tell the Democrats have only ever done two meaningful things for us--the New Deal and Johnson's Great Society. And in both cases it seems they only delivered them under great duress, under the specter of huge civil unrest that threatened to tear the country apart completely. Maybe they would have loved to have done more, more often, and the Republicans just prevented it all those other times, even when it seemed like the Democrats had control of the government. Whatever the case, they seem to have done very little over a great deal of time. The question is, how do we make them actually do things? Useful things, ideally. For a great many of us, Bernie was the COMPROMISE candidate. He WAS the middle ground. And obviously the party rejected him completely for being too extreme. So... What do we do with that? I was reading that recent polling shows 69% general approval of Medicare for All and 88% approval among Democrats, but the Democrats rejected it something like 135 to 35 from their platform this year. Either the polls are way off or the Democrats are far to the RIGHT of the general population. How do we even start to fix this? Can it be fixed? Glitch (talk) 13:55, 3 August 2020 (UTC) - The really big downside to Biden is, that he will almost certainly choose yet another neoliberal tool as his Veep (e.g. Kampala Harris), which means that even if he himself is likely to be a one-term POTUS, it will be almost impossible to get a different Democratic option in 2024 and, if she wins, in 2028. That’s a full 12 years of further neoliberal misrule — sure, it’s not as bad as Trumpism, but man that’s a depressing thought. - As to how to fix it, the most important tool is probably also the first on Godless Raven’s list of suggestions in Debate:US Voting 2020: Primaries. This is essentially how the Tea Party took over and/or coopted the GOP: By aggressively primaring anyone at odds with or not supportive of them (yes, this includes anyone who try to fence sit). It is the one thing that can eventually losen the “centrist” stranglehold on the Democratic Party, because control of the party, its direction and its machinery are far more important to the “centrist” corporate Democrats than actually winning elections. There will always be another election, but in a two-party system it is far more difficult to get “another party”. - Unless “the left” is willing to follow this strategy of ruthlessly primaries and not give into the constant blackmail of “the centrists” with their hypocritical calls for “party unity” (which always means that “left” candidates should bow our, never “centrist” ones as seen by the ludicrous challenge to AOC), “the left” will always get steamrolled by the corporate Democrats. They have no qualms about fighting fair and are clearly willing to continue to field terrible candidates championing unpopular and useless neoliberal policies, even if it means a greater risk of losing at the polls (not to mention the harm done to the vast majority of Americans and their future prospects). ScepticWombat (talk) 06:22, 5 August 2020 (UTC) - *checks notes* Yeah, man! Worked out great for the GOP. Super excited at the prospect of a House-full of progressive Matt Gaetz and Jim Jordans. Helena Bonham Carter (talk) 11:45, 5 August 2020 (UTC) - Yeah, because using similar electoral tactics is TOTALLY guaranteed to elect numbskulls... Oh, and Jim Jordan was elected before the Tea Party as was several of the other walking GOP embarrassments masquerading as congresscritters, such as Louie Gohmert, Peter King, Pat Toomey or Jim Inhofe. ScepticWombat (talk) 13:00, 5 August 2020 (UTC) - Given good ol' Gym and the rest of your selection represent exactly the kind of batshit zealot the Tea Party later fought tooth & nail to elect, I'm not sure your retort does what you think it does. - Speaking more generally, making ideological purity your primary metric for support rarely produces politicians capable of the mucky, boring business of actually getting shit done in a democratic system, especially one with such formidable structural obstacles to sweeping change as the US version. Helena Bonham Carter (talk) 14:14, 5 August 2020 (UTC) - My point was that the numbskulls of the Tea Party were at most a gradual escalation of the general GOP numbskullery prior its arrival. The GOP had already sent crazies like Gohmert to Washington waaay before anyone thought of the tea baggers. So using them as the scary example of what happens if you decided to fight the party establishment is silly, because they were in Washington and crazy as part of that prior party establishment. - Ideological purity tests is obviously not enough and candidates still have to be vetted in the grinding process of a primary and if elected, the politicians still have to answer to their constituents or risk being primaried themselves. If you want the boring stuff done, you’re probably not worse of by getting someone who actually cares about changing stuff, because they might actually tough it out, rather than the status quo “centrists” who think the pinnacle of achievement is to return to the Obama/Clinton presidencies. - So, if you want something different, you’ll have to fight for it and the only arena in which you’re likely to influence a party in a two-party system is through primaries. Then, once the “centrists” have seen that they can’t simply take the “left” voters for granted and that it is indeed possible for such primary challengers to unseat them, you begin to get some leverage within the party and a platform to change its overall direction. Also, if candidates have worked their way up through trade unions or similar organisations they will be very familiar with exactly the kind of organising, bargaining and the type of boring legwork necessary to get results that you asked for. - As much as I abhor the Tea Party’s views, its tactics have been insanely effective. All of the pundits agreed that after the trouncing administered by Obama to McCain in 2012, the GOP would simply have to ditch the right wing batshittery of the Bush era and move to the centre, or it would have no future whatsoever. Instead, the even more batshit Tea Party ruthlessly primaried its way through the GOP, which then basically adopted the Tea Party’s positions. - By contrast, it’s only really over the last couple of Congressional elections that “centrist” Democrats have had to deal with real primary threats and hence they have been free to completely ignore “leftist” views. This, along with the mind numbing idiocy of keeping focus on grand bargains with the GOP (Obama being the quixotic poster child of this approach), now more radical than ever, has left the “centrist” Democrats in a self-imposed bind: Every time they take one step towards the GOP, the latter simply steps back and any deal struck will be denounced by the GOP anyway and won’t survive any GOP gains at the polls. - Thus, the “centrists” are basically losing everything (apart from some cultural issues) little by little. It is indicative that Obama’s one great success, Obamacare, is basically a GOP design, though from the day when the GOP wasn’t quite as insane. Hence, if the “centrists” keep running the Democrats, the highest achievements will basically be equivalent to Reagan Republicanism. ScepticWombat (talk) 22:56, 5 August 2020 (UTC) Let's just look at where the "insane" electoral efficacy of the Tea Party has left the GOP: way to the right of most of the population; with perversely little incentive to change for most of its congressmen, women and senators occupying safe, deep red districts or states; and looking increasingly certain never to realise its stated goals of limited, fiscally responsible government and generally returning the country to some imagined 1950s golden age. It's not hard to imagine progressive Democrats repeating the same unfortunate trick, especially if they take the Very Online Left as their yardstick of where the rest of the country is at politically, and / or pander to them as the GOP has done with evangelicals. One concrete example for the purposes of argument: It's reasonable to suppose a Biden administration will try to restore / improve Obamacare. Progressive Dems could use this as an opportunity to lambast the "centrists" as corporate Big Pharma shills and ramp up demands for M4A in their push for 2022 House seats. It would probably be tactically smart for their purposes, but create wider Dem strategic headaches in statewide races, and thus actually make M4A somewhat less likely to happen in the medium to long term. Alternatively - and work with me here - progressive Dems could get on board with fixing Obamacare as a vital short to medium term improvement in overall social justice, whilst at the same time making the case that long term, the evidence is clear that some form of universal single-payer is much more efficient, both economically and in terms of improved health outcomes. It might not win them as many House seats in '22, but: they get to look like the adults in the room; they don't fuck with the next round of Senate or governor races; and, just maybe, they meaningfully move the needle towards a winning M4A platform in '24 or some other point in the not-too-distant future. You seem smart enough to realise the above alternate possibility (and others like it) isn't going to happen if they're hellbent on an ideological purge of the party, and primarying the fuck out of anyone who disagrees with them. Helena Bonham Carter (talk) 01:48, 6 August 2020 (UTC) - Of course, compromise can be a viable strategy/tactic and “the left” should pursue it where feasible. And yes, a better Obamacare might be a good idea, but the downside is that “fixing” Obamacare also easily becomes and argument against single payer. Hence, if your goal is the latter, you might be better off aiming for it in the first place. This becomes even more important given the likelihood that congressional bartering will probably water down any proposals anyway. - The problem with pursuing a strategy of compromise without aggressive primaring is that the “centrists”, who currently hold the reins of power in the Democratic Party, have demonstrated time and again that they are not prepared to compromise with “the left”, unless the latter has serious leverage. Hence, an aggressive primary strategy is a premise for any meaningful compromise strategy for “the left” —unless the latter consider “unity task forces” a meaningful result. - I also find your analogy to the Tea Party somewhat flawed since the “centrists” are actually to the right of a large slice of the electorate on several key topics, such as Medicare for all. Hence the likelihood that a “left” strategy based on the tactics of the Tea Party will strand them in an ideological lala land seems less likely to me (apart from my own political bias affecting my views, of course). - The “centrists” still seem more interested in bargaining with an ever more radical GOP over the big socio-economic issues than in actually trying to move the debate away from the neoliberal premises established in the Reagan/Clinton era. Basically, I consider the “centrists” to be a mortal threat to the longer term viability of the Democratic Party itself. The GOP‘s ability to fall back on nativism and the culture wars to whip up a frenzy among its electorate doesn’t seem to be lessening, but I’m not sure how the long term prospects are for the “centrists”’s “Well, at least we’re not at bad as the GOP” shtick, while they continue to pursue a Reagnist set of economic policies. ScepticWombat (talk) 17:26, 9 August 2020 (UTC) Favourite action movies of the 80's?[edit] I have a few in mind... — Unsigned, by: 2001:8003:59DB:4100:58F5:757B:1E27:59AB / talk - Disclaimer: Daily Wire nonsense. — Godless Raven talkstalkwalkbalk 🌹 06:26, 7 August 2020 (UTC) - It's tough for me to pick just one... for me, it's a toss-up between Robocop, Predator and Terminator.Bigwiggler (talk) 07:31, 7 August 2020 (UTC) - Deadly Prey is the greatest action movie not only of the 80's but ever, everything else is just pretentious wank Cardinal Chang (talk) 08:25, 7 August 2020 (UTC) - Of the 80s specifically? Robocop, obviously. Also, Shapiro's pathetic little hipster Breitbart hasn't collapsed yet? ☭Comrade GC☭Ministry of Praise 12:16, 7 August 2020 (UTC) - I'm assuming this article functions as some sort of test of manliness against overbearing "PC culture" (I'm not gonna click on the link). A lot of 80's action flicks had a lot of tongue in cheek cultural commentary that I'm sure many of these idiots missed.RipCityLiberal (talk) 15:31, 7 August 2020 (UTC) - The byline is "The Reagan era gave rise to masculine heroes who saved the day without regret or apology." So, pretty much. The actual article is paywalled, but in light of the byline, Robocop is a perfect choice as that satirizes Reagan era ethos quite a bit. I'll also echo Die Hard (which also satirizes machismo a bit) and Terminator (which doesn't, as far as I know). This was also the beginning of the peak of Hong Kong cinema and John Woo's A Better Tomorrow and Jackie Chan's A Police Story would be good to add. Soundwave106 (talk) 19:25, 7 August 2020 (UTC) - I don't care if Benny made this article, I'm still gonna reply: Predator, and the original Rambo.— Jeh2ow Damn son! 18:07, 7 August 2020 (UTC) - As long as you use ad bloc... I prefer to not give traffic to garbage fires. — Godless Raven talkstalkwalkbalk 🌹 18:45, 7 August 2020 (UTC) - Starship Troopers is still the best movie, even if it's from the 90s. ☭Comrade GC☭Ministry of Praise 19:31, 7 August 2020 (UTC) - That's a great one. The eighties was a good decade for movies. If you like to laugh: Ghostbusters. If you want to be frightened senseless: Aliens.Ariel31459 (talk) 21:50, 7 August 2020 (UTC) - Did you mean Alien? Because Aliens wasn't especially scary. A couple jumpscares and some gore, but not like... dread? ikanreed 🐐Bleat at me 21:55, 7 August 2020 (UTC) - I like Raiders of the Lost Ark. Also Indiana Jones 3 if that counts too. Chef Moosolini’s Ristorante ItalianoMake a Reservation 00:16, 8 August 2020 (UTC) - i will go for big trouble in little china today. is the thing an action movie? probably not 80s action movie enough. but for movies that you can truly say are 80s action movies, if it isnt starring arnold schwarzenegger then its not an 80s action movie, its just an action film released in the same decade. schwarzenegger is the 80s action movie. AMassiveGay (talk) 11:10, 8 August 2020 (UTC) Both great films! Junfa (talk) 20:48, 10 August 2020 (UTC) ~On dropping in to the Saloon Bar *[edit] The humanity is never explicit. The arguments are great, *but this is the saloon bar. I'm not arguing for a thing as sacred, but when it's really combative for the sake of combat, it's not a place I want to be. Gol Sarnitt (talk) 05:26, 8 August 2020 (UTC) - Did something happen? Gunther1987 (talk) 09:16, 8 August 2020 (UTC) - I did your mom. Everybody's mom, actually. That's why everybody is so on edge-Hastur! (talk) 12:58, 8 August 2020 (UTC) - Got nothing better todo than posting "yo momma" shit? And I can understand the edgyness. Being 13 and all. Posting constantly on 4chan's /v/.. Gunther1987 (talk) 15:29, 8 August 2020 (UTC) - Maybe it's an obsession brought about by an absence of sorts. Like most "edge-lord"s, they weren't born, merely shat into existence, with a "Mommy" fixation hardwired Cardinal Chang (talk) 22:18, 8 August 2020 (UTC) - I drank a lot. And I drink a lot a lot. I'm sorry if I said anyone was 13 and posting on 4chan, but I'm pretty sure I would not have said that even while blacked out. Not even on my death-bed would I use such shallow insults. Gunther, your mom called me and asked if I could tell Cardinal to stop calling out your name in bed when she's pegging him. Cardinal, she's his son, that's too weird for her. I hope you understand. I'm sorry, but your mom and I are friends and we talk about you. What was your point? Because I'm miles past mine now. Gol Sarnitt (talk) 06:26, 9 August 2020 (UTC) - Ah the Cameron Booze Diet, good luck with that. One day you might even find a sense of humour Cardinal Chang (talk) 14:29, 9 August 2020 (UTC) - I'm working away from the drinking, but I don't know what Cameron means. I assume it's devastating and I'll check, not bet. I would never want to find a sense of humor without being willing to throw my last sense out. I wasn't trying to be mean to you. Take these jokes, I don't need them. Gol Sarnitt (talk) 03:19, 11 August 2020 (UTC) This site is actually the perfect place to ask this and since I don't get any results when typing it in the search bar...[edit] What is Sapiosexual? This is the first time I encountered this word. Gunther1987 (talk) 09:26, 8 August 2020 (UTC) - sapiosexual is when someone finds intelligence a fuck factor if you catch my meaning... 104.243.212.165 (talk) 10:27, 8 August 2020 (UTC) - its something some people say when they are really looking at ya tits. AMassiveGay (talk) 10:44, 8 August 2020 (UTC) - blah - Isn't that kind of dangerous when a denialist or a crank is Sapiosexual? They could find Alex Jones hot as fuck... @AMassiveGay lol. Gunther1987 (talk) 11:01, 8 August 2020 (UTC) - Someone with the (lack of) intelligence to be attracted to the person claiming to be a sapiosexual. - Or someone who is attracted to soap. Anna Livia (talk) 18:43, 8 August 2020 (UTC) - In principle it's a thing. Many people are attracted to things that are connected in some way to intelligence, e.g. sense of humor. In practice it usually means "I'm super pretentious". Not that being pretentious is the worst thing in the world. ikanreed 🐐Bleat at me 20:01, 8 August 2020 (UTC) - In a linguistic sense, it would solely require Sapien. It's unusually broad. Gol Sarnitt (talk) 05:58, 9 August 2020 (UTC) - And I'm drunk, I swear I read ikanreed's post, but I lost it within a minute, I'm very very drunk. This is why I avoid the weekends. 06:04, 9 August 2020 (UTC) - So drunk your signature broke Fowler (talk) 09:17, 10 August 2020 (UTC) - Welp. Yep. Can I amend that with a signature? Gol Sarnitt (talk) 03:20, 11 August 2020 (UTC) Damning expose on CHAZ/CHOP[edit] The left really needs to start self-policing. Sick of ivory tower liberalism from soft-science majors-Hastur! (talk) 00:01, 8 August 2020 (UTC) - Yeah, abolishing the police is not a good idea. Another example of failure of a certain ideology on the left. — Godless Raven talkstalkwalkbalk 🌹 00:07, 8 August 2020 (UTC) - I wonder why they might have a problem with those cops... I really do wonder... I'll also just leave this here... Oh, and given the political makeup of the US, it's highly dubious that most of those protestors are/were anarchists, despite what Trump says. ☭Comrade GC☭Ministry of Praise 00:34, 8 August 2020 (UTC) - This isn't about abolishing or even reforming the police. This is about the left's refusal to acknowledge its worst elements.-Hastur! (talk) 01:02, 8 August 2020 (UTC) - Somehow @Hastur, I really doubt that. Again, given the political makeup of the US, most of those protestors were Liberals. You know, centrists. Further, I really can't take you seriously when you barf out the whole "See, here's what happens when you push back against the cops" (who left that area on their own) and then go "well actually, it's not about defending the cops, it's not about upholding the broken system that lets cops murder people in broad daylight, it's about this minority of people who though they don't have much political sway at the moment are totally the problem." Do you see why I'm kind of not taking you seriously now? ☭Comrade GC☭Ministry of Praise 01:30, 8 August 2020 (UTC) - Also, again, the cops used tear gas in residential areas, in open violation of city laws. I'm sorry if people didn't want to get gassed so you can play white moderate. ☭Comrade GC☭Ministry of Praise 01:32, 8 August 2020 (UTC) I see, the CHAZ was actually really centrist. [48] Quoting Vox here: — Godless Raven talkstalkwalkbalk 🌹 01:35, 8 August 2020 (UTC) - Oh what? It wasn't just anarchists like you originally said? You're now backpedaling? WHAT?!?! ☭Comrade GC☭Ministry of Praise 01:48, 8 August 2020 (UTC) - When did I say it was only anarchists? — Godless Raven talkstalkwalkbalk 🌹 01:51, 8 August 2020 (UTC) - "Yeah, abolishing the police is not a good idea. Another example of failure of a certain ideology on the left." Raven, August 2020. The CHAZ is a lawless wasteland run by warlords! This is why you should let cops murder black people! Tucker Carlson, June 2020. I dunno man, maybe there's a reason I tend not to trust people dissing the CHAZ, especially given it's been out of commission since the first of last month. ☭Comrade GC☭Ministry of Praise 02:07, 8 August 2020 (UTC) - No, but you do use some of the same rhetoric. Nice strawman though. ☭Comrade GC☭Ministry of Praise 02:17, 8 August 2020 (UTC) - The New York Times is generally considered a left-leaning paper... not sure that this is a great example of "the left" refusing to acknowledge its worst elements. - At any rate, my understanding is that CHAZ formed due to aggressive police tactics that actually transformed George Floyd protests into a community effort to keep aggressive police out of the neighborhood. As far as I'm concerned, the business owners have no one to blame but the police for what happened. Of course there are agitators and opportunists that would take advantage of the situation. Duh. But if the police didn't treat every single little thing like it was a war on something and focused on crowd management techniques for protests instead of shooting off as much crap at protesters as possible, CHAZ would not have happened. The New York Times is willing to acknowledge the looters and troublemakers. Some of the right is also willing to acknowledge troublemakers in the police (see libertarian places like Reason.com). And then there's places like Breitbart and Fox News. Le sigh. Soundwave106 (talk) 04:55, 8 August 2020 (UTC) - I found posts from Oxy calling it a "Centrist Rag". So, the NY Times isn't "Centrist" then (I'm not american, so I only know that The Daily Stormer is fucking garbage thanks to RW)? Gunther1987 (talk) 10:58, 8 August 2020 (UTC) - Zheesh. People are throwing around left, centrist and right on the Saloon for the last few days, enough to last a life time. Give it a rest. The Times has columists and Op-Ed writers who tend to be favourable towards progressive and liberal policies but not all of them and not always. That's about the most you can say to generalize about a paper. There are no "left" or "right" papers in any meaningful way. Just a tendency to be sometimes favorable towards some policies and leaders. ShabiDOO 11:51, 8 August 2020 (UTC)d - And "the left needs to start self-policing", it's phrases like this which demonstrate why people should seriously stop referring to "left" and "right" like they are groups. They are not. How many times does this need to be pointed out. They are vaguely defined spheres on two ends of an arbitrarily divided spectrum. People who have nothing in common except the fall to one side of a subjectively drawn line. "The left" doesn't exist as an entity, meaning the "left" doesn't need to do anything. Most certainly not "police" people in their arbitrarily defined group to say or not say, to do or not do anything. ShabiDOO 11:56, 8 August 2020 (UTC) - I personally think the NYT is quite centrist. They loathed Bernie in the primary. They hire columnists like Bret Stephens ("the disease of the arab mind") and Bari Weiss (who defended Tom Cotton's fascist Op-Ed to crush the protesters with the military). — Godless Raven talkstalkwalkbalk 🌹 12:03, 8 August 2020 (UTC) - Media bias has them as left-center. I think that's correct. Since the Internet has forced newspapers to chase subscriptions instead of advertisements, I actually think they've shifted a little to the populist left over the years. And yes, using a single term like "left" obscures a lot. In particular, the New York Times seems to aim for the college educated / "white collar", urban market that has some sympathy for social justice and safety nets, but does not want to tear the system apart. The NYT crowd probably wouldn't get along with the Chapo Trap House crowd very well. In the past, liberal leaning papers usually hired conservative columnists to try and provide "balance" -- usually college educated neo-conservative types. I expect less of that in the future. Bari Weiss was chased out of the New York Times pretty much because of her severe mishandling of the Tom Cotton affair as I understand it, which is fine, she can go be a Zionist fascist elsewhere. Other conservative columnists these days have become very loud Never Trumpers (I'm thinking Bill Kristol and Jennifer Rubin and the like) and we'll see what happens post Trump to these sort of people. Soundwave106 (talk) 18:37, 8 August 2020 (UTC) - I wonder if in a few years we'll look back on these protests as something similar to what happened to Occupy. Occupy's biggest failing was basically being an open tent for literally anyone who complained about "the 1%" without rhyme or reason as to why they might not like the 1% (Jason Kessler anyone?). The Floyd protests, at least from my view seem to be characterized by a mixture of genuine "the police are kinda being shitty to black people, do something about that" to "this is the anarchist revolution we've been waiting for" to "this is not about black people, this is about the working class against the ruling class", and due to a lack of concrete leadership on these protests the entire message gets muddled so that anyone with a bone to pick on any of these statements can find something to hate about a certain section of the protests. As for people like Kessler, while I don't think we'll start to see more people like him pop up out of these protests (due to these being more anti-racist in nature in public perception), I have no doubt that certain leftist grifters with fashy ties have been feeling extremely bolstered by these protests since the entire "working vs ruling class" thing has been picked up by non-grifters as well, and from what I know they are the ones that pushed that variation on the message to start with. - Another reason I feel that we can compare this to Occupy is that the message that the overwhelming majority adopted (Abolish the police), is somewhat asinine in that it kinda makes it hard to bring people in agreement with you. Like, yeah the police in the US are extremely overfunded, behave like the bullies in the playground and so on and so forth, these are all valid issues to have, but yelling "Abolish the police" kicks people who see the police as well, regular law enforcement (and yes this is mostly white people but hear me out) against you in defense because then you make them confront questions like "so if you want to get rid of the police, and someone robs my house while I'm not at home, then I can't go anywhere for that robbery?" for instance. It also is something that could easily have been reworded into a less agressive message, something like "Stop overfunding the police" would just as easily fit on a sign/work on a slogan and you'd be able to get a lot more support for that since unlike Abolish The Police, it introduces the relevant nuance to it. - To finally conclude my thought train here, I think one might also add to the discussion that a lot of the protestors online have been... rather incompetent. I get that "social media is not the real world", but if I look at how these protests have gone down on my social media channels, it mostly boiled down to: - Look, my tweet about [unrelated thing] got popular, time to add a reply saying BLM to it since give money to protestors. - Bait and switch: Open with one interesting thing, then in the next tweet post that you should totes give money to a large number of funds. - When someone has legitimate questions about some of the protests, refusing to assume good faith and just going for cheap dunks since "don't you support the lives of black people". - Sticking up for horrible people doing stupid things in the protests. This takes the shape of blaming things on "external agitators", the police going undercover, "you don't get to decide how people complain about things" and so on and so forth. Like, it's not by any means hard to admit that yeah, there are some shitty assholes in these protests and no, you don't think they did the right thing, but for whatever reason a lot of people seem incapable of admitting it. - That's my current thought train on these protests, and I'm having the feeling that we'll see things (perhaps sadly) fizzle out in the next few weeks. As for here, I fully expect an edit dispute that will almost tear apart the wiki for when we decide to start writing our article on these protests, but that seems like a regular tuesday for me. Techpriest (I am Alpharius! / / / ) 12:12, 8 August 2020 (UTC) - @The Crow I really hope not, for our sake. What happens later down the line isn't pretty. ☭Comrade GC☭Ministry of Praise 12:36, 8 August 2020 (UTC) - Alright, C-Dawg gets it. We've had people defending looters in all this, ffs. Looting a Target doesn't accomplish shit. Just makes the movement look bad. And instead of condemning the violent elements in the protests, idiots just say they're voicing their frustration. And then people are saying things like "All Cops Are Bastards," which is a horrendously bad take. All cops? All of them, really? I'm sure it feels very cool and edgy to say that but these are real people and saying combative crap like that only divides the country further. We can't have legitimate protests coopted by radicals and opportunists-Hastur! (talk) 12:50, 8 August 2020 (UTC) - Firstly, yeah I did defend vandals and looters. No, I never said "ACAB". Once again, you mash multiple users into one another, just to make them easier to attack. Here's the main reason why I defending the vandals and the looters. here's a picture here's another picture. Show me which are protestors and which are rioters. Download them and circle the ones you think are rioters via MS paint or something. If you can't, then you need to admit that the distinction is meaningless, especially given the rhetoric coming Barr and Trump's offices. ☭Comrade GC☭Ministry of Praise 13:16, 8 August 2020 (UTC) - So just to be clear, when I said people, I wasn't talking about people on RationalWiki. I was talking about people in general, like the ones that show up on my facebook feed or write and comment on the blogs I follow. Never said I was talking about people on RationalWiki, actually.-Hastur! (talk) 13:18, 8 August 2020 (UTC) - That's actually worse. You accuse me of saying "ACAB" because you don't like shit you see on Facebook. Even though, both here and on the Discord servers I've been hostile towards the cops, but explicitly anti-ACAB. Great, just fucking great. ☭Comrade GC☭Ministry of Praise 13:22, 8 August 2020 (UTC) - @GrammarCommie I'd rather it not go that way either (because BLM is a good cause in and of itself), but my hindsight for the past two months of protests + evaluating general sentiments on various social media kinda seems to point at there starting to be a similar reaction. I'd personally say that the only reason it hasn't fizzled out yet like every other stupid thing that has happened in the past 4 years is because of Trump's tedency of saying dumb things about the protests (and I think one can argue that he's doing that so that fewer people pay attention to how shit he's at handling COVID-19) whenever it seems like things are calming down again. Techpriest (I am Alpharius! / / / ) 14:37, 8 August 2020 (UTC) - @The Crow Hey, I don't want to have to deal with the the black people in this country getting so angry and jaded that they go full on insurgent either. But that's what happens when the minority group's concerns are downplayed. And it won't take much more to ignite that powder keg. I can tell because of the initial riots, and what the people in that neighborhood said to defend them. As to Trump, yeah. He wants them to go that route. He needs an enemy to justify his regime's brutality. That's why he keeps calling them violent terrorists. But trying to talk down to the protestors, only really benefits one side, Trump's. - To quote ML."" - When you condemn BLM, when you try to idealize the protests, you only carry water for their opposition, and undermine their efforts. This is what I pointed out above with Raven. When he says "The CHAZ proves why we need the cops" he's echoing a sentiment similar to bad faith actors like Carlson, who make that same argument, even though the creation of the CHAZ was a direct result of police abuse. When you say "Well, I support the peaceful protestors, but anyone who doesn't fit my idea of a peaceful protestor is illegitimate" you play into other similar talking points. To truly support the protestors, to truly hear them, you must accept both the good and the bad, the radical and the moderate. And you must understand that if these current protests fail, if things do not improve by a large enough margin, then they'll stop marching with signs, and start marching with guns. This is how these things play out. Eventually, they lose faith in the hand of peace, and instead pick up the sword of war. ☭Comrade GC☭Ministry of Praise 15:20, 8 August 2020 (UTC) - Let me be clear first and foremost, I don't oppose nor condemn BLM. BLM is absolutely something important and the police have serious issues that need to be solved. Raven's echoing of bad faith far right arguments is... concerning, but I'll admit that I hadn't picked up on that one entirely (I frankly have better things to do than weed through torrents of far right dogcrap). Trump obviously wants them to go violent, no disagreement there. As for the MLK quote, yeah I'm familiar with it, and I think King does have a point, but the issue I at least have with your final line and this response as a whole, is that if you support the protests, you must accept everyone in them, is that you basically end up forgoing any kind of nuances. I don't really have an idea of an "idealized protest", every protest probably ought to be shaped in the way that works best for it, but as the saying goes: You don't need to be a plane pilot to realize that a plane stuck in a tree is probably a bad thing. I am not a huge fan of forgoing any kind of self-critique for some sort of Greater Good and I have the idea that due to the (not unfounded) fear that the right wing will just do lazy critiques, that any critique must be a bad faith critique is something that has started to permeate throughout the protests. I tried expressing the sentiment of the Greater Good during the Dem primary in trying to convince people online that the Rogan endorsement wasn't the PR disaster it turned out to be (that it might bring in new voters who otherwise wouldn't consider voting for Sanders), and all I feel that led to is me tacitly providing agreement to dirtbaggers invading lefty spaces and that leading into the entire bullshit drama surrounding Bernie's inability to unify the progressives after Warren dropped out, if that makes sense. I've personally come to the conclusion therefore that if we ignore major issues in a certain group and just claim that as long as they support a Greater Good that they must be fine to walk alongside you, all you're doing is tacitly agreeing to the major issues. - With that stated, I genuinely do hope that change comes and that these protests won't be necessary anymore rather than them just fizzling out, only for them to get kicked up the next time some black guy gets shot by the police. I'm not in the US and I have rather small disposable income, so my ability to say or do much is relatively limited (aside from getting rid of bigots in online communities where I have the power to do so) aside from trying to talk with people and get them on-board with the ideas of BLM if at all possible, but at the same time I also cannot in good faith say that I support people who do actions that I would consider morally condemnable in any other situation. Techpriest (I am Alpharius! / / / ) 15:47, 8 August 2020 (UTC) - Firstly, to Raven and Carlson echoing the same points. I want to be explicitly clear that I'm not trying to call Raven far-right. I am however trying to point out the narrative his position is feeding into. Even as Barr ordered troops to forcibly clear Lafayette square, Trump tried to hairsplit the protests into "peaceful protestors and a angry mob". (The relevant clip starts at 34 seconds.) This not about a "Greater Good", but about understanding the dynamic between the protesters and those who seek to undermine them, and how we plebs fit into it. To the dirtbaggers, they are part of the left. They aren't invading, they are a part of that ecosystem. To push back against them, you have to first acknowledge that. In fact, one could argue the same for the worst elements of the protesters. Solidarity must come first, so that critique lands all the harder. I can't push back against Farrakan's influence for example, if I simply condemn others for not participating in the Gandhi Trap. He's respected by parts of the Black Community partly because he fights for civil rights (or at least appears to). To get rid of his influence, I have to get better results and well... Have you seen how the protests were covered? Lots of headlines about property damage, and detached headlines about protests occurring, very little actual calls for accountability. ☭Comrade GC☭Ministry of Praise 16:16, 8 August 2020 (UTC) @The Crow I cited Vox, btw. You know, the centre-left media outlet in the US? In case you missed it: [49] This is from someone who witnessed the CHAZ, speaking to Vox. If quoting Vox reporting counts as echoing bad faith far-right arguments, cool. Didn't want to respond to this thread anymore, since GC was unable to find the quote of me saying, allegedly, that "all of CHAZ were anarchists" (yet GC was really quick to say that it was "liberals", without evidence), but then I am getting compared to Tucker Carlson, so I just wanted to point that out. - So let me get this straight - a Defund the Police protester gets stabbed, and immediately starts screaming, "Call the Police!" What am I missing here? nobsTo Bob Mueller:Every dog has his day. 18:12, 9 August 2020 (UTC) - When it comes to Dr MLK Jr, I think we've fallen into the all too common trap of declaring that because the person was a net positive, that everything they were and stood for must also be "good". The reality is that humans are complicated, and that "good" isn't always agreed upon even long after the fact. In the case of MLK, he accomplished a lot of good things, enough that a national holiday in his name is justifiable, but he came with a lot of baggage. He was a devoutly religious man, which may be "good" to many people but I'm sure most of us here would disagree with him on that. He cheated on his wife, and while his supporters will try to gloss over that or pull out some BS about his wife was totally into it and for the most part, people here probably won't give too chits about extramarital sex, but for a religious leader to commit adultery is actually a huge issue. He had a lot of uncomfortable ties to Communists; the FBI wasn't keeping a close eye on him purely out of racism, but out of justified paranoia, even more justified when you realize that the Civil Rights Movement was less "infiltrated" by the Russians so much as it was created by them. He was not the moderate answer to Malcolm X, but rather, Malcolm X existed to make MLK look more palatable to the public. He was a "net good", but that doesn't mean he was all good, and likewise, him having flaws does not mean that what he accomplished was a "net bad". - In terms of the "white moderate" speech, well, he's basically declaring "either you are with us or you are against us". It's a Manichean worldview that fails to understand nuance and tens to create more enemies. In the universe where the FBI intervened instead of merely standing by when he was murdered, I'm not so sure that the ultimate legacy he would create in that universe would be lauded anywhere near as much as it is in our own. CoryUsar (talk) 21:44, 9 August 2020 (UTC) - @CorruptUser The point. - Your head. ☭Comrade GC☭Ministry of Praise 21:58, 9 August 2020 (UTC) i dont know what people were expecting from these protests, considering how quickly they flared and the sheer scale of them, and especially considering the reasons for the protests in the first place. the organisers of the initial protests probably did not anticipate the scale. it is understandable if they have been chaotic. it is understandable that there has been some violence - anger and frustration at continued injustices is what brought people to street. emotions that can get away from us very easily. but for the most part the protests have been non violent. there has been looting. in such a chaotic setting there was always going to be. there are always opportunists who will try and take advantage. looting, and other crimes and violence not connected to the protests, but being used for the opportunity the situation presents. but its not all widespread it seems. there have been reports of fringe groups stirring things, trying escalate violence for what ever reasons. again, they are there, but not all widespread. and all going on with confrontational riot police pepper spraying and beating down crowds. at point, why wring our hands at all this? various figures in the protests have early on condemned violence and looting. do we need a further condemnation for every instance we see? we surely dont need to hear a response each time a window gets smashed. its not that widespread and was always going to happen but calls by some for blm or the left or whoever to address such criminality are about cementing an association of criminality with blm and the left. its a smear that we should not respond to. blm are not responsible everything that happens, they cannot have complete control over protests of this scale. lets not forget what spurred all this - yet another black man murdered by police. a horrific symptom of the systemic racism faced by black americans. murdered by police for decades with impunity, denied access justice while being incarcerated in grossly disproportionate numbers, disadvantaged in education, heath, financial - in every sector of society, every part of american life. but its some looters that has us worried? we are concerned that some of the rhetoric might a bit aggressive? we have been here before. there has been outrage at police brutality before. there have been riots before. there have been calls for reform, there have been reforms. and here we are again. another black man killed by police. asking nicely hasnt seem to have done much. the bare minimum of reforms that could make a difference will need more than asking pretty please. pressure needs to kept up to achieve anything more than doing just enough to mollify the masses. but ive said elsewhere that reform wont rebuild trust in police that will needed for them to work. its a half measure doomed to be watered down and we will be here again. as for the the CHAZ business, again what did anyone expect? its formation was not planned, coming about because the police pulled out. whatever it turned out to be, the press spotlight and threats from those in authority to violently take it back ensured opportunists and those spoiling for a fight would flock to it, exacerbating a challenging situation. the negative attention it got was far out of proportion to its place in the protests as a whole and it is not indicative of any short comings in any of the perceived ideologies that have been claimed by or assigned to it. it is nothing what abolishing the police would look like either, seeing as the police just pulled out leaving no institutions to replace them. its just a further distraction from the issue of police brutality and systemic racism. AMassiveGay (talk) 14:12, 10 August 2020 (UTC) - ☭Comrade GC☭Ministry of Praise 15:02, 10 August 2020 (UTC) - There are plenty of things to criticize about this movement, but this ain't it. CHAZ/CHOP was limited to one city, and wasn't exactly a unified action. Many BLM supporters said they lost the plot after a week. Also comparing left wing violence to right wing violence is like comparing a NERF gun and an AK-47.RipCityLiberal (talk) 16:36, 10 August 2020 (UTC) - Only one is subject to government restriction? 192․168․1․42 (talk) 17:47, 10 August 2020 (UTC) So Vox is echoing far-right talking points?[edit] I just wanna know whether Vox is not left-wing enough for some people at RationalWiki. — Godless Raven talkstalkwalkbalk 🌹 17:57, 10 August 2020 (UTC) - Vox isn't perfect, and can you seriously piss off for once? — Oxyaena Harass 18:20, 10 August 2020 (UTC) - Not yet. — Godless Raven talkstalkwalkbalk 🌹 18:41, 10 August 2020 (UTC) - what is it you think vox is saying, and why do you think it is in agreement with what you have been saying? if you think it is saying chaz is or was over run with with anarchists, it does not. it says some people were floating the idea of 'more of an anarchist space'. the full article makes no more claims beyond it being an idea being floated, nor tells of the political affiliations of anyone within. the article merely says they are considering their options, believing the police will be moving in at any moment. the idea it was all an anarchist stunt or takeover or that anarchists were calling the shots or have in any way organised and controlled events are the right wing talking points i am assuming you have been accused of regurgitating. the vox article does not support your case. in the wider picture of protests and police brutality and systemic racism, chaz is a pointless side show and its not all about you AMassiveGay (talk) 19:10, 10 August 2020 (UTC) - Is x left-wing enough? is such an asinine question. Left right is a spectrum whose only actual value, in an intellectual conversation, is to place political parties on a politcal spectrum. Turning it into some sort of formula for an ideological competition is rediculous. Left vs. right does not equal progressive vs. regressive, liberal vs. conservative or democrat vs. republican. ShabiDOO 19:21, 10 August 2020 (UTC) - Goddless Raven, listen to me. You need to stop asking disingenuous questions, then when people answer you, refusing to understand what they say. It's absolutely trolling and you've got to stop. You're shitting up the bar. ikanreed 🐐Bleat at me 19:50, 10 August 2020 (UTC) - @GR And why was this fucker taken out of sysoprevoke? — Oxyaena Harass 20:05, 10 August 2020 (UTC) - Here's a thought. The cops have fucked off after gassing you and your fellow protestors, plus civilians (including children), and also after you guys routed them back to their station where they then cowered like the dipshits they are before running away. The neighborhood needs system of enforcing the peace. No one wants to form a standard hierarchical leadership structure, because of the cops and neo-nazis who keep coming in and attacking people. Most of you are pretty moderate, but some of you are maybe PolSci students. So some of you (the hypothetical PolSci students, or someone else with the relevent knowledge) suggest elements of a decentralized administrative system which calls for greater civic participation and has ideas on a non-cop peacekeeping system in order to meet the needs of the now semi-autonomous area. You then form a semi-autonomous liberal hippy commune. I dunno, seems plausible to me. ☭Comrade GC☭Ministry of Praise 21:25, 10 August 2020 (UTC) - Vox is NBC bullshit re-packaged for a younger audience. What? You think true blue communists have the capital to reach as far as Vox has? nobsBlack Guns Matter 21:37, 10 August 2020 (UTC) - Rob shut the fuck up adults are talking.-RipCityLiberal (talk) 21:52, 10 August 2020 (UTC) You know, the funny thing is how I didn't even insert the political axis as a thing until someone (GC) did in order to complain about how I am supposedly "echoing far-right talking points" by merely quoting Vox's reporting that yes, there was a power struggle within the CHAZ by (I assume mostly privileged white, middle-class teenager) anarchists trying to redirect attention from systemic racism, police violence and the murder of George Floyd to their... "cause" (which I don't even recognize as a cause, since it lacks any serious nature to it). You think the left vs. right spectrum is nonsense? Good, take it up with GC, who assumed without any evidence that the CHAZ was inhabited by "centrist liberals"; yet, when I gave evidence that some faction within CHAZ was far-left larping, then we have a problem? Okay. Secondly, you can look up all of my replies: I never said it was all anarchist. I posted an article by Vox because Vox is widely regarded as not being far-right; my original question being a facetious counter to GC's and Crow's assertion that I am "echoing the far-right" when, given by the account of the person who was involved with the shitshow that is CHAZ, it had a significant anarchist influence. Unless you have better evidence, I take it that none of you are accusing Vox of being "fake news"? Because if quoting Vox is now considered far-right, I am sorry, you might've lost the plot. Now, it is funny how ikanreed is complaining about me "shitting up" the bar when someone just called me a "fucker" and is consistently targeting me with verbal attacks. Gotta say, my haters don't really care about any of this as long as it is to attack the bigly evil raven. — Godless Raven talkstalkwalkbalk 🌹 23:32, 10 August 2020 (UTC) - That being said, can any of you answer? Is Vox echoing far-right talking points? Yes/No? — Godless Raven talkstalkwalkbalk 🌹 23:41, 10 August 2020 (UTC) - GR your I'm a poor little victim complex was tiresome already like a week ago. Give it a rest and learn to take responsibility for doing something silly, provocative or cringe-worthy.ShabiDOO 00:08, 11 August 2020 (UTC) - Godless Raven is an iconoclast and believes it is important for people to recognize the flaws in their heroes and even their ideologies. I don't think there's anything wrong with that. If you object to his iconoclasm, the simplest, most effective solution is not to reply.-Hastur! (talk) 00:12, 11 August 2020 (UTC) - As usual, Hastur can be counted on to provide way-too-generous "summaries" of GR's actions.-Flandres (talk) 00:28, 11 August 2020 (UTC) - Indeed. His final question "is Vox parroting far-right talking points" or whatever, is a totally valid fair question. I don't know the answer. But the "is it left enough" was a ridiculous question asked to provoke not gain any information or knowledge. Try to spot the difference Hastur. ShabiDOO 00:33, 11 August 2020 (UTC) - Wow, Shabidoo finally concedes on anything! And of course, Flandres is here to malign me, as usual. Otherwise, nothing out of the ordinary here, CIA. It's just another day on RationalWiki. — Godless Raven talkstalkwalkbalk 🌹 00:34, 11 August 2020 (UTC) - People consistently disagree with you on a similar set of topics that you constantly bring up on a site that often encourages dialogue with people you disagree with! Good job, GR! You've found the thread that brings the fiendish conspiracy to destroy you all together!-Flandres (talk) 00:39, 11 August 2020 (UTC) - Thank you, very kind of you Flandres! — Godless Raven talkstalkwalkbalk 🌹 00:45, 11 August 2020 (UTC) - You know, I demonstrated this before you brought up Vox. Maybe you should improve your reading skills on certain subjects eh? Anyway, learn to read, and don't put words in my mouth. ☭Comrade GC☭Ministry of Praise 01:04, 11 August 2020 (UTC) What do you think you demonstrated, GC? You have yet to admit that I never said CHAZ is "all anarchist". — Godless Raven talkstalkwalkbalk 🌹 01:07, 11 August 2020 (UTC) - " Another example of failure of a certain ideology on the left." Shut up, you selectively disingenuous shitheel. ☭Comrade GC☭Ministry of Praise 01:47, 11 August 2020 (UTC) - Aside from the personal attack, if I point out the failure of the anarchist faction of CHAZ, does that mean all of CHAZ is far-left? It doesn't make sense. Do you at least retract saying that CHAZ is made up of liberals/centrists? — Godless Raven talkstalkwalkbalk 🌹 01:56, 11 August 2020 (UTC) - No, I do not retract my statement, because you didn't say "Ah, so some of those ideas didn't work out that well due to X, Y, and Z factors" You said, and I will quote you again (much more honestly than you've been quoting Vox, since you originally brought it up to dispute my statement that the bulk of the protesters were Liberals, aka a mainstream position), "Another example of failure of a certain ideology on the left." See, when you said "a certain ideology on the left" your passive aggressive vagueposting made a demonstrable claim, which I and others have easily debunked. Further, you argued that the protesters shouldn't have run the cops out, a talking point I noticed you dropped after I pointed out their crimes. Is it really so hard for you to grow the fuck up and admit you were wrong? ☭Comrade GC☭Ministry of Praise 02:25, 11 August 2020 (UTC) Further, you argued that the protesters shouldn't have run the cops out ??? Are you hallucinating? Where did I say that? — Godless Raven talkstalkwalkbalk 🌹 02:48, 11 August 2020 (UTC) - "Yeah, abolishing the police is not a good idea." Now, given they didn't actually abolish the police, they just surounded the station and protested until they left, you might be tempted to argue semantics. But see, here's the thing. When you vaguepost, you don't actually involve these little nuances, nor do you really engage in anything constructive. You were wrong, admit it. I've owned up to mistakes in the past, and so has almost every user currently active on this site. Just fucking do it and get it over with. ☭Comrade GC☭Ministry of Praise 02:56, 11 August 2020 (UTC) - This isn't semantics, it's basic reading comprehension skills! Just because I say that the police shouldn't be institutionally abolished doesn't mean I am in favor of against CHAZ in principle. My only take on CHAZ is that I love far-left failings in real time and I find the memes about CHAZ and it's disorganized and mostly white teenager anarchist section hilarious! I support police reform, I support divesting from the police to fund social services that are far more lacking than a militarized police as it is now the case in the US. If you think those two statements are the same, you gotta read some books, man. — Godless Raven talkstalkwalkbalk 🌹 03:31, 11 August 2020 (UTC) - You literally responded to an article about the CHAZ with "Yeah, abolishing the police is not a good idea. Another example of failure of a certain ideology on the left." You vagueposted, and now you're arguing semantics. Just admit you fucked up. Why is this so hard for you? ☭Comrade GC☭Ministry of Praise 12:09, 11 August 2020 (UTC) - Here's the thing, the "anarchists" there weren't mostly white, and only a minority of them were actual anarchists. — Oxyaena Harass 10:13, 11 August 2020 (UTC) - How do you know? — Godless Raven talkstalkwalkbalk 🌹 10:15, 11 August 2020 (UTC) - If Anarchists aren't able maintain a safe society in a place where they make up a larger fraction than in the general population, that kind of disproves Anarchism as a legitimate societal ambition. The simple truth is that when Anarchists build a town up from scratch, they are never able to make it past the tribal stage of likeminded individuals, and when they take over anything larger, it all goes to shit. - I also don't understand why You, Oxyaena, would advocate for Anarchism. You may be right that under a Capitalist framework, autistic people have a disadvantage compared to non-ASD, but the harsh reality is that the difficulty in working with others or developing personal relationships means that autistic people have a disadvantage under EVERY framework, and in an Anarchist framework the same issues that prevent you from holding a job in Capitalism will only be magnified a thousandfold. CoryUsar (talk) 13:12, 11 August 2020 (UTC) there is a certain amount of dishonesty surrounding the reporting of chaz/chop and its dismantling that is difficult to take much that has been written on it seriously, its difficult to take the conversation here seriously, with same dishonesty. i dont mean the all the fake news and photoshopped images that sort to defame the thing early on, i refer to the dozens of articles, earnestly and hyperbolically, declaring it a failure of the left, a failure of anarchism, or of socialism, and a warning against abolishing or defunding the police. to be a failure of any of these things it would have needed to have been a determined and focused attempt at some kind of left wing utopia that could not overcome the inherent failings of their ideologies. this was never the case. its portrayed as some kind of dangerous threat to american values and indicator of the ruin to befall the us if these foolish reds had their way. the threat and significance has been built up to make its failing seem all the more damning, more crushing for these leftists, with a smug resounding told you so as they assert their world view is thus proven. this is false. there was no diabolical plan by a nefarious cabal of socialists, or anarchists, or communists or whoever the fuck you want to check off on your who you hate bingo card. there was no long term plan or strategy or even any plan at all. a disparate group of protestors found themselves in stand off and thought it would be jolly to declare a no police zone. the police will take back the ground in a couple of hours, enjoy it while lasts. it would have ended there had the mayor not thought it good publicity so put the police on a leash. the failure, such as it is for something never meant to last, lies with this same group of disparate protestors now suddenly having to form a government and provide amenities and security for a small town. thats a big ask when most had come to chant slogans at the police. there was never any cohesive group. never any clear goals. no clear leadership. with goodwill providing supplies, they could muddle along for awhile, but security was the big problem. fear the police would attack at any moment, opportunistic criminal gangs making the most of things. far right groups had attacked them. security was not one single entity but several groups. armed. untrained. unaccountable. no one in control, different groups butting heads, and the no police label attracts elements of human detritus. it was always going to implode. ideology had fuck all to do with it. it made good press and gave all the usual suspects a chance to lay into protestors that didnt make them look like racist. a few scary words like anarchist and socialist is all that was needed for people to create their own narratives in their heads. now its all over we are seeing lots of crowing and talk of the failure of this or a warning against that, pretending something significant had happened, or that we have learned important lessons. the reality is far less definitive. its mundane. too much was responsibility was given a group of random strangers there was never any reason to think were a cohesive unit that was up to the job. criticism has been harsh and too much was expected. in truth, it did well to last a month. it shouldnt have lasted a day AMassiveGay (talk) 13:46, 11 August 2020 (UTC) - I never understood the "educate yourself on X" mentality. Do you or do you not want to convince the person that your ideas are actually worth anything? First, oxy refuses to debate an actual socialist who has similar and maybe even harsher criticisms of Cuba and the other red fascist states; then, she tells people "go educate yourself"? Do you want anarchism to just pop into existence? There has to be some effort. — Godless Raven talkstalkwalkbalk 🌹 14:32, 11 August 2020 (UTC) - Also, I assumed that most of the anarchists in the CHAZ were white teenagers because (essential) working people actually don't have time for this nonsense. They aren't busy editwarring about some white cishet two centuries ago, they just want to survive and have a decent living. I am open to have my mind changed that it wasn't just a white teenager anarchist camp provided that there is evidence on the demographics of CHAZ. — Godless Raven talkstalkwalkbalk 🌹 14:34, 11 August 2020 (UTC) - Ah, I see you're trying to pivot again. Just say "I was wrong to try to imply that the CHAZ was an attempt at an anarchist commune, and to carry water for abusive cops." ☭Comrade GC☭Ministry of Praise 14:42, 11 August 2020 (UTC) Template:Verygood — Godless Raven talkstalkwalkbalk 🌹 15:07, 11 August 2020 (UTC) - Based on your passive aggressive and sarcastic response, I can only conclude that you are indeed ok with police abuse, and that you are too cowardly to admit such. ☭Comrade GC☭Ministry of Praise 15:24, 11 August 2020 (UTC)
https://rationalwiki.org/wiki/RationalWiki:Saloon_bar/Archive366
CC-MAIN-2022-21
refinedweb
45,204
69.11
Blogging Evolved: Application Aggregation Posted on Friday, May 13th, 2005 3:16 PMSo I've been exploring some ideas that I figured I'd write about here to see what's being done out there that I don't know about. The idea can be summed up in a phrase: "What's Notes is New Again." Right now blog tools allow you to create a "post" which is usually comprised of just a few fields: title, content, date, and maybe categories or tags. I've seen some other fields like media links as Enclosures (essential for podcasting), geotags for location, and there's been a sputtering effort to add in the iCal namespace for calendaring, but all these seem to be in separate worlds. In other words, you'd have a feed that's generally one thing or another, and not really combined into one thing. What I'm thinking about is a way of looking at "posts" or in RSS nomenclature: "items" as containers for arbitrary data in labeled fields, in a way that can be easily extended and re-used. Sort of like a "note" in Lotus Notes.. equasion,. So how do the aggregators "know" how to process the fields? Well, they don't automagically - the developer of the aggregator will decide to support some sorts of fields and just display the others. I can imagine some systems building a plug-in architecture which could read the various Fieldsets, but in general we'd all probably just do our best. Sort of how aggregators work right now. -Russ
http://m.mowser.com/web/www.russellbeattie.com/notebook/1008462.html
crawl-002
refinedweb
260
65.76
Py5Image.np_pixels[] Contents Py5Image.np_pixels[]# The np_pixels[] array contains the values for all the pixels in the image. Examples# def setup(): tower = py5.load_image("tower.jpg") tower.load_np_pixels() tower.np_pixels[:, ::2, 1:] = [0, 0, 0] tower.update_np_pixels() py5.image(tower, 0, 0) Description# The np_pixels[] array contains the values for all the pixels in the image. Unlike the one dimensional array Py5Image.pixels[], the np_pixels[] array organizes the color data in a 3 dimensional numpy array. The size of the array’s dimensions are defined by the size of the image. some of them like opencv will by default order the color channels as RGBA. Much like the Py5Image.pixels[] array, there are load and update methods that must be called before and after making changes to the data in np_pixels[]. Before accessing np_pixels[], the data must be loaded with the Py5Image.load_np_pixels() method. If this is not done, np_pixels will be equal to None and your code will likely result in Python exceptions. After np_pixels[] has been modified, the Py5Image.update_np_pixels() method must be called to update the content of the display window. To set the entire contents of np_pixels[] to the contents of another equally sized numpy array, consider using Py5Image.set_np_pixels(). Updated on September 01, 2022 16:36:02pm UTC
https://py5.ixora.io/reference/py5image_np_pixels.html
CC-MAIN-2022-40
refinedweb
213
51.34